Skip to main content

max / makenotwork

34.0 KB · 849 lines History Blame Raw
1 //! Test harness for in-process integration tests.
2
3 pub(crate) mod client;
4 pub(crate) mod db;
5 pub(crate) mod email;
6 pub(crate) mod faults;
7 pub(crate) mod gitfixture;
8 pub(crate) mod parity;
9 pub(crate) mod seed;
10 pub(crate) mod storage;
11 pub(crate) mod stripe;
12
13 #[allow(unused_imports)]
14 pub(crate) use seed::{seed_project, seed_user};
15
16 /// CDN render base every test app uses unless `Opts::cdn_base_url` overrides it.
17 /// `Config::cdn_base_url` is required, so tests always have one.
18 pub(crate) const TEST_CDN_BASE: &str = "https://cdn.test";
19
20 /// Compute SHA-256 hash of a SyncKit API key (mirrors server's hash_api_key).
21 pub(crate) fn hash_api_key(api_key: &str) -> String {
22 use sha2::Digest;
23 hex::encode(sha2::Sha256::digest(api_key.as_bytes()))
24 }
25
26 use docengine::DocLoader;
27
28 /// The real published docs, parsed once per test binary.
29 ///
30 /// The harness used to build a loader with `sections: vec![]` against `"."`, so
31 /// under test the site had no doc pages at all and nothing could cover `/docs`
32 /// or the docs half of the sitemap. Loading the real tree costs a parse, which
33 /// is why it is shared rather than rebuilt per `TestHarness::new`, and it goes
34 /// through `site_docs::build_doc_loader` so the config cannot drift from the
35 /// one production uses.
36 fn site_docs() -> Arc<DocLoader> {
37 static DOCS: std::sync::OnceLock<Arc<DocLoader>> = std::sync::OnceLock::new();
38 DOCS.get_or_init(|| {
39 let assumptions = makenotwork::site_docs::load_assumptions()
40 .expect("tests run from the crate root, where the assumptions file is");
41 Arc::new(makenotwork::site_docs::build_doc_loader(assumptions))
42 })
43 .clone()
44 }
45 use makenotwork::config::{
46 BuildConfig, Config, CreatorTierPricing, EmailWebhookConfig, IntegrationsConfig, ScanConfig,
47 StripeConfig,
48 };
49 use makenotwork::db::UserId;
50 use makenotwork::email::{EmailClient, EmailConfig};
51 use makenotwork::payments::{PaymentProvider, StripeClient};
52 use makenotwork::scanning::ScanPipeline;
53 use makenotwork::{AppState, AppStateParts, AppStorage, build_app};
54 use sqlx::PgPool;
55 use std::sync::Arc;
56 use tower_sessions::cookie::SameSite;
57 use tower_sessions::cookie::time::Duration as CookieDuration;
58 use tower_sessions::{Expiry, SessionManagerLayer};
59 use tower_sessions_sqlx_store::PostgresStore;
60
61 use self::client::TestClient;
62 use self::db::TestDb;
63 use self::storage::InMemoryStorage;
64
65 /// Result of setting up a test creator with project and item.
66 #[allow(dead_code)]
67 pub(crate) struct CreatorSetup {
68 pub user_id: UserId,
69 pub project_id: String,
70 pub item_id: String,
71 pub slug: String,
72 }
73
74 /// Options for customizing a test harness build.
75 #[derive(Default)]
76 pub(crate) struct BuildOptions {
77 pub storage: Option<Arc<InMemoryStorage>>,
78 pub synckit_storage: Option<Arc<InMemoryStorage>>,
79 pub stripe_client: Option<Arc<dyn PaymentProvider>>,
80 pub scanner: Option<Arc<ScanPipeline>>,
81 pub admin_user_id: Option<UserId>,
82 pub existing_db: Option<TestDb>,
83 pub postmark_webhook_token: Option<String>,
84 pub postmark_broadcast_webhook_token: Option<String>,
85 pub git_repos_path: Option<String>,
86 pub build_trigger_token: Option<String>,
87 pub postmark_inbound_webhook_token: Option<String>,
88 pub mt_base_url: Option<String>,
89 pub internal_shared_secret: Option<String>,
90 pub cli_service_token: Option<String>,
91 pub mock_email: Option<Arc<email::MockEmailTransport>>,
92 /// Overrides the CDN render base. `None` uses [`TEST_CDN_BASE`]; the base is
93 /// required config, so there is no "no CDN" mode to opt into.
94 pub cdn_base_url: Option<String>,
95 /// Site access gate. Defaults to `Open`; set to `FanPlusOrCreator` to test
96 /// the testnot-style gate.
97 pub access_gate: makenotwork::config::AccessGate,
98 /// Delegated-login (SSO) provider config. `None` = local password form.
99 pub sso: Option<makenotwork::config::SsoConfig>,
100 /// Sticker monthly creator-tier price IDs. `None` = empty (creator-tier
101 /// checkout is unconfigured and bails). Set to exercise creator-tier flows.
102 pub creator_tier_prices:
103 Option<std::collections::HashMap<makenotwork::db::CreatorTier, String>>,
104 /// Rate-limit profile. `None` relaxes the limits, which is what almost every
105 /// test wants: a test that logs in six times is not asking to be throttled.
106 /// Set `Some(RateLimits::production())` to assert the thresholds that ship,
107 /// which is what `workflows::rate_limiting` does.
108 pub rate_limits: Option<makenotwork::constants::RateLimits>,
109 /// Whether founder pricing is on offer. Defaults to closed, which is the
110 /// state every pre-existing test was written against. Set it to exercise
111 /// the surfaces that only exist while the window is open.
112 pub founder_window_open: bool,
113 /// Which screens serve from the description layer. Empty by default, so a
114 /// test asserting the served HTML keeps asserting the Askama one until a
115 /// conversion's own test opts in.
116 pub quasi_screens: makenotwork::config::QuasiScreens,
117 }
118
119 /// Full test harness: isolated database, in-process app, cookie-aware client.
120 #[allow(dead_code)]
121 pub(crate) struct TestHarness {
122 pub client: TestClient,
123 pub db: PgPool,
124 pub storage: Option<Arc<InMemoryStorage>>,
125 /// Mock email transport, if configured. Use `.sent()` to inspect sent emails.
126 pub mock_email: Option<Arc<email::MockEmailTransport>>,
127 /// Mock payment provider, if configured. Use `.checkouts()` to inspect created sessions.
128 pub mock_stripe: Option<Arc<stripe::MockPaymentProvider>>,
129 /// Pieces needed to drain the scan worker synchronously from tests
130 /// (`drain_scan_jobs`). `None` when the harness wasn't built with a scanner.
131 scan_deps: Option<ScanDeps>,
132 /// The assembled state, kept so tests can drive scheduler jobs that take it.
133 /// `build_app` borrows rather than consumes it, so this costs a cheap clone.
134 state: makenotwork::AppState,
135 _test_db: TestDb,
136 }
137
138 struct ScanDeps {
139 s3: Arc<dyn makenotwork::storage::StorageBackend>,
140 pipeline: Arc<ScanPipeline>,
141 semaphore: Arc<tokio::sync::Semaphore>,
142 }
143
144 impl TestHarness {
145 /// Spin up a fresh database, build the app, and return a ready-to-use harness.
146 pub(crate) async fn new() -> Self {
147 Self::build(BuildOptions::default()).await
148 }
149
150 /// Harness whose router carries the rate limits that ship, rather than the
151 /// relaxed profile every other harness uses. This is the only way to assert
152 /// the real thresholds, and the reason the limits are runtime config: under
153 /// the old `fast-tests` feature the two profiles could not coexist in one
154 /// run, so CI exercised the relaxed limiter and never the production one.
155 #[allow(dead_code)]
156 pub(crate) async fn with_production_rate_limits() -> Self {
157 Self::build(BuildOptions {
158 rate_limits: Some(makenotwork::constants::RateLimits::production()),
159 ..Default::default()
160 })
161 .await
162 }
163
164 /// Harness with founder pricing on offer. Every other harness runs with the
165 /// window shut, so this is the only way to reach the banner and the
166 /// list/founder toggle on `/pricing`.
167 #[allow(dead_code)]
168 pub(crate) async fn with_founder_window_open() -> Self {
169 Self::build(BuildOptions {
170 founder_window_open: true,
171 ..Default::default()
172 })
173 .await
174 }
175
176 /// Harness with in-memory storage backend.
177 #[allow(dead_code)]
178 pub(crate) async fn with_storage() -> Self {
179 let mem = Arc::new(InMemoryStorage::new());
180 Self::build(BuildOptions {
181 storage: Some(mem),
182 ..Default::default()
183 })
184 .await
185 }
186
187 /// Harness with SyncKit in-memory storage backend (for OTA tests).
188 #[allow(dead_code)]
189 pub(crate) async fn with_synckit_storage() -> Self {
190 let mem = Arc::new(InMemoryStorage::new());
191 Self::build(BuildOptions {
192 synckit_storage: Some(mem),
193 ..Default::default()
194 })
195 .await
196 }
197
198 /// Harness with in-memory storage + file scanning pipeline.
199 #[allow(dead_code)]
200 pub(crate) async fn with_storage_and_scanner() -> Self {
201 let mem = Arc::new(InMemoryStorage::new());
202 let scanner = Self::no_op_scanner();
203 Self::build(BuildOptions {
204 storage: Some(mem),
205 scanner: Some(Arc::new(scanner)),
206 ..Default::default()
207 })
208 .await
209 }
210
211 /// Harness with admin user + in-memory storage + file scanning pipeline.
212 /// Returns (harness, admin_user_id).
213 #[allow(dead_code)]
214 pub(crate) async fn with_admin_storage_and_scanner() -> (Self, UserId) {
215 let test_db = TestDb::new().await;
216 let pool = test_db.pool.clone();
217 let admin_id = Self::insert_admin_user(&pool).await;
218
219 let mem = Arc::new(InMemoryStorage::new());
220 let scanner = Self::no_op_scanner();
221 let harness = Self::build(BuildOptions {
222 storage: Some(mem),
223 scanner: Some(Arc::new(scanner)),
224 admin_user_id: Some(admin_id),
225 existing_db: Some(test_db),
226 ..Default::default()
227 })
228 .await;
229 (harness, admin_id)
230 }
231
232 /// Harness with Stripe client configured (fake key, known webhook secrets).
233 #[allow(dead_code)]
234 pub(crate) async fn with_stripe() -> Self {
235 let stripe_config = StripeConfig {
236 secret_key: "sk_test_fake_key_for_testing".to_string(),
237 webhook_secret: vec![stripe::TEST_WEBHOOK_SECRET.to_string()],
238 webhook_secret_v2: Some(stripe::TEST_WEBHOOK_SECRET_V2.to_string()),
239 };
240 let stripe_client: Arc<dyn PaymentProvider> =
241 Arc::new(StripeClient::new(&stripe_config).expect("test Stripe client builds"));
242 Self::build(BuildOptions {
243 stripe_client: Some(stripe_client),
244 ..Default::default()
245 })
246 .await
247 }
248
249 /// Harness with mock Stripe + mock email for full payment flow testing.
250 /// Access mocks via `harness.mock_stripe` and `harness.mock_email`.
251 #[allow(dead_code)]
252 pub(crate) async fn with_mocks() -> Self {
253 let mock_stripe = Arc::new(stripe::MockPaymentProvider::new());
254 let mock_email = Arc::new(email::MockEmailTransport::new());
255 let mem = Arc::new(InMemoryStorage::new());
256 let mut harness = Self::build(BuildOptions {
257 storage: Some(mem),
258 stripe_client: Some(mock_stripe.clone() as Arc<dyn PaymentProvider>),
259 mock_email: Some(mock_email),
260 ..Default::default()
261 })
262 .await;
263 harness.mock_stripe = Some(mock_stripe);
264 harness
265 }
266
267 /// Harness wired for creator-tier checkout: mock Stripe plus a configured
268 /// sticker price for the Everything tier (the founder window stays closed,
269 /// so checkout uses the sticker price ID, the mock ignores it anyway).
270 /// Exposes `mock_stripe` for asserting on the trial passed to Stripe.
271 #[allow(dead_code)]
272 pub(crate) async fn with_creator_tier_checkout() -> Self {
273 let mock_stripe = Arc::new(stripe::MockPaymentProvider::new());
274 let mut prices = std::collections::HashMap::new();
275 prices.insert(
276 makenotwork::db::CreatorTier::Everything,
277 "price_test_everything".to_string(),
278 );
279 let mut harness = Self::build(BuildOptions {
280 storage: Some(Arc::new(InMemoryStorage::new())),
281 stripe_client: Some(mock_stripe.clone() as Arc<dyn PaymentProvider>),
282 creator_tier_prices: Some(prices),
283 ..Default::default()
284 })
285 .await;
286 harness.mock_stripe = Some(mock_stripe);
287 harness
288 }
289
290 /// Harness with admin user configured. Returns (harness, admin_user_id).
291 #[allow(dead_code)]
292 pub(crate) async fn with_admin() -> (Self, UserId) {
293 let test_db = TestDb::new().await;
294 let pool = test_db.pool.clone();
295 let admin_id = Self::insert_admin_user(&pool).await;
296
297 let harness = Self::build(BuildOptions {
298 admin_user_id: Some(admin_id),
299 existing_db: Some(test_db),
300 ..Default::default()
301 })
302 .await;
303 (harness, admin_id)
304 }
305
306 /// Harness with Postmark webhook token configured.
307 #[allow(dead_code)]
308 pub(crate) async fn with_postmark() -> Self {
309 Self::build(BuildOptions {
310 postmark_webhook_token: Some("test-postmark-token".to_string()),
311 postmark_broadcast_webhook_token: Some("test-broadcast-token".to_string()),
312 ..Default::default()
313 })
314 .await
315 }
316
317 /// Harness with git repos path configured.
318 #[allow(dead_code)]
319 pub(crate) async fn with_git_repos(path: String) -> Self {
320 Self::build(BuildOptions {
321 git_repos_path: Some(path),
322 ..Default::default()
323 })
324 .await
325 }
326
327 /// Insert an admin user and return the ID.
328 async fn insert_admin_user(pool: &PgPool) -> UserId {
329 let password_hash =
330 makenotwork::auth::hash_password("password123").expect("hash_password for admin");
331 sqlx::query_scalar(
332 "INSERT INTO users (username, email, password_hash, email_verified)
333 VALUES ('admin', 'admin@test.com', $1, true)
334 RETURNING id",
335 )
336 .bind(&password_hash)
337 .fetch_one(pool)
338 .await
339 .expect("Failed to insert admin user")
340 }
341
342 /// Create a no-op scan pipeline for tests.
343 fn no_op_scanner() -> ScanPipeline {
344 let scan_config = ScanConfig {
345 clamav_socket: None,
346 yara_rules_dir: "/nonexistent".to_string(),
347 malwarebazaar_enabled: false,
348 urlhaus_enabled: false,
349 abuse_ch_auth_key: None,
350 metadefender_api_key: None,
351 yara_min_rule_files: 0,
352 clamav_max_scan_bytes: None,
353 };
354 ScanPipeline::new(&scan_config).expect("ScanPipeline::new with no-op config")
355 }
356
357 /// Builder shared by all constructors. Public so workflow tests can use custom `BuildOptions`.
358 pub(crate) async fn build(opts: BuildOptions) -> Self {
359 // `main` does this for the real binary; tests never run `main`, and
360 // without it the first Stripe connector build panics inside rustls.
361 makenotwork::crypto::install_default_crypto_provider();
362
363 let t0 = std::time::Instant::now();
364 let test_db = match opts.existing_db {
365 Some(db) => db,
366 None => TestDb::new().await,
367 };
368 let pool = test_db.pool.clone();
369
370 // Create session store (migration already applied in template DB)
371 let session_store = PostgresStore::new(pool.clone());
372 if !test_db.session_migrated {
373 session_store
374 .migrate()
375 .await
376 .expect("Failed to migrate session store");
377 }
378
379 let session_layer = SessionManagerLayer::new(session_store)
380 .with_secure(false)
381 .with_same_site(SameSite::Lax)
382 .with_expiry(Expiry::OnInactivity(CookieDuration::days(1)));
383
384 // Minimal config, no S3, no Stripe (those come from opts)
385 let config = Config {
386 host: "127.0.0.1".parse().unwrap(),
387 port: 0,
388 database_url: String::new(),
389 host_url: std::sync::Arc::from("http://localhost:3000"),
390 signing_secret: "test-signing-secret-for-integration-tests".to_string(),
391 storage: None,
392 synckit_storage: None,
393 public_storage: None,
394 stripe: None,
395 admin_user_id: opts.admin_user_id,
396 synckit_jwt_secret: Some("test-synckit-jwt-secret".to_string()),
397 scan: None,
398 cdn_base_url: opts
399 .cdn_base_url
400 .clone()
401 .unwrap_or_else(|| TEST_CDN_BASE.to_string()),
402 user_pages_host: std::sync::Arc::from("u.localhost"),
403 access_gate: opts.access_gate,
404 sso: opts.sso.clone(),
405 rate_limits: opts
406 .rate_limits
407 .unwrap_or_else(makenotwork::constants::RateLimits::relaxed),
408 // Askama everywhere unless a test says otherwise, matching every
409 // deployment until wave 2 flips a screen.
410 quasi_screens: opts.quasi_screens.clone(),
411 build: BuildConfig {
412 trigger_token: opts.build_trigger_token,
413 host_linux: None,
414 host_darwin: None,
415 git_repos_path: opts.git_repos_path,
416 git_ssh_host: None,
417 },
418 email_webhooks: EmailWebhookConfig {
419 webhook_token: opts.postmark_webhook_token,
420 broadcast_webhook_token: opts.postmark_broadcast_webhook_token,
421 inbound_webhook_token: opts.postmark_inbound_webhook_token,
422 enforce_sender_auth: true,
423 },
424 creator_pricing: CreatorTierPricing {
425 fan_plus_price_id: None,
426 tier_prices: opts.creator_tier_prices.unwrap_or_default(),
427 tier_annual_prices: std::collections::HashMap::new(),
428 tier_founder_prices: std::collections::HashMap::new(),
429 tier_founder_annual_prices: std::collections::HashMap::new(),
430 founder_window_open: opts.founder_window_open,
431 },
432 integrations: IntegrationsConfig {
433 // Was hardcoded `None` while `BuildOptions::mt_base_url` fed
434 // `mt_client` alone, so a test could ask for Multithreaded and
435 // get a client with no config behind it. Anything reading the
436 // config (the described forum-memberships screens do) saw it as
437 // unconfigured and refused. Default is still `None`.
438 mt_base_url: opts.mt_base_url.clone(),
439 wam_url: None,
440 internal_shared_secret: opts.internal_shared_secret.clone(),
441 cli_service_token: opts.cli_service_token.clone(),
442 alerts_ingest_token: None,
443 },
444 };
445
446 let mock_email_ref = opts.mock_email.clone();
447 let email = if let Some(ref mock) = opts.mock_email {
448 EmailClient::with_transport(mock.clone() as Arc<dyn makenotwork::email::EmailTransport>)
449 } else {
450 EmailClient::new(
451 EmailConfig {
452 postmark_token: None,
453 from_address: "test@makenot.work".to_string(),
454 from_name: "Test".to_string(),
455 },
456 Some(pool.clone()),
457 )
458 };
459
460 let rp_origin = url::Url::parse(&config.host_url).expect("test HOST_URL");
461 let rp_id = rp_origin
462 .host_str()
463 .expect("test HOST_URL host")
464 .to_string();
465 let webauthn = Arc::new(
466 webauthn_rs::WebauthnBuilder::new(&rp_id, &rp_origin)
467 .expect("WebauthnBuilder")
468 .rp_name("Test")
469 .build()
470 .expect("Webauthn"),
471 );
472
473 // Convert InMemoryStorage to trait object
474 let storage = opts.storage;
475 let s3 = storage
476 .clone()
477 .map(|s| s as Arc<dyn makenotwork::storage::StorageBackend>);
478 let synckit_s3 = opts
479 .synckit_storage
480 .map(|s| s as Arc<dyn makenotwork::storage::StorageBackend>);
481 // Public bucket shares the same in-memory backend as `s3` (one flat map,
482 // no bucket isolation) so the cross-bucket image promote resolves.
483 let public_s3 = s3.clone();
484
485 // Route through the same `AppState::build` constructor production uses
486 // (main.rs), so the derived in-memory state, start timestamps, the empty
487 // cache maps, the concurrency semaphores, has a single source of truth.
488 // The harness only supplies the externally-wired dependencies.
489 let state = AppState::build(AppStateParts {
490 db: pool.clone(),
491 config,
492 storage: AppStorage {
493 s3,
494 synckit_s3,
495 public_s3,
496 },
497 stripe: opts.stripe_client,
498 email,
499 docs: site_docs(),
500 tier_prices: {
501 // Install the process-global TierPrices so handler code paths
502 // that call CreatorTier::{price_cents,max_file_bytes,
503 // max_storage_bytes} work under test (they read the global,
504 // same as production). Idempotent across tests.
505 makenotwork::tier_prices::TierPrices::install_test_default();
506 makenotwork::tier_prices::TierPrices::global().clone()
507 },
508 runway_config: makenotwork::tier_prices::RunwayConfig::default(),
509 fee_calculator: makenotwork::fee_calculator::FeeCalculator::load(
510 "docs/business/assumptions.toml",
511 ),
512 scanner: opts.scanner,
513 webauthn,
514 syntax: None,
515 mt_client: opts
516 .mt_base_url
517 .zip(opts.internal_shared_secret)
518 .map(|(url, secret)| makenotwork::mt_client::MtClient::new(url, secret)),
519 wam: None,
520 domain_cache: Arc::new(dashmap::DashMap::new()),
521 metrics_handle: None,
522 page_view_tx: makenotwork::db::page_views::spawn_batcher(pool.clone()),
523 bg: makenotwork::background::spawn_pool_detached(),
524 });
525
526 // Capture scan deps before `build_app` consumes `state`.
527 let scan_deps = match (state.scanner.clone(), state.storage.s3.clone()) {
528 (Some(pipeline), Some(s3)) => Some(ScanDeps {
529 s3,
530 pipeline,
531 semaphore: state.limiters.scan_semaphore.clone(),
532 }),
533 _ => None,
534 };
535
536 let app = build_app(&state, session_layer);
537 let client = TestClient::new(app);
538
539 // Extract mock_stripe: if the stripe_client is a MockPaymentProvider,
540 // we stored the Arc in BuildOptions.stripe_client. We can't downcast the
541 // trait object, so with_mocks() stores the mock ref separately. For the
542 // general build path, mock_stripe is None.
543 let mock_stripe = None; // Set by with_mocks() post-build via direct field access
544
545 let build_ms = t0.elapsed().as_millis();
546 if build_ms > 1000 {
547 eprintln!("[test-harness] SLOW harness build: {build_ms}ms");
548 }
549
550 TestHarness {
551 client,
552 db: pool,
553 storage,
554 mock_email: mock_email_ref,
555 mock_stripe,
556 scan_deps,
557 state,
558 _test_db: test_db,
559 }
560 }
561
562 /// Run the orphaned-upload reaper once, synchronously.
563 ///
564 /// The scheduler drives this on a tick in production. Tests that want the
565 /// reaper's failure branches (a transient S3 delete handed off to the
566 /// durable queue, a best-effort multipart abort) need it to run at a known
567 /// point instead, the same reason `drain_s3_deletions` exists.
568 #[allow(dead_code)]
569 pub(crate) async fn run_orphan_upload_reaper(&self) {
570 makenotwork::scheduler::cleanup_orphaned_uploads_for_test(&self.state).await;
571 }
572
573 /// Sign up a new user via POST /join. Returns the user's ID.
574 pub(crate) async fn signup(&mut self, username: &str, email: &str, password: &str) -> UserId {
575 // Fetch a page first to establish session + CSRF
576 self.client.fetch_csrf_token().await;
577
578 let body = format!(
579 "username={}&email={}&password={}",
580 urlencoding::encode(username),
581 urlencoding::encode(email),
582 urlencoding::encode(password),
583 );
584
585 let resp = self.client.post_form("/join/step/account", &body).await;
586 assert_eq!(
587 resp.status, 200,
588 "Signup failed with status {}: {}",
589 resp.status, resp.text
590 );
591
592 // Login rotates the CSRF token, fetch the new one
593 self.client.fetch_csrf_token().await;
594
595 // Look up the user in the database
596 sqlx::query_scalar::<_, UserId>("SELECT id FROM users WHERE username = $1")
597 .bind(username)
598 .fetch_one(&self.db)
599 .await
600 .expect("User not found after signup")
601 }
602
603 /// Grant creator permissions to a user via direct SQL.
604 pub(crate) async fn grant_creator(&self, user_id: UserId) {
605 sqlx::query("UPDATE users SET can_create_projects = true WHERE id = $1")
606 .bind(user_id)
607 .execute(&self.db)
608 .await
609 .expect("Failed to grant creator");
610 }
611
612 /// Trust a user for uploads via direct SQL.
613 pub(crate) async fn trust_user(&self, user_id: UserId) {
614 sqlx::query("UPDATE users SET upload_trusted = true WHERE id = $1")
615 .bind(user_id)
616 .execute(&self.db)
617 .await
618 .expect("Failed to trust user");
619 }
620
621 /// Give a user an active creator tier subscription via direct SQL.
622 /// Also syncs the denormalized `creator_tier` column on the users table.
623 pub(crate) async fn grant_tier(&self, user_id: UserId, tier: &str) {
624 sqlx::query(
625 r"INSERT INTO creator_subscriptions (user_id, stripe_subscription_id, stripe_customer_id, tier, status)
626 VALUES ($1, 'sub_test_' || $1::text, 'cus_test_' || $1::text, $2, 'active')
627 ON CONFLICT (user_id) DO UPDATE SET tier = $2, status = 'active'",
628 )
629 .bind(user_id)
630 .bind(tier)
631 .execute(&self.db)
632 .await
633 .expect("Failed to grant tier");
634
635 sqlx::query("UPDATE users SET creator_tier = $2 WHERE id = $1")
636 .bind(user_id)
637 .bind(tier)
638 .execute(&self.db)
639 .await
640 .expect("Failed to sync creator_tier");
641 }
642
643 /// Suspend a user via direct SQL.
644 #[allow(dead_code)]
645 pub(crate) async fn suspend_user(&self, user_id: UserId) {
646 sqlx::query("UPDATE users SET suspended_at = NOW(), suspension_reason = 'test suspension' WHERE id = $1")
647 .bind(user_id)
648 .execute(&self.db)
649 .await
650 .expect("Failed to suspend user");
651 }
652
653 /// POST a single login attempt and return the response. Refreshes the
654 /// CSRF token first so the new Manual-posture `/login` (Phase 2) accepts
655 /// the form even when a previous `/logout` invalidated the cached token.
656 /// Use this for negative-path login tests (lockout, suspended, wrong
657 /// password) that need to inspect the response rather than asserting
658 /// success like `login()` does.
659 pub(crate) async fn failed_login_attempt(
660 &mut self,
661 login: &str,
662 password: &str,
663 ) -> client::TestResponse {
664 self.client.fetch_csrf_token().await;
665 let body = format!(
666 "login={}&password={}",
667 urlencoding::encode(login),
668 urlencoding::encode(password),
669 );
670 self.client.post_form("/login", &body).await
671 }
672
673 /// Synchronously drain queued scan jobs by running the worker loop in-
674 /// process until the queue is empty. Mirrors the production worker pool
675 /// without spawning a background task, integration tests call this
676 /// between upload-confirm and any assertion on `scan_status`.
677 pub(crate) async fn drain_scan_jobs(&self) {
678 let Some(ctx) = self.scan_worker_context() else {
679 return;
680 };
681 // Hard cap to avoid an infinite loop if a job re-enqueues itself.
682 for _ in 0..256 {
683 match makenotwork::scanning::worker::process_next_for_test(&ctx).await {
684 Ok(true) => {}
685 Ok(false) => return,
686 Err(e) => panic!("scan worker drain failed: {e}"),
687 }
688 }
689 panic!("drain_scan_jobs did not terminate within 256 iterations");
690 }
691
692 /// Run one scan job and return its outcome instead of panicking on failure.
693 ///
694 /// `drain_scan_jobs` treats a failing job as a broken test, which is right
695 /// for the happy paths but makes the worker's failure branch unobservable:
696 /// a job whose download fails marks itself `failed` and resets its entity to
697 /// `HeldForReview`, and no test could reach that while the only entry point
698 /// panicked. `Ok(true)` ran a job, `Ok(false)` found an empty queue, `Err`
699 /// carries the message the worker recorded in `last_error`.
700 #[allow(dead_code)]
701 pub(crate) async fn try_process_one_scan_job(&self) -> Result<bool, String> {
702 let Some(ctx) = self.scan_worker_context() else {
703 return Ok(false);
704 };
705 makenotwork::scanning::worker::process_next_for_test(&ctx)
706 .await
707 .map_err(|e| e.to_string())
708 }
709
710 /// The worker context both drain paths run against. `None` when the harness
711 /// was not built with a scanner.
712 fn scan_worker_context(&self) -> Option<makenotwork::scanning::worker::WorkerContext> {
713 let deps = self.scan_deps.as_ref()?;
714 Some(makenotwork::scanning::worker::WorkerContext {
715 db: self.db.clone(),
716 s3: deps.s3.clone(),
717 pipeline: deps.pipeline.clone(),
718 scan_semaphore: deps.semaphore.clone(),
719 wam: None,
720 bg: makenotwork::background::spawn_pool_detached(),
721 // No Cloudflare purge in tests; quarantine still deletes from origin.
722 cloudflare: None,
723 cdn_base_url: std::sync::Arc::from(TEST_CDN_BASE),
724 // OTA artifacts scan from the SyncKit bucket; tests share one backend.
725 synckit_s3: Some(deps.s3.clone()),
726 // Public bucket shares the same backend; image promotes copy here.
727 public_s3: Some(deps.s3.clone()),
728 config: self.state.config.clone(),
729 })
730 }
731
732 /// Synchronously perform any queued S3 object deletions (`main` bucket).
733 /// Handler-side deletes only enqueue to `pending_s3_deletions`; the actual
734 /// delete is the scheduler's job in production. Tests that assert an object
735 /// was removed from storage call this first (the deterministic mirror of
736 /// the production retry worker). Returns the number of objects deleted.
737 pub(crate) async fn drain_s3_deletions(&self) -> usize {
738 let Some(storage) = self.storage.as_ref() else {
739 return 0;
740 };
741 makenotwork::scheduler::drain_pending_s3_deletions_for_test(&self.db, storage.as_ref())
742 .await
743 }
744
745 /// Log in as an existing user via POST /login. The client's session
746 /// cookies are updated automatically.
747 pub(crate) async fn login(&mut self, login: &str, password: &str) {
748 // Fetch CSRF token first
749 self.client.fetch_csrf_token().await;
750
751 let body = format!(
752 "login={}&password={}",
753 urlencoding::encode(login),
754 urlencoding::encode(password),
755 );
756
757 let resp = self.client.post_form("/login", &body).await;
758 assert_eq!(
759 resp.status, 303,
760 "Login failed with status {}: {}",
761 resp.status, resp.text
762 );
763
764 // Login rotates the CSRF token, fetch the new one
765 self.client.fetch_csrf_token().await;
766 }
767
768 /// Create a test creator: signup, grant creator access, re-login.
769 /// Uses password "password123" and email "{username}@test.com".
770 pub(crate) async fn create_creator(&mut self, username: &str) -> UserId {
771 let user_id = self
772 .signup(username, &format!("{username}@test.com"), "password123")
773 .await;
774 self.grant_creator(user_id).await;
775 self.client.post_form("/logout", "").await;
776 self.login(username, "password123").await;
777 user_id
778 }
779
780 /// Create a test creator with a project and one item. Creator is logged in afterward.
781 /// Project slug: "{username}-proj". Returns all created IDs.
782 pub(crate) async fn create_creator_with_item(
783 &mut self,
784 username: &str,
785 item_type: &str,
786 price_cents: i64,
787 ) -> CreatorSetup {
788 let user_id = self.create_creator(username).await;
789
790 // Usernames may contain underscores (valid for accounts) but project
791 // slugs may not, the slug charset is lowercase letters, digits, and
792 // hyphens only. Sanitize so a `seller_vis` creator yields `seller-vis-proj`.
793 let slug = format!("{}-proj", username.replace('_', "-"));
794 let resp = self
795 .client
796 .post_form("/api/projects", &format!("slug={slug}&title=Test+Project"))
797 .await;
798 assert_eq!(resp.status, 200, "Create project failed: {}", resp.text);
799 let project: serde_json::Value = resp.json();
800 let project_id = project["id"].as_str().unwrap().to_string();
801
802 let resp = self
803 .client
804 .post_form(
805 &format!("/api/projects/{project_id}/items"),
806 &format!("title=Test+Item&item_type={item_type}&price_cents={price_cents}"),
807 )
808 .await;
809 assert_eq!(resp.status, 200, "Create item failed: {}", resp.text);
810 let item: serde_json::Value = resp.json();
811 let item_id = item["id"].as_str().unwrap().to_string();
812
813 CreatorSetup {
814 user_id,
815 project_id,
816 item_id,
817 slug,
818 }
819 }
820
821 /// Connect a user's Stripe account via direct SQL.
822 /// Sets stripe_account_id, stripe_charges_enabled, and stripe_onboarding_complete.
823 /// Use after `create_creator()` for tests that need a Stripe-connected seller.
824 pub(crate) async fn connect_stripe(&self, user_id: UserId, account_id: &str) {
825 sqlx::query(
826 "UPDATE users SET stripe_account_id = $2, stripe_charges_enabled = true, \
827 stripe_onboarding_complete = true, stripe_payouts_enabled = true WHERE id = $1",
828 )
829 .bind(user_id)
830 .bind(account_id)
831 .execute(&self.db)
832 .await
833 .expect("Failed to connect Stripe");
834 }
835
836 /// Publish both a project and an item.
837 pub(crate) async fn publish_project_and_item(&mut self, project_id: &str, item_id: &str) {
838 self.client
839 .put_json(
840 &format!("/api/projects/{project_id}"),
841 r#"{"is_public": true}"#,
842 )
843 .await;
844 self.client
845 .put_form(&format!("/api/items/{item_id}"), "is_public=true")
846 .await;
847 }
848 }
849