| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
pub const DEFAULT_LOG_FILTER: &str = |
| 17 |
"makenotwork=debug,tower_http=debug,sqlx=info,csp_violation=warn"; |
| 18 |
|
| 19 |
pub mod access_gate; |
| 20 |
pub mod auth; |
| 21 |
pub mod background; |
| 22 |
pub mod build_runner; |
| 23 |
pub mod changelog; |
| 24 |
pub mod cloudflare; |
| 25 |
pub mod config; |
| 26 |
pub mod constants; |
| 27 |
pub mod crypto; |
| 28 |
pub mod csrf; |
| 29 |
pub mod currency; |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
pub use custom_pages; |
| 36 |
pub mod db; |
| 37 |
pub mod email; |
| 38 |
pub mod error; |
| 39 |
pub mod extractors; |
| 40 |
pub mod fee_calculator; |
| 41 |
pub mod formatting; |
| 42 |
pub mod fragment_redirect; |
| 43 |
pub mod git; |
| 44 |
pub mod git_ssh; |
| 45 |
pub mod helpers; |
| 46 |
pub mod import; |
| 47 |
pub mod license_templates; |
| 48 |
pub mod markdown; |
| 49 |
pub mod metrics; |
| 50 |
pub mod monitor; |
| 51 |
pub mod mt_client; |
| 52 |
pub mod oauth_scope; |
| 53 |
pub mod openapi; |
| 54 |
pub mod payments; |
| 55 |
pub mod pricing; |
| 56 |
pub mod quasi; |
| 57 |
pub mod quasi_spike; |
| 58 |
pub mod rate_limit; |
| 59 |
pub mod routes; |
| 60 |
pub mod rss; |
| 61 |
pub mod scanning; |
| 62 |
pub mod scheduler; |
| 63 |
pub mod security_signals; |
| 64 |
pub mod seed; |
| 65 |
pub mod shell; |
| 66 |
pub mod site_docs; |
| 67 |
pub mod storage; |
| 68 |
pub mod synckit_auth; |
| 69 |
pub mod synckit_billing; |
| 70 |
pub mod templates; |
| 71 |
pub mod theming; |
| 72 |
pub mod tier_prices; |
| 73 |
pub mod types; |
| 74 |
pub mod validation; |
| 75 |
pub mod wam_client; |
| 76 |
pub mod wordlist; |
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
#[cfg(test)] |
| 81 |
mod deploy_lint; |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
#[cfg(test)] |
| 86 |
mod test_tracing; |
| 87 |
|
| 88 |
use axum::{Router, extract::FromRef, http::HeaderValue, middleware}; |
| 89 |
use std::time::Instant; |
| 90 |
use tower_http::limit::RequestBodyLimitLayer; |
| 91 |
use tower_http::services::ServeDir; |
| 92 |
use tower_http::set_header::SetResponseHeaderLayer; |
| 93 |
use tower_sessions::SessionManagerLayer; |
| 94 |
use tower_sessions_sqlx_store::PostgresStore; |
| 95 |
|
| 96 |
use std::sync::Arc; |
| 97 |
|
| 98 |
use dashmap::DashMap; |
| 99 |
use db::{SyncAppId, UserId, UserSessionId}; |
| 100 |
|
| 101 |
use config::Config; |
| 102 |
use docengine::DocLoader; |
| 103 |
use email::EmailClient; |
| 104 |
use payments::{PaymentCapabilities, PaymentProvider}; |
| 105 |
use routes::{ |
| 106 |
admin_routes, api_routes, auth_routes, build_routes, git_issue_routes, git_routes, |
| 107 |
git_write_routes, oauth_routes, ota_routes, page_routes, postmark_routes, rpm_routes, |
| 108 |
sso_routes, storage_routes, stripe_routes, synckit_routes, |
| 109 |
}; |
| 110 |
use scanning::ScanPipeline; |
| 111 |
use storage::StorageBackend; |
| 112 |
use webauthn_rs::Webauthn; |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
#[derive(Clone, FromRef)] |
| 123 |
pub struct AppState { |
| 124 |
pub db: sqlx::PgPool, |
| 125 |
pub config: Config, |
| 126 |
|
| 127 |
|
| 128 |
pub storage: AppStorage, |
| 129 |
pub payments: Option<Arc<dyn PaymentProvider>>, |
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
pub payment_caps: PaymentCapabilities, |
| 135 |
pub email: EmailClient, |
| 136 |
pub docs: Arc<DocLoader>, |
| 137 |
pub tier_prices: tier_prices::TierPrices, |
| 138 |
pub runway_config: tier_prices::RunwayConfig, |
| 139 |
|
| 140 |
|
| 141 |
pub fee_calculator: fee_calculator::FeeCalculator, |
| 142 |
pub scanner: Option<Arc<ScanPipeline>>, |
| 143 |
pub webauthn: Arc<Webauthn>, |
| 144 |
pub syntax: Option<Arc<git::SyntaxHighlighter>>, |
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
#[from_ref(skip)] |
| 149 |
pub started_at: chrono::DateTime<chrono::Utc>, |
| 150 |
#[from_ref(skip)] |
| 151 |
pub start_instant: Instant, |
| 152 |
|
| 153 |
pub mt_client: Option<mt_client::MtClient>, |
| 154 |
|
| 155 |
pub wam: Option<wam_client::WamClient>, |
| 156 |
|
| 157 |
pub caches: AppCaches, |
| 158 |
|
| 159 |
pub limiters: AppLimiters, |
| 160 |
|
| 161 |
|
| 162 |
pub restart_at: Arc<std::sync::atomic::AtomicI64>, |
| 163 |
|
| 164 |
pub metrics_handle: Option<metrics_exporter_prometheus::PrometheusHandle>, |
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
pub page_view_tx: db::page_views::PageViewTx, |
| 169 |
|
| 170 |
|
| 171 |
|
| 172 |
|
| 173 |
pub bg: background::BackgroundTx, |
| 174 |
} |
| 175 |
|
| 176 |
|
| 177 |
#[derive(Clone)] |
| 178 |
pub struct AppStorage { |
| 179 |
|
| 180 |
pub s3: Option<Arc<dyn StorageBackend>>, |
| 181 |
|
| 182 |
pub synckit_s3: Option<Arc<dyn StorageBackend>>, |
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
pub public_s3: Option<Arc<dyn StorageBackend>>, |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
pub rpm_s3: Option<Arc<dyn StorageBackend>>, |
| 192 |
} |
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
#[derive(Clone)] |
| 197 |
pub struct AppCaches { |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
pub session_cache: Arc<DashMap<UserSessionId, Instant>>, |
| 202 |
|
| 203 |
|
| 204 |
pub domain_cache: Arc<DashMap<String, db::UserId>>, |
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
pub sync_notify: Arc<DashMap<(SyncAppId, UserId), tokio::sync::broadcast::Sender<i64>>>, |
| 209 |
|
| 210 |
pub sse_connections: Arc<DashMap<UserId, std::sync::atomic::AtomicUsize>>, |
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
pub notes_cache: Arc<git::notes::NotesCache>, |
| 216 |
} |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
#[derive(Clone)] |
| 221 |
pub struct AppLimiters { |
| 222 |
|
| 223 |
|
| 224 |
pub scan_semaphore: Arc<tokio::sync::Semaphore>, |
| 225 |
|
| 226 |
|
| 227 |
pub caddy_ask_semaphore: Arc<tokio::sync::Semaphore>, |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
pub git_smart_http_semaphore: Arc<tokio::sync::Semaphore>, |
| 234 |
} |
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
#[derive(Clone)] |
| 255 |
pub struct Billing { |
| 256 |
pub payments: Option<Arc<dyn PaymentProvider>>, |
| 257 |
pub payment_caps: PaymentCapabilities, |
| 258 |
pub tier_prices: tier_prices::TierPrices, |
| 259 |
pub runway_config: tier_prices::RunwayConfig, |
| 260 |
pub fee_calculator: fee_calculator::FeeCalculator, |
| 261 |
} |
| 262 |
|
| 263 |
impl FromRef<AppState> for Billing { |
| 264 |
fn from_ref(s: &AppState) -> Self { |
| 265 |
Self { |
| 266 |
payments: s.payments.clone(), |
| 267 |
payment_caps: s.payment_caps.clone(), |
| 268 |
tier_prices: s.tier_prices.clone(), |
| 269 |
runway_config: s.runway_config.clone(), |
| 270 |
fee_calculator: s.fee_calculator.clone(), |
| 271 |
} |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
|
| 276 |
#[derive(Clone)] |
| 277 |
pub struct Integrations { |
| 278 |
pub mt_client: Option<mt_client::MtClient>, |
| 279 |
pub wam: Option<wam_client::WamClient>, |
| 280 |
} |
| 281 |
|
| 282 |
impl FromRef<AppState> for Integrations { |
| 283 |
fn from_ref(s: &AppState) -> Self { |
| 284 |
Self { |
| 285 |
mt_client: s.mt_client.clone(), |
| 286 |
wam: s.wam.clone(), |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
|
| 291 |
|
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
#[derive(Clone)] |
| 300 |
pub struct Scanning { |
| 301 |
pub scanner: Option<Arc<ScanPipeline>>, |
| 302 |
} |
| 303 |
|
| 304 |
impl FromRef<AppState> for Scanning { |
| 305 |
fn from_ref(s: &AppState) -> Self { |
| 306 |
Self { |
| 307 |
scanner: s.scanner.clone(), |
| 308 |
} |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
#[derive(Clone)] |
| 315 |
pub struct Sync { |
| 316 |
pub synckit_s3: Option<Arc<dyn StorageBackend>>, |
| 317 |
pub sync_notify: Arc<DashMap<(SyncAppId, UserId), tokio::sync::broadcast::Sender<i64>>>, |
| 318 |
pub sse_connections: Arc<DashMap<UserId, std::sync::atomic::AtomicUsize>>, |
| 319 |
} |
| 320 |
|
| 321 |
impl FromRef<AppState> for Sync { |
| 322 |
fn from_ref(s: &AppState) -> Self { |
| 323 |
Self { |
| 324 |
synckit_s3: s.storage.synckit_s3.clone(), |
| 325 |
sync_notify: s.caches.sync_notify.clone(), |
| 326 |
sse_connections: s.caches.sse_connections.clone(), |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
const SYNC_NOTIFY_CHANNEL_DEPTH: usize = 16; |
| 336 |
|
| 337 |
impl Sync { |
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
pub fn notify_push(&self, app_id: SyncAppId, user_id: UserId, cursor: i64) { |
| 342 |
if let Some(sender) = self.sync_notify.get(&(app_id, user_id)) { |
| 343 |
let _ = sender.send(cursor); |
| 344 |
} |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
pub fn subscribe_channel( |
| 351 |
&self, |
| 352 |
app_id: SyncAppId, |
| 353 |
user_id: UserId, |
| 354 |
) -> tokio::sync::broadcast::Receiver<i64> { |
| 355 |
self.sync_notify |
| 356 |
.entry((app_id, user_id)) |
| 357 |
.or_insert_with(|| tokio::sync::broadcast::channel(SYNC_NOTIFY_CHANNEL_DEPTH).0) |
| 358 |
.value() |
| 359 |
.subscribe() |
| 360 |
} |
| 361 |
} |
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
#[derive(Clone)] |
| 368 |
pub struct Git { |
| 369 |
pub syntax: Option<Arc<git::SyntaxHighlighter>>, |
| 370 |
pub smart_http_semaphore: Arc<tokio::sync::Semaphore>, |
| 371 |
pub notes_cache: Arc<git::notes::NotesCache>, |
| 372 |
} |
| 373 |
|
| 374 |
impl FromRef<AppState> for Git { |
| 375 |
fn from_ref(s: &AppState) -> Self { |
| 376 |
Self { |
| 377 |
syntax: s.syntax.clone(), |
| 378 |
smart_http_semaphore: s.limiters.git_smart_http_semaphore.clone(), |
| 379 |
notes_cache: Arc::clone(&s.caches.notes_cache), |
| 380 |
} |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 387 |
|
| 388 |
#[derive(Clone)] |
| 389 |
pub struct Ops { |
| 390 |
pub started_at: chrono::DateTime<chrono::Utc>, |
| 391 |
pub start_instant: Instant, |
| 392 |
pub restart_at: Arc<std::sync::atomic::AtomicI64>, |
| 393 |
pub metrics_handle: Option<metrics_exporter_prometheus::PrometheusHandle>, |
| 394 |
} |
| 395 |
|
| 396 |
impl FromRef<AppState> for Ops { |
| 397 |
fn from_ref(s: &AppState) -> Self { |
| 398 |
Self { |
| 399 |
started_at: s.started_at, |
| 400 |
start_instant: s.start_instant, |
| 401 |
restart_at: s.restart_at.clone(), |
| 402 |
metrics_handle: s.metrics_handle.clone(), |
| 403 |
} |
| 404 |
} |
| 405 |
} |
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
pub struct AppStateParts { |
| 415 |
pub db: sqlx::PgPool, |
| 416 |
pub config: Config, |
| 417 |
pub storage: AppStorage, |
| 418 |
pub payments: Option<Arc<dyn PaymentProvider>>, |
| 419 |
pub payment_caps: PaymentCapabilities, |
| 420 |
pub email: EmailClient, |
| 421 |
pub docs: Arc<DocLoader>, |
| 422 |
pub tier_prices: tier_prices::TierPrices, |
| 423 |
pub runway_config: tier_prices::RunwayConfig, |
| 424 |
pub fee_calculator: fee_calculator::FeeCalculator, |
| 425 |
pub scanner: Option<Arc<ScanPipeline>>, |
| 426 |
pub webauthn: Arc<Webauthn>, |
| 427 |
pub syntax: Option<Arc<git::SyntaxHighlighter>>, |
| 428 |
pub mt_client: Option<mt_client::MtClient>, |
| 429 |
pub wam: Option<wam_client::WamClient>, |
| 430 |
|
| 431 |
pub domain_cache: Arc<DashMap<String, db::UserId>>, |
| 432 |
pub metrics_handle: Option<metrics_exporter_prometheus::PrometheusHandle>, |
| 433 |
pub page_view_tx: db::page_views::PageViewTx, |
| 434 |
pub bg: background::BackgroundTx, |
| 435 |
} |
| 436 |
|
| 437 |
impl AppStorage { |
| 438 |
|
| 439 |
pub fn require_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 440 |
self.s3.as_ref().ok_or_else(|| { |
| 441 |
error::AppError::ServiceUnavailable("File storage is not configured".to_string()) |
| 442 |
}) |
| 443 |
} |
| 444 |
|
| 445 |
|
| 446 |
pub fn require_synckit_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 447 |
self.synckit_s3.as_ref().ok_or_else(|| { |
| 448 |
error::AppError::ServiceUnavailable("SyncKit storage is not configured".to_string()) |
| 449 |
}) |
| 450 |
} |
| 451 |
|
| 452 |
|
| 453 |
pub fn require_public_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 454 |
self.public_s3.as_ref().ok_or_else(|| { |
| 455 |
error::AppError::ServiceUnavailable( |
| 456 |
"Public storage bucket is not configured".to_string(), |
| 457 |
) |
| 458 |
}) |
| 459 |
} |
| 460 |
|
| 461 |
|
| 462 |
pub fn require_rpm_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 463 |
self.rpm_s3.as_ref().ok_or_else(|| { |
| 464 |
error::AppError::ServiceUnavailable("RPM bucket is not configured".to_string()) |
| 465 |
}) |
| 466 |
} |
| 467 |
} |
| 468 |
|
| 469 |
impl AppState { |
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
pub fn build(parts: AppStateParts) -> Self { |
| 480 |
Self { |
| 481 |
db: parts.db, |
| 482 |
config: parts.config, |
| 483 |
storage: parts.storage, |
| 484 |
payments: parts.payments, |
| 485 |
payment_caps: parts.payment_caps, |
| 486 |
email: parts.email, |
| 487 |
docs: parts.docs, |
| 488 |
tier_prices: parts.tier_prices, |
| 489 |
runway_config: parts.runway_config, |
| 490 |
fee_calculator: parts.fee_calculator, |
| 491 |
scanner: parts.scanner, |
| 492 |
webauthn: parts.webauthn, |
| 493 |
syntax: parts.syntax, |
| 494 |
started_at: chrono::Utc::now(), |
| 495 |
start_instant: Instant::now(), |
| 496 |
mt_client: parts.mt_client, |
| 497 |
wam: parts.wam, |
| 498 |
restart_at: Arc::new(std::sync::atomic::AtomicI64::new(0)), |
| 499 |
metrics_handle: parts.metrics_handle, |
| 500 |
page_view_tx: parts.page_view_tx, |
| 501 |
bg: parts.bg, |
| 502 |
caches: AppCaches { |
| 503 |
session_cache: Arc::new(DashMap::new()), |
| 504 |
domain_cache: parts.domain_cache, |
| 505 |
sync_notify: Arc::new(DashMap::new()), |
| 506 |
sse_connections: Arc::new(DashMap::new()), |
| 507 |
notes_cache: Arc::new(git::notes::NotesCache::default()), |
| 508 |
}, |
| 509 |
limiters: AppLimiters { |
| 510 |
scan_semaphore: Arc::new(tokio::sync::Semaphore::new( |
| 511 |
constants::SCAN_MAX_CONCURRENT, |
| 512 |
)), |
| 513 |
caddy_ask_semaphore: Arc::new(tokio::sync::Semaphore::new( |
| 514 |
constants::CADDY_ASK_MAX_CONCURRENT, |
| 515 |
)), |
| 516 |
git_smart_http_semaphore: Arc::new(tokio::sync::Semaphore::new( |
| 517 |
constants::GIT_SMART_HTTP_MAX_CONCURRENT, |
| 518 |
)), |
| 519 |
}, |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
|
| 524 |
pub fn require_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 525 |
self.storage.require_s3() |
| 526 |
} |
| 527 |
|
| 528 |
|
| 529 |
pub fn require_synckit_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 530 |
self.storage.require_synckit_s3() |
| 531 |
} |
| 532 |
|
| 533 |
|
| 534 |
pub fn require_public_s3(&self) -> error::Result<&Arc<dyn StorageBackend>> { |
| 535 |
self.storage.require_public_s3() |
| 536 |
} |
| 537 |
} |
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
pub async fn delete_user_account( |
| 551 |
db: &sqlx::PgPool, |
| 552 |
caches: &AppCaches, |
| 553 |
user_id: db::UserId, |
| 554 |
) -> error::Result<()> { |
| 555 |
db::users::delete_user(db, user_id).await?; |
| 556 |
caches.domain_cache.retain(|_, uid| *uid != user_id); |
| 557 |
Ok(()) |
| 558 |
} |
| 559 |
|
| 560 |
|
| 561 |
pub fn build_app(state: &AppState, session_layer: SessionManagerLayer<PostgresStore>) -> Router { |
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
let csrf_routes = csrf::CsrfRouter::new() |
| 568 |
.merge(auth_routes(state.config.rate_limits)) |
| 569 |
.merge(api_routes(state.config.rate_limits)) |
| 570 |
.merge(storage_routes()) |
| 571 |
.merge(stripe_routes()) |
| 572 |
.merge(admin_routes(state.clone())) |
| 573 |
.merge(synckit_routes( |
| 574 |
state |
| 575 |
.config |
| 576 |
.synckit_jwt_secret |
| 577 |
.clone() |
| 578 |
.map(std::sync::Arc::new), |
| 579 |
)) |
| 580 |
.merge(oauth_routes()) |
| 581 |
.merge(postmark_routes()) |
| 582 |
.merge(git_issue_routes()) |
| 583 |
.merge(git_write_routes()) |
| 584 |
.merge(ota_routes()) |
| 585 |
.merge(rpm_routes()) |
| 586 |
.merge(build_routes()); |
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
|
| 591 |
|
| 592 |
|
| 593 |
|
| 594 |
|
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
let csrf_routes = quasi::mounts(state) |
| 599 |
.into_iter() |
| 600 |
.fold(csrf_routes, |routes, (path, described)| { |
| 601 |
routes.nest_service(path, described) |
| 602 |
}); |
| 603 |
|
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
let csrf_routes = quasi::document_mounts(state) |
| 608 |
.into_iter() |
| 609 |
.fold(csrf_routes, |routes, (path, described)| { |
| 610 |
routes.route_service(path, described) |
| 611 |
}); |
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
let csrf_routes = quasi::public_document_mounts(state) |
| 616 |
.into_iter() |
| 617 |
.fold(csrf_routes, |routes, (path, described)| { |
| 618 |
routes.route_service(path, described) |
| 619 |
}); |
| 620 |
|
| 621 |
|
| 622 |
let csrf_routes = quasi::public_mounts(state) |
| 623 |
.into_iter() |
| 624 |
.fold(csrf_routes, |routes, (path, described)| { |
| 625 |
routes.nest_service(path, described) |
| 626 |
}); |
| 627 |
let csrf_routes = csrf_routes.finalize(); |
| 628 |
let app = Router::new() |
| 629 |
.merge(page_routes(state.config.rate_limits)) |
| 630 |
.merge(sso_routes()) |
| 631 |
.merge(csrf_routes) |
| 632 |
.merge(git_routes()) |
| 633 |
.merge(routes::embed::embed_routes()) |
| 634 |
|
| 635 |
|
| 636 |
|
| 637 |
.nest_service("/spike", quasi_spike::router(Arc::clone(&state.docs))) |
| 638 |
.route( |
| 639 |
"/api/openapi.json", |
| 640 |
axum::routing::get(openapi::openapi_json), |
| 641 |
) |
| 642 |
.merge(utoipa_swagger_ui::SwaggerUi::new("/api/docs").url( |
| 643 |
"/api-docs/openapi.json", |
| 644 |
<openapi::ApiDoc as utoipa::OpenApi>::openapi(), |
| 645 |
)) |
| 646 |
|
| 647 |
|
| 648 |
|
| 649 |
|
| 650 |
|
| 651 |
|
| 652 |
|
| 653 |
|
| 654 |
|
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
|
| 670 |
|
| 671 |
|
| 672 |
|
| 673 |
|
| 674 |
.nest_service( |
| 675 |
concat!("/static/dist-", env!("STATIC_VERSION")), |
| 676 |
tower::ServiceBuilder::new() |
| 677 |
.layer(SetResponseHeaderLayer::overriding( |
| 678 |
axum::http::header::CACHE_CONTROL, |
| 679 |
HeaderValue::from_static("public, max-age=604800, immutable"), |
| 680 |
)) |
| 681 |
.service(ServeDir::new("static/dist")), |
| 682 |
) |
| 683 |
|
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
.nest_service( |
| 689 |
"/static/dist", |
| 690 |
tower::ServiceBuilder::new() |
| 691 |
.layer(SetResponseHeaderLayer::overriding( |
| 692 |
axum::http::header::CACHE_CONTROL, |
| 693 |
HeaderValue::from_static("public, no-cache"), |
| 694 |
)) |
| 695 |
.service(ServeDir::new("static/dist")), |
| 696 |
) |
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
|
| 701 |
|
| 702 |
|
| 703 |
.nest_service( |
| 704 |
"/static", |
| 705 |
tower::ServiceBuilder::new() |
| 706 |
.layer(SetResponseHeaderLayer::overriding( |
| 707 |
axum::http::header::CACHE_CONTROL, |
| 708 |
HeaderValue::from_static( |
| 709 |
"public, max-age=604800, stale-while-revalidate=86400", |
| 710 |
), |
| 711 |
)) |
| 712 |
.service(ServeDir::new("static")), |
| 713 |
) |
| 714 |
|
| 715 |
|
| 716 |
|
| 717 |
|
| 718 |
|
| 719 |
.method_not_allowed_fallback(error::method_not_allowed) |
| 720 |
.fallback(routes::custom_domain::custom_domain_fallback) |
| 721 |
.with_state(state.clone()); |
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
|
| 727 |
|
| 728 |
|
| 729 |
|
| 730 |
|
| 731 |
crate::rate_limit::start_governor_sweeper(); |
| 732 |
|
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
app.layer(middleware::from_fn( |
| 737 |
fragment_redirect::fragment_redirect_middleware, |
| 738 |
)) |
| 739 |
.layer(middleware::from_fn(request_timeout_middleware)) |
| 740 |
.layer(middleware::from_fn_with_state( |
| 741 |
state.clone(), |
| 742 |
access_gate::access_gate_middleware, |
| 743 |
)) |
| 744 |
.layer(middleware::from_fn_with_state( |
| 745 |
state.clone(), |
| 746 |
security_headers_middleware, |
| 747 |
)) |
| 748 |
.layer(middleware::from_fn(metrics::cache_control_middleware)) |
| 749 |
.layer(middleware::from_fn(metrics::metrics_middleware)) |
| 750 |
.layer(middleware::from_fn_with_state( |
| 751 |
state.clone(), |
| 752 |
metrics::idempotency_middleware, |
| 753 |
)) |
| 754 |
.layer(session_layer) |
| 755 |
.layer(RequestBodyLimitLayer::new(1024 * 1024)) |
| 756 |
|
| 757 |
|
| 758 |
|
| 759 |
|
| 760 |
.layer(middleware::from_fn_with_state( |
| 761 |
state.clone(), |
| 762 |
routes::user_pages::dispatch, |
| 763 |
)) |
| 764 |
} |
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_mins(2); |
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
fn timeout_exempt(path: &str) -> bool { |
| 782 |
path.starts_with("/git") |
| 783 |
|| path.starts_with("/api/export/") |
| 784 |
|| path.starts_with("/api/internal/creator/export/") |
| 785 |
|| path.starts_with("/api/sync/subscribe") |
| 786 |
|| path.starts_with("/api/v1/sync/subscribe") |
| 787 |
|| path.starts_with("/api/sync/ota") |
| 788 |
|| path.starts_with("/api/v1/sync/ota") |
| 789 |
} |
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
async fn request_timeout_middleware( |
| 797 |
request: axum::http::Request<axum::body::Body>, |
| 798 |
next: middleware::Next, |
| 799 |
) -> axum::response::Response { |
| 800 |
use axum::response::IntoResponse; |
| 801 |
if timeout_exempt(request.uri().path()) { |
| 802 |
return next.run(request).await; |
| 803 |
} |
| 804 |
match tokio::time::timeout(REQUEST_TIMEOUT, next.run(request)).await { |
| 805 |
Ok(response) => response, |
| 806 |
Err(_) => (axum::http::StatusCode::GATEWAY_TIMEOUT, "Request timed out").into_response(), |
| 807 |
} |
| 808 |
} |
| 809 |
|
| 810 |
|
| 811 |
|
| 812 |
async fn security_headers_middleware( |
| 813 |
axum::extract::State(state): axum::extract::State<AppState>, |
| 814 |
request: axum::http::Request<axum::body::Body>, |
| 815 |
next: middleware::Next, |
| 816 |
) -> axum::response::Response { |
| 817 |
let path = request.uri().path(); |
| 818 |
let is_embed = path.starts_with("/embed/"); |
| 819 |
|
| 820 |
|
| 821 |
|
| 822 |
|
| 823 |
|
| 824 |
let is_oauth_authorize = path == "/oauth/authorize"; |
| 825 |
let mut response = next.run(request).await; |
| 826 |
let headers = response.headers_mut(); |
| 827 |
|
| 828 |
|
| 829 |
|
| 830 |
|
| 831 |
|
| 832 |
let report_endpoint = format!( |
| 833 |
"{}/api/csp-report", |
| 834 |
state.config.host_url.trim_end_matches('/') |
| 835 |
); |
| 836 |
let reporting = format!("; report-uri {report_endpoint}; report-to mnw-csp"); |
| 837 |
if let Ok(value) = HeaderValue::from_str(&format!("mnw-csp=\"{report_endpoint}\"")) { |
| 838 |
headers.insert( |
| 839 |
axum::http::header::HeaderName::from_static("reporting-endpoints"), |
| 840 |
value, |
| 841 |
); |
| 842 |
} |
| 843 |
|
| 844 |
if is_embed { |
| 845 |
|
| 846 |
|
| 847 |
|
| 848 |
|
| 849 |
|
| 850 |
|
| 851 |
|
| 852 |
headers.insert( |
| 853 |
axum::http::header::X_FRAME_OPTIONS, |
| 854 |
HeaderValue::from_static("ALLOWALL"), |
| 855 |
); |
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
let embed_csp = format!( |
| 861 |
"default-src 'none'; \ |
| 862 |
img-src 'self' data: https:; \ |
| 863 |
media-src 'self'; \ |
| 864 |
style-src 'unsafe-inline'; \ |
| 865 |
script-src 'self'; \ |
| 866 |
font-src 'self'; \ |
| 867 |
base-uri 'none'; \ |
| 868 |
form-action 'none'; \ |
| 869 |
frame-ancestors *{reporting}" |
| 870 |
); |
| 871 |
if let Ok(value) = HeaderValue::from_str(&embed_csp) { |
| 872 |
headers.insert( |
| 873 |
axum::http::header::HeaderName::from_static("content-security-policy"), |
| 874 |
value, |
| 875 |
); |
| 876 |
} |
| 877 |
} else { |
| 878 |
|
| 879 |
headers.insert( |
| 880 |
axum::http::header::X_FRAME_OPTIONS, |
| 881 |
HeaderValue::from_static("DENY"), |
| 882 |
); |
| 883 |
|
| 884 |
let s3_origin = std::env::var("S3_ENDPOINT").unwrap_or_default(); |
| 885 |
let s3_origin = s3_origin.as_str(); |
| 886 |
let cdn = state.config.cdn_base_url.as_str(); |
| 887 |
let storage_origins = match (s3_origin.is_empty(), cdn.is_empty()) { |
| 888 |
(false, false) => format!(" {s3_origin} {cdn}"), |
| 889 |
(false, true) => format!(" {s3_origin}"), |
| 890 |
(true, false) => format!(" {cdn}"), |
| 891 |
(true, true) => String::new(), |
| 892 |
}; |
| 893 |
|
| 894 |
|
| 895 |
let scheme = if state.config.host_url.starts_with("https") { |
| 896 |
"https" |
| 897 |
} else { |
| 898 |
"http" |
| 899 |
}; |
| 900 |
let user_pages_origin = format!("{scheme}://{}", state.config.user_pages_host); |
| 901 |
let form_action = if is_oauth_authorize { |
| 902 |
"'self' http://127.0.0.1:* http://[::1]:* http://localhost:*" |
| 903 |
} else { |
| 904 |
"'self'" |
| 905 |
}; |
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
let policy = |style_src: &str| { |
| 912 |
format!( |
| 913 |
"default-src 'self'; \ |
| 914 |
script-src 'self' https://js.stripe.com; \ |
| 915 |
style-src {style_src}; \ |
| 916 |
img-src 'self' data: https:; \ |
| 917 |
font-src 'self'; \ |
| 918 |
connect-src 'self' https://api.stripe.com{storage_origins}; \ |
| 919 |
media-src 'self'{storage_origins}; \ |
| 920 |
frame-src 'self' https://js.stripe.com {user_pages_origin}; \ |
| 921 |
base-uri 'self'; \ |
| 922 |
form-action {form_action}; \ |
| 923 |
frame-ancestors 'none'{reporting}" |
| 924 |
) |
| 925 |
}; |
| 926 |
if let Ok(value) = HeaderValue::from_str(&policy("'self' 'unsafe-inline'")) { |
| 927 |
headers.insert( |
| 928 |
axum::http::header::HeaderName::from_static("content-security-policy"), |
| 929 |
value, |
| 930 |
); |
| 931 |
} |
| 932 |
|
| 933 |
|
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 939 |
|
| 940 |
if let Ok(value) = HeaderValue::from_str(&policy("'self'")) { |
| 941 |
headers.insert( |
| 942 |
axum::http::header::HeaderName::from_static("content-security-policy-report-only"), |
| 943 |
value, |
| 944 |
); |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
headers.insert( |
| 949 |
axum::http::header::HeaderName::from_static("strict-transport-security"), |
| 950 |
HeaderValue::from_static("max-age=31536000; includeSubDomains"), |
| 951 |
); |
| 952 |
headers.insert( |
| 953 |
axum::http::header::X_CONTENT_TYPE_OPTIONS, |
| 954 |
HeaderValue::from_static("nosniff"), |
| 955 |
); |
| 956 |
headers.insert( |
| 957 |
axum::http::header::REFERRER_POLICY, |
| 958 |
HeaderValue::from_static("strict-origin-when-cross-origin"), |
| 959 |
); |
| 960 |
headers.insert( |
| 961 |
axum::http::header::HeaderName::from_static("permissions-policy"), |
| 962 |
HeaderValue::from_static("camera=(), microphone=(), geolocation=()"), |
| 963 |
); |
| 964 |
response |
| 965 |
} |
| 966 |
|
| 967 |
#[cfg(test)] |
| 968 |
mod from_ref_slices { |
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
|
| 974 |
|
| 975 |
use super::*; |
| 976 |
|
| 977 |
fn assert_from_ref<T: FromRef<AppState>>() {} |
| 978 |
|
| 979 |
#[test] |
| 980 |
fn slices_are_extractable() { |
| 981 |
|
| 982 |
assert_from_ref::<sqlx::PgPool>(); |
| 983 |
assert_from_ref::<Config>(); |
| 984 |
assert_from_ref::<EmailClient>(); |
| 985 |
assert_from_ref::<background::BackgroundTx>(); |
| 986 |
|
| 987 |
assert_from_ref::<AppStorage>(); |
| 988 |
assert_from_ref::<AppCaches>(); |
| 989 |
assert_from_ref::<AppLimiters>(); |
| 990 |
|
| 991 |
assert_from_ref::<Billing>(); |
| 992 |
assert_from_ref::<Integrations>(); |
| 993 |
assert_from_ref::<Scanning>(); |
| 994 |
assert_from_ref::<Sync>(); |
| 995 |
assert_from_ref::<Git>(); |
| 996 |
assert_from_ref::<Ops>(); |
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
assert_from_ref::<monitor::MonitorCtx>(); |
| 1001 |
assert_from_ref::<build_runner::BuildCtx>(); |
| 1002 |
} |
| 1003 |
} |
| 1004 |
|
| 1005 |
#[cfg(test)] |
| 1006 |
mod timeout_exempt_tests { |
| 1007 |
use super::timeout_exempt; |
| 1008 |
|
| 1009 |
#[test] |
| 1010 |
fn exempts_only_anchored_long_running_routes() { |
| 1011 |
|
| 1012 |
for p in [ |
| 1013 |
"/git/foo/bar.git/info/refs", |
| 1014 |
"/api/export/content", |
| 1015 |
"/api/internal/creator/export/sales", |
| 1016 |
"/api/sync/subscribe", |
| 1017 |
"/api/v1/sync/subscribe", |
| 1018 |
"/api/sync/ota/apps/x/releases", |
| 1019 |
"/api/v1/sync/ota/slug/macos/arm64/1.0.0", |
| 1020 |
] { |
| 1021 |
assert!(timeout_exempt(p), "{p} should be exempt"); |
| 1022 |
} |
| 1023 |
|
| 1024 |
for p in [ |
| 1025 |
"/dashboard/export", |
| 1026 |
"/u/somecreator/export-notes", |
| 1027 |
"/items/sync/ota-recap", |
| 1028 |
] { |
| 1029 |
assert!(!timeout_exempt(p), "{p} must not be exempt"); |
| 1030 |
} |
| 1031 |
} |
| 1032 |
} |
| 1033 |
|