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