| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use std::{sync::Arc, time::SystemTime}; |
| 8 | |
| 9 | use sqlx::SqlitePool; |
| 10 | use topcoat::{ |
| 11 | Result, |
| 12 | context::{Cx, app_context}, |
| 13 | router::{ |
| 14 | HeaderName, HeaderValue, |
| 15 | error::{internal_server_error, not_found}, |
| 16 | header::{HOST, LOCATION}, |
| 17 | headers, |
| 18 | }, |
| 19 | session, |
| 20 | }; |
| 21 | |
| 22 | use crate::{ |
| 23 | application::{ |
| 24 | AppConfig, Error, Identity, PublicProfile, RepoView, describe_identity, is_claimed, |
| 25 | resolve_actor, |
| 26 | }, |
| 27 | domain::{Actor, DomainError, PrivateTargets, SessionTokenHash}, |
| 28 | infrastructure::{ |
| 29 | cat_file::CatFilePool, |
| 30 | disk::WalkingDiskUsage, |
| 31 | git::{DiskGitArchive, DiskGitMerge, DiskGitStorage, GitFeatures, GitHttpBackend}, |
| 32 | git_query::DiskGitQuery, |
| 33 | highlight::HighlightCache, |
| 34 | mail::LettreMailer, |
| 35 | merge_cache::MergeCache, |
| 36 | repository::{ |
| 37 | SqliteIssueRepo, SqliteLabelRepo, SqliteMembershipRepo, SqliteOrgRepo, |
| 38 | SqlitePasswordResetRepo, SqlitePullRequestRepo, SqlitePushEventRepo, SqliteRepoRepo, |
| 39 | SqliteSessionRepo, SqliteTokenRepo, SqliteUserRepo, SqliteWebhookDeliveryRepo, |
| 40 | SqliteWebhookRepo, |
| 41 | }, |
| 42 | webhook::UreqWebhookSender, |
| 43 | }, |
| 44 | }; |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | pub struct SetupState(pub crate::domain::SetupToken); |
| 50 | |
| 51 | pub fn pool(cx: &Cx) -> &SqlitePool { |
| 52 | app_context::<SqlitePool>(cx) |
| 53 | } |
| 54 | |
| 55 | |
| 56 | |
| 57 | pub fn server_error<E>(error: E) -> topcoat::Error |
| 58 | where |
| 59 | E: std::error::Error + Send + Sync + 'static, |
| 60 | { |
| 61 | eprintln!("steid: {error}"); |
| 62 | internal_server_error(error).into() |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | pub fn timed_out(error: &Error) -> bool { |
| 78 | matches!(error, Error::GitQuery(query) if query.is_timeout()) |
| 79 | } |
| 80 | |
| 81 | pub fn orgs(cx: &Cx) -> SqliteOrgRepo { |
| 82 | SqliteOrgRepo::new(pool(cx).clone()) |
| 83 | } |
| 84 | |
| 85 | pub fn memberships(cx: &Cx) -> SqliteMembershipRepo { |
| 86 | SqliteMembershipRepo::new(pool(cx).clone()) |
| 87 | } |
| 88 | |
| 89 | pub fn repos(cx: &Cx) -> SqliteRepoRepo { |
| 90 | SqliteRepoRepo::new(pool(cx).clone()) |
| 91 | } |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | pub fn disk_usage(cx: &Cx) -> &WalkingDiskUsage { |
| 100 | app_context::<WalkingDiskUsage>(cx) |
| 101 | } |
| 102 | |
| 103 | |
| 104 | pub fn storage(cx: &Cx) -> DiskGitStorage { |
| 105 | DiskGitStorage::new(app_context::<AppConfig>(cx).data_dir.clone()) |
| 106 | } |
| 107 | |
| 108 | pub fn users(cx: &Cx) -> SqliteUserRepo { |
| 109 | SqliteUserRepo::new(pool(cx).clone()) |
| 110 | } |
| 111 | |
| 112 | pub fn tokens(cx: &Cx) -> SqliteTokenRepo { |
| 113 | SqliteTokenRepo::new(pool(cx).clone()) |
| 114 | } |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | pub fn sessions(cx: &Cx) -> SqliteSessionRepo { |
| 121 | SqliteSessionRepo::new(pool(cx).clone()) |
| 122 | } |
| 123 | |
| 124 | |
| 125 | pub fn resets(cx: &Cx) -> SqlitePasswordResetRepo { |
| 126 | SqlitePasswordResetRepo::new(pool(cx).clone()) |
| 127 | } |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | pub fn mailer(cx: &Cx) -> LettreMailer { |
| 137 | LettreMailer::from_config(app_context::<AppConfig>(cx)).unwrap_or_else(|error| { |
| 138 | |
| 139 | |
| 140 | |
| 141 | eprintln!("steid: the mail configuration stopped being usable: {error}"); |
| 142 | LettreMailer::unusable() |
| 143 | }) |
| 144 | } |
| 145 | |
| 146 | pub fn issues(cx: &Cx) -> SqliteIssueRepo { |
| 147 | SqliteIssueRepo::new(pool(cx).clone()) |
| 148 | } |
| 149 | |
| 150 | |
| 151 | pub fn labels(cx: &Cx) -> SqliteLabelRepo { |
| 152 | SqliteLabelRepo::new(pool(cx).clone()) |
| 153 | } |
| 154 | |
| 155 | |
| 156 | pub fn pulls(cx: &Cx) -> SqlitePullRequestRepo { |
| 157 | SqlitePullRequestRepo::new(pool(cx).clone()) |
| 158 | } |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | pub fn merges(cx: &Cx) -> DiskGitMerge { |
| 166 | DiskGitMerge::new(app_context::<AppConfig>(cx).data_dir.clone()) |
| 167 | } |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | pub fn git_features(cx: &Cx) -> GitFeatures { |
| 179 | topcoat::context::try_app_context::<GitFeatures>(cx) |
| 180 | .copied() |
| 181 | .unwrap_or_default() |
| 182 | } |
| 183 | |
| 184 | |
| 185 | pub fn push_events(cx: &Cx) -> SqlitePushEventRepo { |
| 186 | SqlitePushEventRepo::new(pool(cx).clone()) |
| 187 | } |
| 188 | |
| 189 | pub fn webhooks(cx: &Cx) -> SqliteWebhookRepo { |
| 190 | SqliteWebhookRepo::new(pool(cx).clone()) |
| 191 | } |
| 192 | |
| 193 | pub fn deliveries(cx: &Cx) -> SqliteWebhookDeliveryRepo { |
| 194 | SqliteWebhookDeliveryRepo::new(pool(cx).clone()) |
| 195 | } |
| 196 | |
| 197 | |
| 198 | |
| 199 | |
| 200 | |
| 201 | pub fn webhook_sender(cx: &Cx) -> UreqWebhookSender { |
| 202 | UreqWebhookSender::new(private_targets(cx)) |
| 203 | } |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | |
| 211 | |
| 212 | pub fn private_targets(cx: &Cx) -> PrivateTargets { |
| 213 | if app_context::<AppConfig>(cx).allow_private_webhooks { |
| 214 | PrivateTargets::Allowed |
| 215 | } else { |
| 216 | PrivateTargets::Refused |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | pub fn queries(cx: &Cx) -> DiskGitQuery { |
| 227 | DiskGitQuery::new( |
| 228 | app_context::<AppConfig>(cx).data_dir.clone(), |
| 229 | app_context::<Arc<CatFilePool>>(cx).clone(), |
| 230 | app_context::<Arc<MergeCache>>(cx).clone(), |
| 231 | ) |
| 232 | } |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | pub fn highlights(cx: &Cx) -> &Arc<HighlightCache> { |
| 240 | app_context::<Arc<HighlightCache>>(cx) |
| 241 | } |
| 242 | |
| 243 | |
| 244 | pub fn archives(cx: &Cx) -> DiskGitArchive { |
| 245 | DiskGitArchive::new(app_context::<AppConfig>(cx).data_dir.clone()) |
| 246 | } |
| 247 | |
| 248 | |
| 249 | pub fn protocol(cx: &Cx) -> GitHttpBackend { |
| 250 | GitHttpBackend::new(app_context::<AppConfig>(cx).data_dir.clone()) |
| 251 | } |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | pub async fn current_actor(cx: &Cx) -> Result<Actor> { |
| 258 | let presented = session::token_hash(cx) |
| 259 | .await? |
| 260 | .map(|hash| SessionTokenHash::from_trusted(hex(&hash))); |
| 261 | |
| 262 | let sessions = SqliteSessionRepo::new(pool(cx).clone()); |
| 263 | |
| 264 | resolve_actor(presented.as_ref(), SystemTime::now(), &sessions) |
| 265 | .await |
| 266 | .map_err(server_error) |
| 267 | } |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | pub async fn identity(cx: &Cx) -> Result<Option<Identity>> { |
| 273 | let actor = current_actor(cx).await?; |
| 274 | let pool = pool(cx).clone(); |
| 275 | |
| 276 | describe_identity( |
| 277 | &actor, |
| 278 | &SqliteUserRepo::new(pool.clone()), |
| 279 | &SqliteOrgRepo::new(pool), |
| 280 | ) |
| 281 | .await |
| 282 | .map_err(server_error) |
| 283 | } |
| 284 | |
| 285 | |
| 286 | pub async fn claimed(cx: &Cx) -> Result<bool> { |
| 287 | let users = SqliteUserRepo::new(pool(cx).clone()); |
| 288 | |
| 289 | is_claimed(&users).await.map_err(server_error) |
| 290 | } |
| 291 | |
| 292 | |
| 293 | pub fn setup_token(cx: &Cx) -> Option<&crate::domain::SetupToken> { |
| 294 | topcoat::context::try_app_context::<SetupState>(cx).map(|state| &state.0) |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | |
| 311 | pub fn location(uri: &str) -> Result<(HeaderName, HeaderValue)> { |
| 312 | Ok((LOCATION, HeaderValue::try_from(uri).map_err(server_error)?)) |
| 313 | } |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | pub fn public_origin(cx: &Cx) -> String { |
| 326 | let headers = headers(cx); |
| 327 | let value = |name: &str| headers.get(name).and_then(|value| value.to_str().ok()); |
| 328 | |
| 329 | let scheme = value("x-forwarded-proto").unwrap_or("http"); |
| 330 | let host = headers |
| 331 | .get(HOST) |
| 332 | .and_then(|value| value.to_str().ok()) |
| 333 | .unwrap_or("localhost"); |
| 334 | |
| 335 | format!("{scheme}://{host}") |
| 336 | } |
| 337 | |
| 338 | |
| 339 | pub fn hex(hash: &session::TokenHash) -> String { |
| 340 | hash.iter().map(|byte| format!("{byte:02x}")).collect() |
| 341 | } |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | pub async fn owned_repo(cx: &Cx) -> Result<RepoView> { |
| 358 | let repo = super::repo::repo_for(cx).await?; |
| 359 | |
| 360 | if !repo.viewer_is_owner { |
| 361 | return Err(not_found().into()); |
| 362 | } |
| 363 | |
| 364 | Ok(repo) |
| 365 | } |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | pub async fn instance_owner(cx: &Cx) -> Result<bool> { |
| 381 | crate::application::instance_owner(¤t_actor(cx).await?, &users(cx)) |
| 382 | .await |
| 383 | .map_err(server_error) |
| 384 | } |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | pub async fn owned_profile(cx: &Cx) -> Result<PublicProfile> { |
| 392 | let profile = super::profile::profile_for(cx).await?; |
| 393 | |
| 394 | if !profile.viewer_is_owner { |
| 395 | return Err(not_found().into()); |
| 396 | } |
| 397 | |
| 398 | Ok(profile) |
| 399 | } |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | pub fn write_failure(error: Error) -> std::result::Result<String, topcoat::Error> { |
| 418 | match error { |
| 419 | Error::Domain(DomainError::Validation { field, reason }) => { |
| 420 | Ok(format!("That {field} is no good: {reason}.")) |
| 421 | } |
| 422 | Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. }) => { |
| 423 | Err(not_found().into()) |
| 424 | } |
| 425 | |
| 426 | other => Err(server_error(std::io::Error::other(other.to_string()))), |
| 427 | } |
| 428 | } |
| 429 | |
| 430 | #[cfg(test)] |
| 431 | mod tests { |
| 432 | use topcoat::router::error::{InternalServerError, NotFoundError}; |
| 433 | |
| 434 | use super::*; |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | fn is_not_found(error: topcoat::Error) -> bool { |
| 441 | error.downcast::<NotFoundError>().is_ok() |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn a_validation_failure_becomes_a_sentence_the_form_can_show() { |
| 446 | let message = write_failure(Error::Domain(DomainError::Validation { |
| 447 | field: "title".to_owned(), |
| 448 | reason: "it is empty".to_owned(), |
| 449 | })); |
| 450 | |
| 451 | assert_eq!( |
| 452 | message.expect("a message"), |
| 453 | "That title is no good: it is empty." |
| 454 | ); |
| 455 | } |
| 456 | |
| 457 | #[test] |
| 458 | fn losing_ownership_mid_write_is_a_404_rather_than_a_403() { |
| 459 | |
| 460 | |
| 461 | let error = write_failure(Error::Domain(DomainError::Forbidden)).expect_err("a response"); |
| 462 | |
| 463 | assert!(is_not_found(error)); |
| 464 | } |
| 465 | |
| 466 | #[test] |
| 467 | fn a_target_that_went_away_is_the_same_404() { |
| 468 | let error = write_failure(Error::Domain(DomainError::NotFound { entity: "issue" })) |
| 469 | .expect_err("a response"); |
| 470 | |
| 471 | assert!(is_not_found(error)); |
| 472 | } |
| 473 | |
| 474 | #[test] |
| 475 | fn anything_else_is_ours_and_is_a_500() { |
| 476 | |
| 477 | |
| 478 | let error = write_failure(Error::Domain(DomainError::Archived)).expect_err("a response"); |
| 479 | |
| 480 | assert!(error.downcast::<InternalServerError>().is_ok()); |
| 481 | } |
| 482 | } |