forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·7.1 MiB·490f099·Tahinli·7 hours ago·322 commits
| 1 | use std::fmt; |
| 2 | |
| 3 | use crate::live::Topic; |
| 4 | use crate::state::AppState; |
| 5 | |
| 6 | pub use discussion_write::DiscussionWriteLayer; |
| 7 | pub use not_found_layer::NotFoundLayer; |
| 8 | pub use org_write::OrgWriteLayer; |
| 9 | pub use pull_write::PullWriteLayer; |
| 10 | pub use repo_moved::RepoMovedLayer; |
| 11 | pub use repo_settings_write::RepoSettingsWriteLayer; |
| 12 | pub use settings_write::AccountWriteLayer; |
| 13 | |
| 14 | /// Raised by `load_repo` when the requested owner/name is a past name of a repo the viewer may |
| 15 | /// read. The `repo_moved` layer turns it into a 307 to `location`. |
| 16 | #[derive(Debug)] |
| 17 | pub struct RepoMoved { |
| 18 | pub location: String, |
| 19 | } |
| 20 | |
| 21 | impl fmt::Display for RepoMoved { |
| 22 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 23 | f.write_str("repository moved") |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl std::error::Error for RepoMoved {} |
| 28 | |
| 29 | /// A plain-text download (a `.patch` or `.diff`) raised by a page handler that cannot return a |
| 30 | /// response of its own. The `repo_moved` layer turns it into a 200 with these bytes. |
| 31 | #[derive(Debug, Clone)] |
| 32 | pub struct RawDownload { |
| 33 | pub content_type: &'static str, |
| 34 | /// File name offered to the browser. |
| 35 | pub filename: String, |
| 36 | pub data: Vec<u8>, |
| 37 | } |
| 38 | |
| 39 | impl fmt::Display for RawDownload { |
| 40 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 41 | f.write_str("raw download") |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl std::error::Error for RawDownload {} |
| 46 | |
| 47 | /// Wakes the review-request list of `user_id`: a request was added or withdrawn, or the user |
| 48 | /// submitted a review (which clears their own request). |
| 49 | pub fn bump_review_requests(state: &AppState, user_id: &str) { |
| 50 | state.live.bump(&Topic::ReviewRequests(user_id.to_owned())); |
| 51 | } |
| 52 | |
| 53 | /// Wakes the review-request lists of everyone with a pending request on the pull request. Call it |
| 54 | /// after the pull closed or merged, which drops it from those lists. |
| 55 | pub async fn bump_pending_reviewers(state: &AppState, issue_id: &str) { |
| 56 | let names = match state.store.requested_reviewers(issue_id).await { |
| 57 | Ok(names) => names, |
| 58 | Err(e) => { |
| 59 | tracing::error!(error = %e, issue_id, "live: listing reviewers to bump failed"); |
| 60 | return; |
| 61 | } |
| 62 | }; |
| 63 | for name in names { |
| 64 | match state.store.user_by_username(&name).await { |
| 65 | Ok(Some(user)) => bump_review_requests(state, &user.id), |
| 66 | Ok(None) => {} |
| 67 | Err(e) => tracing::error!(error = %e, name, "live: loading a reviewer to bump failed"), |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | mod settings_write { |
| 73 | use topcoat::Result; |
| 74 | use topcoat::context::{Cx, context}; |
| 75 | use topcoat::router::request::{method, uri}; |
| 76 | use topcoat::router::response::Response; |
| 77 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; |
| 78 | |
| 79 | use crate::auth::current_user; |
| 80 | use crate::live::bump_account; |
| 81 | use crate::state::AppState; |
| 82 | |
| 83 | /// Wraps the requests under `/settings`. Only a POST does anything. Registered on the public router |
| 84 | /// in `boot.rs` and the test router. It sits on a path, so it runs inside the cookie layer (a |
| 85 | /// pathless layer would run outside it, where the session cannot be read). |
| 86 | pub struct AccountWriteLayer; |
| 87 | |
| 88 | impl Layer for AccountWriteLayer { |
| 89 | fn path(&self) -> Option<&Path> { |
| 90 | Some(Path::new("/settings")) |
| 91 | } |
| 92 | |
| 93 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 94 | Box::pin(bump_after_settings_write(cx, body, next)) |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | /// Bumps the viewer's topic once the handler has run. The viewer is read before the handler, so a |
| 99 | /// write that ends the viewer's own session (a revoke of the current one) still wakes the tabs. |
| 100 | async fn bump_after_settings_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { |
| 101 | if *method(cx) != Method::POST || !uri(cx).path().starts_with("/settings/") { |
| 102 | return next.run(cx, body).await; |
| 103 | } |
| 104 | let viewer = current_user(cx) |
| 105 | .await |
| 106 | .ok() |
| 107 | .flatten() |
| 108 | .map(|(user, _)| user.id); |
| 109 | let result = next.run(cx, body).await; |
| 110 | if let Some(user_id) = viewer { |
| 111 | bump_account(context::<AppState>(cx), &user_id); |
| 112 | } |
| 113 | result |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | mod repo_moved { |
| 118 | use http::{ |
| 119 | HeaderValue, |
| 120 | header::{CACHE_CONTROL, LOCATION}, |
| 121 | }; |
| 122 | use topcoat::Result; |
| 123 | use topcoat::context::Cx; |
| 124 | use topcoat::router::error::not_found; |
| 125 | use topcoat::router::response::Response; |
| 126 | use topcoat::router::{Body, Layer, LayerFuture, Next, Path, StatusCode}; |
| 127 | |
| 128 | use super::{RawDownload, RepoMoved}; |
| 129 | |
| 130 | /// Wraps every request (no path) so a `RepoMoved` error becomes a 307. Registered explicitly on the |
| 131 | /// public router in `boot.rs`: a `#[layer("/")]` would clash with the security-headers layer. |
| 132 | pub struct RepoMovedLayer; |
| 133 | |
| 134 | impl Layer for RepoMovedLayer { |
| 135 | fn path(&self) -> Option<&Path> { |
| 136 | None |
| 137 | } |
| 138 | |
| 139 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 140 | Box::pin(repo_moved(cx, body, next)) |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /// Turns a `RepoMoved` error from a handler into a 307 with the new location, and a `RawDownload` |
| 145 | /// into its plain-text response. Other errors pass through unchanged. |
| 146 | async fn repo_moved(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { |
| 147 | let error = match next.run(cx, body).await { |
| 148 | Ok(response) => return Ok(response), |
| 149 | Err(error) => error, |
| 150 | }; |
| 151 | let error = match error.downcast_cloned::<RawDownload>() { |
| 152 | Ok(download) => { |
| 153 | return raw_download_response(download).ok_or_else(|| not_found().into()); |
| 154 | } |
| 155 | Err(error) => error, |
| 156 | }; |
| 157 | match error.downcast_ref::<RepoMoved>() { |
| 158 | Some(moved) => { |
| 159 | let mut response = Response::new(Body::empty()); |
| 160 | // Temporary and uncached: an old name can be taken by a new repo later, and a browser |
| 161 | // that cached a 301 would keep sending its visitors to the renamed repo. |
| 162 | *response.status_mut() = StatusCode::TEMPORARY_REDIRECT; |
| 163 | // Owner and repo names are plain ASCII and the query came from a valid URI, so this |
| 164 | // only fails on a corrupt location; a 404 is the safe answer then. |
| 165 | let Ok(location) = HeaderValue::from_str(&moved.location) else { |
| 166 | return Err(not_found().into()); |
| 167 | }; |
| 168 | response.headers_mut().insert(LOCATION, location); |
| 169 | response |
| 170 | .headers_mut() |
| 171 | .insert(CACHE_CONTROL, HeaderValue::from_static("no-store")); |
| 172 | Ok(response) |
| 173 | } |
| 174 | None => Err(error), |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | /// The 200 response for a [`RawDownload`]. `None` when the file name is not a valid header value. |
| 179 | fn raw_download_response(download: RawDownload) -> Option<Response> { |
| 180 | let mut response = Response::new(Body::from(download.data)); |
| 181 | let headers = response.headers_mut(); |
| 182 | headers.insert( |
| 183 | http::header::CONTENT_TYPE, |
| 184 | HeaderValue::from_static(download.content_type), |
| 185 | ); |
| 186 | headers.insert( |
| 187 | http::header::CONTENT_DISPOSITION, |
| 188 | HeaderValue::from_str(&format!("inline; filename=\"{}\"", download.filename)).ok()?, |
| 189 | ); |
| 190 | headers.insert( |
| 191 | http::header::X_CONTENT_TYPE_OPTIONS, |
| 192 | HeaderValue::from_static("nosniff"), |
| 193 | ); |
| 194 | headers.insert( |
| 195 | http::header::CACHE_CONTROL, |
| 196 | HeaderValue::from_static("private, no-cache"), |
| 197 | ); |
| 198 | Some(response) |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | mod pull_write { |
| 203 | use topcoat::context::{Cx, context}; |
| 204 | use topcoat::router::request::{method, uri}; |
| 205 | use topcoat::router::response::Response; |
| 206 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; |
| 207 | |
| 208 | use super::bump_pending_reviewers; |
| 209 | use crate::live::{bump_list, bump_pull, bump_repo_pulls}; |
| 210 | use crate::state::AppState; |
| 211 | |
| 212 | /// Which topic a POST under the pulls paths writes to. |
| 213 | enum Written { |
| 214 | /// A write to one pull request (`/{o}/{r}/pulls/{n}/...`). |
| 215 | Pull { |
| 216 | owner: String, |
| 217 | repo: String, |
| 218 | number: i64, |
| 219 | }, |
| 220 | /// A new pull request (`/{o}/{r}/pulls`). |
| 221 | New { owner: String, repo: String }, |
| 222 | /// A repo-wide change the pulls show: a label or milestone edit. |
| 223 | Repo { owner: String, repo: String }, |
| 224 | } |
| 225 | |
| 226 | /// The write a request makes to the pull side, when it is a POST that can change one. |
| 227 | fn written(cx: &Cx) -> Option<Written> { |
| 228 | if *method(cx) != Method::POST { |
| 229 | return None; |
| 230 | } |
| 231 | let path = uri(cx).path().to_owned(); |
| 232 | let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); |
| 233 | let [owner, repo, kind, rest @ ..] = parts.as_slice() else { |
| 234 | return None; |
| 235 | }; |
| 236 | let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); |
| 237 | match (*kind, rest) { |
| 238 | ("pulls", []) => Some(Written::New { owner, repo }), |
| 239 | ("pulls", [number, ..]) => number.parse().ok().map(|number| Written::Pull { |
| 240 | owner, |
| 241 | repo, |
| 242 | number, |
| 243 | }), |
| 244 | ("labels" | "milestones", _) => Some(Written::Repo { owner, repo }), |
| 245 | _ => None, |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | /// Wraps every request. Only a POST under the pulls paths, or to a label or milestone route, does |
| 250 | /// anything. Registered on the public router in `boot.rs`, next to the other request layers. |
| 251 | pub struct PullWriteLayer; |
| 252 | |
| 253 | impl Layer for PullWriteLayer { |
| 254 | fn path(&self) -> Option<&Path> { |
| 255 | None |
| 256 | } |
| 257 | |
| 258 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 259 | Box::pin(bump_after_write(cx, body, next)) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | /// Bumps the topics a write named, once the handler has run. The handler's result passes through |
| 264 | /// unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and agrees. |
| 265 | async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> { |
| 266 | let target = written(cx); |
| 267 | let result = next.run(cx, body).await; |
| 268 | if let Some(target) = target { |
| 269 | bump_written(context::<AppState>(cx), target).await; |
| 270 | } |
| 271 | result |
| 272 | } |
| 273 | |
| 274 | async fn bump_written(state: &AppState, target: Written) { |
| 275 | let (owner, name) = match &target { |
| 276 | Written::Pull { owner, repo, .. } |
| 277 | | Written::New { owner, repo } |
| 278 | | Written::Repo { owner, repo } => (owner.as_str(), repo.as_str()), |
| 279 | }; |
| 280 | let repo = match state.store.repo_by_owner_and_name(owner, name).await { |
| 281 | Ok(Some(repo)) => repo, |
| 282 | Ok(None) => return, |
| 283 | Err(e) => { |
| 284 | tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); |
| 285 | return; |
| 286 | } |
| 287 | }; |
| 288 | match target { |
| 289 | Written::Pull { number, .. } => { |
| 290 | match state.store.pull_by_number(&repo.id, number).await { |
| 291 | Ok(Some(pr)) => { |
| 292 | bump_pull(state, &repo.id, &pr.issue.id); |
| 293 | // A closed or merged pull leaves its reviewers' request lists. |
| 294 | if pr.issue.state != forge_core::IssueState::Open || pr.merged_at.is_some() |
| 295 | { |
| 296 | bump_pending_reviewers(state, &pr.issue.id).await; |
| 297 | } |
| 298 | } |
| 299 | Ok(None) => {} |
| 300 | Err(e) => { |
| 301 | tracing::error!(error = %e, number, "live: loading the pull to bump failed") |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | Written::New { .. } => bump_list(state, &repo.id), |
| 306 | Written::Repo { .. } => bump_repo_pulls(state, &repo.id).await, |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | mod discussion_write { |
| 312 | use topcoat::context::{Cx, context}; |
| 313 | use topcoat::router::request::{method, uri}; |
| 314 | use topcoat::router::response::Response; |
| 315 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; |
| 316 | |
| 317 | use crate::live::Topic; |
| 318 | use crate::state::AppState; |
| 319 | |
| 320 | /// Which topics a discussion write reaches. |
| 321 | enum Written { |
| 322 | /// A new discussion, or the discussions toggle of the repo settings: the list. |
| 323 | List { owner: String, repo: String }, |
| 324 | /// A write to one discussion (`/{o}/{r}/discussions/{n}/...`): the list and the discussion. |
| 325 | Discussion { |
| 326 | owner: String, |
| 327 | repo: String, |
| 328 | number: String, |
| 329 | }, |
| 330 | } |
| 331 | |
| 332 | /// The write a request makes to the discussion side, when it is a POST that can change one. |
| 333 | fn written(cx: &Cx) -> Option<Written> { |
| 334 | if *method(cx) != Method::POST { |
| 335 | return None; |
| 336 | } |
| 337 | let path = uri(cx).path().to_owned(); |
| 338 | let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); |
| 339 | let [owner, repo, kind, rest @ ..] = parts.as_slice() else { |
| 340 | return None; |
| 341 | }; |
| 342 | let (owner, repo) = ((*owner).to_owned(), (*repo).to_owned()); |
| 343 | match (*kind, rest) { |
| 344 | ("discussions", ["new"]) => Some(Written::List { owner, repo }), |
| 345 | ("discussions", [number, ..]) => Some(Written::Discussion { |
| 346 | owner, |
| 347 | repo, |
| 348 | number: (*number).to_owned(), |
| 349 | }), |
| 350 | ("settings", ["discussions"]) => Some(Written::List { owner, repo }), |
| 351 | _ => None, |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | /// The topics a write reaches, looked up before the handler runs. A repo or discussion that does |
| 356 | /// not exist yields nothing, and a failed lookup is logged. |
| 357 | async fn topics_of(state: &AppState, target: Written) -> Vec<Topic> { |
| 358 | let (owner, name) = match &target { |
| 359 | Written::List { owner, repo } | Written::Discussion { owner, repo, .. } => { |
| 360 | (owner.as_str(), repo.as_str()) |
| 361 | } |
| 362 | }; |
| 363 | let repo = match state.store.repo_by_owner_and_name(owner, name).await { |
| 364 | Ok(Some(repo)) => repo, |
| 365 | Ok(None) => return Vec::new(), |
| 366 | Err(e) => { |
| 367 | tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); |
| 368 | return Vec::new(); |
| 369 | } |
| 370 | }; |
| 371 | let mut topics = vec![Topic::Discussions(repo.id.clone())]; |
| 372 | if let Written::Discussion { number, .. } = target |
| 373 | && let Ok(number) = number.parse::<i64>() |
| 374 | { |
| 375 | match state.store.discussion_by_number(&repo.id, number).await { |
| 376 | Ok(Some(discussion)) => topics.push(Topic::Discussion(discussion.id)), |
| 377 | Ok(None) => {} |
| 378 | Err(e) => { |
| 379 | tracing::error!(error = %e, number, "live: loading the discussion to bump failed") |
| 380 | } |
| 381 | } |
| 382 | } |
| 383 | topics |
| 384 | } |
| 385 | |
| 386 | /// Wraps every request. Only a POST under the discussions paths, or the discussions settings |
| 387 | /// toggle, does anything. Registered on the public router in `boot.rs`, next to the other layers. |
| 388 | pub struct DiscussionWriteLayer; |
| 389 | |
| 390 | impl Layer for DiscussionWriteLayer { |
| 391 | fn path(&self) -> Option<&Path> { |
| 392 | None |
| 393 | } |
| 394 | |
| 395 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 396 | Box::pin(bump_after_write(cx, body, next)) |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | /// Bumps the topics a write reaches, once the handler has run. The handler's result passes |
| 401 | /// through unchanged, so a refused write (an error or a redirect) bumps too: the page re-reads and |
| 402 | /// agrees. |
| 403 | async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> { |
| 404 | let state = context::<AppState>(cx); |
| 405 | let topics = match written(cx) { |
| 406 | Some(target) => topics_of(state, target).await, |
| 407 | None => Vec::new(), |
| 408 | }; |
| 409 | let result = next.run(cx, body).await; |
| 410 | for topic in &topics { |
| 411 | state.live.bump(topic); |
| 412 | } |
| 413 | result |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | mod org_write { |
| 418 | use topcoat::context::{Cx, context}; |
| 419 | use topcoat::router::request::{method, uri}; |
| 420 | use topcoat::router::response::Response; |
| 421 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; |
| 422 | |
| 423 | use crate::live::Topic; |
| 424 | use crate::state::AppState; |
| 425 | |
| 426 | /// The org a POST under `/org/{org}/{members|teams|settings}` writes to, by its name. |
| 427 | fn written_org(cx: &Cx) -> Option<String> { |
| 428 | if *method(cx) != Method::POST { |
| 429 | return None; |
| 430 | } |
| 431 | let path = uri(cx).path().to_owned(); |
| 432 | let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); |
| 433 | let ["org", name, kind, ..] = parts.as_slice() else { |
| 434 | return None; |
| 435 | }; |
| 436 | matches!(*kind, "members" | "teams" | "settings").then(|| (*name).to_owned()) |
| 437 | } |
| 438 | |
| 439 | /// Wraps every request. Only a POST under an org's members, teams or settings does anything. |
| 440 | /// Registered on the public router in `boot.rs`, next to the pull write layer. |
| 441 | pub struct OrgWriteLayer; |
| 442 | |
| 443 | impl Layer for OrgWriteLayer { |
| 444 | fn path(&self) -> Option<&Path> { |
| 445 | None |
| 446 | } |
| 447 | |
| 448 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 449 | Box::pin(bump_after_write(cx, body, next)) |
| 450 | } |
| 451 | } |
| 452 | |
| 453 | /// Bumps the org's topic after the handler ran. The org is looked up before the handler, so a |
| 454 | /// write that removes the org (its deletion) still reaches the streams that follow it. The |
| 455 | /// handler's result passes through unchanged. |
| 456 | async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> topcoat::Result<Response> { |
| 457 | let Some(name) = written_org(cx) else { |
| 458 | return next.run(cx, body).await; |
| 459 | }; |
| 460 | let state = context::<AppState>(cx); |
| 461 | let org_id = match state.store.user_by_username(&name).await { |
| 462 | Ok(Some(org)) if org.is_org() => Some(org.id), |
| 463 | Ok(_) => None, |
| 464 | Err(e) => { |
| 465 | tracing::error!(error = %e, name, "live: loading the org to bump failed"); |
| 466 | None |
| 467 | } |
| 468 | }; |
| 469 | let result = next.run(cx, body).await; |
| 470 | if let Some(org_id) = org_id { |
| 471 | state.live.bump(&Topic::Org(org_id.clone())); |
| 472 | state.live.bump(&Topic::User(org_id)); |
| 473 | } |
| 474 | result |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | mod repo_settings_write { |
| 479 | use topcoat::Result; |
| 480 | use topcoat::context::{Cx, context}; |
| 481 | use topcoat::router::request::{method, uri}; |
| 482 | use topcoat::router::response::Response; |
| 483 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; |
| 484 | |
| 485 | use crate::live::{Topic, bump_repo_pulls, bump_settings}; |
| 486 | use crate::state::AppState; |
| 487 | |
| 488 | /// Wraps every request. Only a POST under the settings or security paths does anything. Registered |
| 489 | /// on the public router in `boot.rs`, and on the test router, next to the other request layers. |
| 490 | pub struct RepoSettingsWriteLayer; |
| 491 | |
| 492 | impl Layer for RepoSettingsWriteLayer { |
| 493 | fn path(&self) -> Option<&Path> { |
| 494 | None |
| 495 | } |
| 496 | |
| 497 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 498 | Box::pin(bump_after_write(cx, body, next)) |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | /// The `(owner, name)` of a POST under `/{o}/{r}/settings/...` or `/{o}/{r}/security/...`. |
| 503 | fn written(cx: &Cx) -> Option<(String, String)> { |
| 504 | if *method(cx) != Method::POST { |
| 505 | return None; |
| 506 | } |
| 507 | let path = uri(cx).path().to_owned(); |
| 508 | let parts: Vec<&str> = path.trim_start_matches('/').split('/').collect(); |
| 509 | match parts.as_slice() { |
| 510 | [owner, name, "settings" | "security", ..] => { |
| 511 | Some(((*owner).to_owned(), (*name).to_owned())) |
| 512 | } |
| 513 | _ => None, |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | /// Bumps the settings topic once the handler has run. The repo is looked up before the handler, |
| 518 | /// because a rename moves its name away. The handler's result passes through unchanged, so a |
| 519 | /// refused write bumps too: the page re-reads and agrees. |
| 520 | async fn bump_after_write(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { |
| 521 | let repo_id = match written(cx) { |
| 522 | Some((owner, name)) => { |
| 523 | let state = context::<AppState>(cx); |
| 524 | match state.store.repo_by_owner_and_name(&owner, &name).await { |
| 525 | Ok(repo) => repo.map(|repo| repo.id), |
| 526 | Err(e) => { |
| 527 | tracing::error!(error = %e, owner, name, "live: loading the repo to bump failed"); |
| 528 | None |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | None => None, |
| 533 | }; |
| 534 | let result = next.run(cx, body).await; |
| 535 | if let Some(repo_id) = repo_id { |
| 536 | let state = context::<AppState>(cx); |
| 537 | bump_settings(&state.live, &repo_id); |
| 538 | // The repo header shows settings too (the mirror line, the archived notice, the tabs); its |
| 539 | // stream sends nothing when its fingerprint holds. |
| 540 | state.live.bump(&Topic::Repo(repo_id.clone())); |
| 541 | // The merge gate of a pull page reads the branch protection rules, so every pull of the |
| 542 | // repo may show a different gate. A pull's stream sends nothing when its fingerprint holds. |
| 543 | bump_repo_pulls(state, &repo_id).await; |
| 544 | } |
| 545 | result |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | mod not_found_layer { |
| 550 | use http::header::ACCEPT; |
| 551 | use topcoat::Result; |
| 552 | use topcoat::context::Cx; |
| 553 | use topcoat::router::error::{ForbiddenError, NotFoundError, rewrite}; |
| 554 | use topcoat::router::request::headers; |
| 555 | use topcoat::router::response::Response; |
| 556 | use topcoat::router::{Body, Layer, LayerFuture, Method, Next, Path}; |
| 557 | |
| 558 | use crate::auth::percent_encode; |
| 559 | |
| 560 | /// The styled 404 and 403 pages. Topcoat answers `not_found()` and `forbidden()` with a bare text |
| 561 | /// body, so this layer swaps that body for the regular shell plus a short message, for browser |
| 562 | /// requests only. A signed-out visitor refused a page is sent to log in first, as every page that |
| 563 | /// needs an account does. |
| 564 | pub struct NotFoundLayer; |
| 565 | |
| 566 | impl Layer for NotFoundLayer { |
| 567 | fn path(&self) -> Option<&Path> { |
| 568 | None |
| 569 | } |
| 570 | |
| 571 | fn handle<'a>(&'a self, cx: &'a Cx, body: Body, next: Next<'a>) -> LayerFuture<'a> { |
| 572 | Box::pin(styled_not_found(cx, body, next)) |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | async fn styled_not_found(cx: &Cx, body: Body, next: Next<'_>) -> Result<Response> { |
| 577 | let is_get = *topcoat::router::request::method(cx) == Method::GET; |
| 578 | let result = next.run(cx, body).await; |
| 579 | let is_not_found = matches!(&result, Err(e) if e.downcast_ref::<NotFoundError>().is_some()); |
| 580 | let is_forbidden = |
| 581 | matches!(&result, Err(e) if e.downcast_ref::<ForbiddenError>().is_some()); |
| 582 | let wants_html = headers(cx) |
| 583 | .get(ACCEPT) |
| 584 | .and_then(|v| v.to_str().ok()) |
| 585 | .is_some_and(|v| v.contains("text/html")); |
| 586 | if !wants_html || !(is_not_found || is_forbidden) { |
| 587 | return result; |
| 588 | } |
| 589 | if is_forbidden { |
| 590 | // The cookies are not readable out here, so the page itself decides whether the visitor |
| 591 | // must log in first; a refused GET hands it the address to come back to. |
| 592 | let target = if is_get { |
| 593 | let path = topcoat::router::request::uri(cx) |
| 594 | .path_and_query() |
| 595 | .map_or("/", |p| p.as_str()); |
| 596 | format!("{FORBIDDEN_PATH}?next={}", percent_encode(path)) |
| 597 | } else { |
| 598 | FORBIDDEN_PATH.to_owned() |
| 599 | }; |
| 600 | return Err(rewrite(target, Body::empty()).method(Method::GET).into()); |
| 601 | } |
| 602 | Err(rewrite(PATH, Body::empty()).method(Method::GET).into()) |
| 603 | } |
| 604 | |
| 605 | /// Where the layer sends a browser's 403. The page answers with status 403 itself. |
| 606 | const FORBIDDEN_PATH: &str = "/-/forbidden"; |
| 607 | |
| 608 | /// Where the layer sends a browser's 404. The page answers with status 404 itself. |
| 609 | const PATH: &str = "/-/not-found"; |
| 610 | } |