Skip to main content

cratefield_testing/
conformance.rs

1//! The shared conformance suite (issue #9): every module must pass it.
2
3use cratefield_core::{
4    AnyError, BoxFuture, Config, ConfigError, EventHandler, EventName, HmacSigner, Migrations,
5    Module, ModuleContext, Port, Ports, UlidIdGen,
6};
7use std::sync::Arc;
8
9use crate::{TestHarness, request};
10
11/// Wraps a module so its `well_known` router (when present) carries a
12/// probe route the kit can request, proving where `Harness::router`
13/// mounted it (issue #46). Everything else delegates unchanged.
14struct WellKnownProbe {
15    inner: Arc<dyn Module>,
16}
17
18impl Module for WellKnownProbe {
19    fn name(&self) -> &'static str {
20        self.inner.name()
21    }
22    fn version(&self) -> &'static str {
23        self.inner.version()
24    }
25    fn harness_api(&self) -> u32 {
26        self.inner.harness_api()
27    }
28    fn requires(&self) -> &'static [Port] {
29        self.inner.requires()
30    }
31    fn optional(&self) -> &'static [Port] {
32        self.inner.optional()
33    }
34    fn tables(&self) -> &'static [&'static str] {
35        self.inner.tables()
36    }
37    /// Delegated, like `tables`, and for the same reason: the kit builds a
38    /// harness out of this wrapper, and `HarnessBuilder::build` validates a
39    /// module's personal-data declarations against the tables it claims. A
40    /// wrapper that answered core's empty default would hand every module a
41    /// build that checked declarations it could not see.
42    fn personal_data(&self) -> &'static [cratefield_core::PersonalDataSet] {
43        self.inner.personal_data()
44    }
45    fn emits(&self) -> &'static [&'static str] {
46        self.inner.emits()
47    }
48    fn public_writes(&self) -> bool {
49        self.inner.public_writes()
50    }
51    fn migrations(&self) -> Migrations {
52        self.inner.migrations()
53    }
54    fn validate_config(&self, cfg: &dyn Config) -> Result<(), ConfigError> {
55        self.inner.validate_config(cfg)
56    }
57    fn self_check(&self) -> Vec<String> {
58        self.inner.self_check()
59    }
60    fn router(&self, ctx: ModuleContext) -> axum::Router {
61        self.inner.router(ctx)
62    }
63    fn well_known(&self) -> Option<axum::Router> {
64        self.inner.well_known().map(|router| {
65            router.route(
66                WELL_KNOWN_PROBE_PATH,
67                axum::routing::get(|| async { "well-known" }),
68            )
69        })
70    }
71    fn events(&self) -> Vec<(EventName, EventHandler)> {
72        self.inner.events()
73    }
74    fn scheduled<'a>(
75        &'a self,
76        ctx: &'a ModuleContext,
77        cron: &'a str,
78    ) -> BoxFuture<'a, Result<(), AnyError>> {
79        self.inner.scheduled(ctx, cron)
80    }
81}
82
83/// Route the probe wrapper registers inside the module's well-known
84/// router; reachable at `/.well-known{WELL_KNOWN_PROBE_PATH}`.
85const WELL_KNOWN_PROBE_PATH: &str = "/conformance-probe";
86
87/// A [`Ports`] bundle with every [`Port`] wired to a fake, for checks that
88/// need a full bundle: conformance's visibility check (declared ports must
89/// survive [`Ports::view_for`], undeclared ones must be hidden), and a
90/// runtime proving it carries every port through a copy of its bundle.
91/// `dispatcher` and `tenants` are not ports and stay `None`.
92///
93/// # Panics
94///
95/// Only if the kit's own fixed signer secret or clock epoch is invalid.
96#[must_use]
97pub fn full_fake_ports() -> Ports {
98    let mut ports = Ports::empty();
99    ports.db = Some(Arc::new(crate::fakes::EmptyDatabase));
100    ports.auth = Some(Arc::new(crate::fakes::FakeAuth::new(
101        crate::fakes::AuthMode::Anonymous,
102    )));
103    ports.mailer = Some(Arc::new(crate::fakes::FakeMailer::new(
104        crate::fakes::MailerMode::SendOk,
105    )));
106    ports.captcha = Some(Arc::new(crate::fakes::FakeCaptcha::allow_all()));
107    ports.rate_limiter = Some(Arc::new(crate::fakes::FakeRateLimiter::always_allow()));
108    ports.signer = Some(Arc::new(
109        HmacSigner::new(crate::TEST_HARNESS_SECRET, None).expect("test secret is long enough"),
110    ));
111    ports.kv = Some(Arc::new(crate::fakes::MemoryKeyValue::new()));
112    ports.blob = Some(Arc::new(crate::fakes::MemoryBlob::new()));
113    ports.push = Some(Arc::new(crate::fakes::FakePush::new(
114        crate::fakes::PushMode::DeliverOk,
115    )));
116    ports.payments = Some(Arc::new(crate::fakes::FakePayments::new(
117        crate::fakes::PaymentsMode::Ok,
118    )));
119    ports.tracker = Some(Arc::new(crate::fakes::FakeTracker::new(
120        crate::fakes::TrackerMode::FileOk,
121    )));
122    ports.realtime = Some(Arc::new(crate::fakes::FakeRealtime::new()));
123    ports.text_model = Some(Arc::new(crate::fakes::FakeTextModel::default()));
124    ports.classifier = Some(Arc::new(crate::fakes::FakeClassifier::default()));
125    // The index's dimensions are the fake embedder's width: an index and
126    // the embedder feeding it must agree (issue #561).
127    ports.vector_index = Some(Arc::new(cratefield_core::ExactVectorIndex::new(
128        crate::fakes::FAKE_EMBEDDER_DIMENSIONS,
129    )));
130    ports.embedder = Some(Arc::new(crate::fakes::FakeEmbedder));
131    ports.custom_hostnames = Some(Arc::new(crate::fakes::FakeCustomHostnames::new(
132        "cratefield.app",
133    )));
134    ports.http = Some(Arc::new(crate::fakes::FakeHttpClient::ok_json("{}")));
135    ports.clock = Some(Arc::new(crate::fakes::FixedClock(
136        time::OffsetDateTime::from_unix_timestamp(1_800_000_000).expect("fixed epoch"),
137    )));
138    ports.id_gen = Some(Arc::new(UlidIdGen));
139    ports.defer = Some(Arc::new(crate::fakes::FakeDefer::new()));
140    ports
141}
142
143/// Runs the shared conformance suite against one module, once per
144/// dialect available in the environment (issue #20 — SQLite always,
145/// Postgres when `FZ_TEST_POSTGRES_URL` names a server):
146///
147/// 1. mounts under `/v1/<name>` and `/__health` lists it with its version;
148/// 2. a request under the module prefix is answered (no harness-level
149///    crash — module-specific routes are covered by the module's own
150///    tests via [`crate::request`]);
151/// 3. migrations apply from scratch **twice** on fresh databases
152///    (idempotence);
153/// 4. no undeclared port access: `Ports::view_for` hides every port the
154///    module did not declare;
155/// 5. two concurrent requests keep their own request ids (ADR 0007);
156/// 6. a well-known router, when provided, serves at the root under
157///    `/.well-known` and never under `/v1` (issue #46);
158/// 7. every table the module owns has a personal-data declaration, so a
159///    table cannot be added to `tables()` and left outside export and
160///    erasure (issue #244);
161/// 8. every table the module's **migrations** create is in `tables()`, so a
162///    table cannot come into being outside all three lists at once — and,
163///    the other way round, every table `tables()` names is one the scan
164///    actually found, so check 8 cannot pass by seeing nothing (issue #272).
165///
166/// # Panics
167///
168/// Panics with a message naming the failed check and the dialect.
169pub fn conformance(module: Box<dyn Module>) {
170    let inner: Arc<dyn Module> = Arc::from(module);
171    conformance_inner(&inner, true);
172}
173
174/// [`conformance`] without the sidecar parity axis (issue #64). `reason`
175/// is recorded in code and printed by the run, so a module that opts out
176/// says why in the same place it opts out. Use it only for a module that
177/// genuinely cannot be sidecar-mounted; "it fails" is not a reason.
178///
179/// # Panics
180///
181/// Panics when `reason` is empty, and on any conformance failure.
182pub fn conformance_in_process_only(module: Box<dyn Module>, reason: &str) {
183    assert!(
184        !reason.trim().is_empty(),
185        "conformance_in_process_only needs a reason: it is the only record of why \
186         `{}` is not checked for sidecar parity",
187        module.name()
188    );
189    eprintln!("[{}] sidecar parity axis skipped: {reason}", module.name());
190    let inner: Arc<dyn Module> = Arc::from(module);
191    conformance_inner(&inner, false);
192}
193
194/// The modules that own tables and have not said what is personal about
195/// them, with the tables still missing.
196///
197/// **Empty, and that is the deliverable** (issue #265). `auth-core`, `cms`,
198/// `email-signup`, `linkedin` and `waitlist` each sat here while they were
199/// being worked through, and each left as it was declared. The mechanism
200/// stays because the next module to grow a table before its declaration will
201/// want it — but an entry is a debt with a number on it, not a place to park
202/// one, and the list is checked empty by
203/// `no_module_is_exempt_from_the_personal_data_rule`.
204///
205/// An exemption is a loud silence rather than a quiet one. `HarnessBuilder::build`
206/// has always refused a declaration for a table a module does **not** own; the
207/// converse — a table with no declaration at all — is what actually happens,
208/// and what left `cratefield-module-notifications` holding addresses, device
209/// tokens and inbox rows outside the erasure catalogue through six migrations
210/// in two days (issue #244).
211///
212/// An entry names the tables, not just the module, so it cannot rot: a module
213/// that declares one of them fails until its entry is corrected or removed,
214/// and a module that grows a **new** undeclared table fails even while it is
215/// listed. Every exemption prints on the run that uses it.
216const UNDECLARED_TABLES: &[(&str, &[&str])] = &[];
217
218/// What [`personal_data_verdict`] found.
219enum Verdict {
220    /// Every table the module owns has a declaration.
221    Declared,
222    /// Listed in `UNDECLARED_TABLES`, and the entry still describes the
223    /// module exactly. Printed on the run rather than failing it.
224    Exempt(String),
225    /// The panic message.
226    Failed(String),
227}
228
229/// The personal-data rule, as a value rather than a panic (issue #244).
230///
231/// Split out from [`check_personal_data`] so the exemption's anti-rot half
232/// keeps a test after the list went empty: with nothing listed there is no
233/// module left to reach that branch through `conformance` itself, and a
234/// mechanism that only runs when somebody needs it is exactly the one that
235/// must not be allowed to quietly stop working in between.
236fn personal_data_verdict(
237    name: &str,
238    undeclared: &[&'static str],
239    exemptions: &[(&str, &[&str])],
240) -> Verdict {
241    let exempt = exemptions
242        .iter()
243        .find(|(listed, _)| *listed == name)
244        .map(|(_, tables)| *tables);
245
246    if let Some(tables) = exempt {
247        if undeclared != tables {
248            return Verdict::Failed(format!(
249                "[{name}] is exempt from the personal-data rule for {tables:?} (issue #265), but \
250                 its undeclared tables are now {undeclared:?}. Correct the entry in \
251                 UNDECLARED_TABLES in cratefield-testing, or remove it: an exemption that no \
252                 longer describes the module is how the next omission hides."
253            ));
254        }
255        return Verdict::Exempt(format!(
256            "[{name}] personal-data declarations missing for {tables:?}; exempt under issue #265"
257        ));
258    }
259
260    if undeclared.is_empty() {
261        return Verdict::Declared;
262    }
263    Verdict::Failed(format!(
264        "[{name}] owns {undeclared:?} and declares nothing personal about them. \
265         `cratefield-module-privacy` plans an export and an erasure from \
266         `Module::personal_data()`, so a table missing from it is never exported and never \
267         erased. Declare each one with a `PersonalDataSet`, or with `PersonalDataSet::none(table, \
268         reason)` if it holds nobody — \"no declaration\" and \"nothing here\" must not look the \
269         same."
270    ))
271}
272
273/// Fails a module that owns a table it declares nothing about (issue #244).
274///
275/// Export walks [`Module::tables`] and erasure plans from
276/// [`Module::personal_data`], so a table added to the first and forgotten in
277/// the second is invisible from both ends: the venture boots, the export runs,
278/// the erasure reports success, and the rows are never in either. Nothing
279/// catches it but this.
280fn check_personal_data(module: &dyn Module) {
281    match personal_data_verdict(
282        module.name(),
283        &cratefield_core::undeclared_tables(module),
284        UNDECLARED_TABLES,
285    ) {
286        Verdict::Declared => {}
287        Verdict::Exempt(note) => eprintln!("{note}"),
288        Verdict::Failed(message) => panic!("{message}"),
289    }
290}
291
292/// The migrations-versus-`tables()` rule, as a value rather than a panic
293/// (issue #272). `Err` is the panic message.
294///
295/// **No exemption list.** The rule it completes has one, emptied in #271, and
296/// an entry in it is a debt with a number on it. This one starts empty and
297/// stays that way: a module that cannot pass it has a table outside export and
298/// outside erasure right now, and the entry would be the record of deciding
299/// not to mind. #265 is what a list that grows looks like.
300///
301/// `found` is every table the module's migrations leave behind and `listed` is
302/// what `tables()` says, and **both directions are checked**, deliberately:
303///
304/// - a table in `found` and not in `listed` is the hole this exists for;
305/// - a table in `listed` that the scan did not find is the failure mode that
306///   makes the first check pass for the wrong reason. "No unlisted table" is
307///   an absence assertion, and a scan that has quietly stopped matching —
308///   a dialect that stops embedding its SQL, a `CREATE TABLE` written a way
309///   the walk does not read — satisfies it perfectly while seeing nothing.
310///   A module with migrations and a table list must be able to show the scan
311///   found what it listed.
312fn unlisted_verdict(
313    name: &str,
314    migration_count: usize,
315    listed: &[&'static str],
316    found: &[String],
317) -> Result<(), String> {
318    if migration_count > 0 {
319        let missed: Vec<&str> = listed
320            .iter()
321            .copied()
322            .filter(|table| !found.iter().any(|seen| seen.eq_ignore_ascii_case(table)))
323            .collect();
324        if !missed.is_empty() {
325            return Err(format!(
326                "[{name}] lists {missed:?} in `Module::tables()`, but the `CREATE TABLE` scan \
327                 over its {migration_count} migrations did not find them — it found {found:?}. \
328                 Either the module does not create those tables, or the scan has stopped \
329                 matching; the second is why this is checked at all, because \"no unlisted \
330                 table\" is an absence assertion and a scan that sees nothing satisfies it \
331                 forever (issue #272)."
332            ));
333        }
334    }
335
336    let unlisted: Vec<&String> = found
337        .iter()
338        .filter(|table| !listed.iter().any(|name| name.eq_ignore_ascii_case(table)))
339        .collect();
340    if unlisted.is_empty() {
341        return Ok(());
342    }
343    Err(format!(
344        "[{name}] creates {unlisted:?} in its migrations and does not list them in \
345         `Module::tables()`. A table in neither list is outside three things at once: \
346         `fz data export` walks `tables()`, subject access and erasure walk \
347         `personal_data()`, and the rule that compares them can only read the two lists it \
348         is handed. `auth-core` held `deletion_jobs` — and a person's identifier at their \
349         identity provider with it — in exactly that position (issue #272). Add each table \
350         to `tables()` and give it a `PersonalDataSet`; note that `tables()` is also what a \
351         whole-database `fz data export`/`import` carries, so adding one changes what a \
352         move of this venture takes with it."
353    ))
354}
355
356/// Fails a module that creates a table its `tables()` never mentions
357/// (issue #272).
358///
359/// The converse of [`check_personal_data`], one step further back: that rule
360/// reads `tables()`, so it cannot see a table that never reached the list.
361/// The migrations can, because a `CREATE TABLE` is where a table comes into
362/// being and is the one statement its author cannot forget to write.
363///
364/// It reaches a module through the module's own `tests/conformance.rs`, which
365/// is the cost of being a kit check rather than a build error: a module
366/// without that file is not checked by anything. The control plane's two
367/// modules are in exactly that position and own six unlisted tables between
368/// them (issue #280).
369fn check_module_tables(module: &dyn Module) {
370    if let Err(message) = unlisted_verdict(
371        module.name(),
372        module.migrations().sqlite.len() + module.migrations().postgres.len(),
373        module.tables(),
374        &cratefield_core::migration_tables(module),
375    ) {
376        panic!("{message}");
377    }
378}
379
380fn conformance_inner(inner: &Arc<dyn Module>, parity: bool) {
381    check_module_tables(inner.as_ref());
382    check_personal_data(inner.as_ref());
383    let name = inner.name().to_owned();
384    let version = inner.version().to_owned();
385    let has_well_known = inner.well_known().is_some();
386    let module: Arc<dyn Module> = Arc::new(WellKnownProbe {
387        inner: inner.clone(),
388    });
389
390    for dialect in crate::dialect::Dialect::available() {
391        conformance_on_dialect(&dialect, module.clone(), &name, &version, has_well_known);
392    }
393
394    if parity {
395        // One instance across both mounts, as the dialect axis above
396        // already does: the probes never reach a module's parked context.
397        parity_on(inner, &name);
398    }
399}
400
401fn conformance_on_dialect(
402    dialect: &crate::dialect::Dialect,
403    module: Arc<dyn Module>,
404    name: &str,
405    version: &str,
406    has_well_known: bool,
407) {
408    let kit = TestHarness::from_arcs(vec![module], dialect.clone(), |_| {});
409    let module = kit
410        .modules
411        .iter()
412        .find(|m| m.name() == name)
413        .unwrap_or_else(|| panic!("module {name} missing from kit"))
414        .clone();
415
416    // 1. health lists it.
417    let health = pollster::block_on(request(
418        &kit.router,
419        axum::http::Method::GET,
420        "/__health",
421        None,
422    ));
423    let body = health.json();
424    let listed = body["modules"]
425        .as_array()
426        .unwrap_or_else(|| panic!("health modules array missing: {body}"));
427    let entry = listed
428        .iter()
429        .find(|entry| entry["name"] == *name)
430        .unwrap_or_else(|| panic!("health does not list {name}: {body}"));
431    assert_eq!(
432        entry["version"],
433        version,
434        "[{}] health lists the module version",
435        dialect.name()
436    );
437
438    // 2. a request under the prefix is answered without panicking.
439    let probe = pollster::block_on(request(
440        &kit.router,
441        axum::http::Method::GET,
442        &format!("/v1/{name}/"),
443        None,
444    ));
445    // Any status is the module's business; the point is no crash.
446    let _ = probe.status;
447
448    // 3. migrations apply twice on fresh databases.
449    #[cfg(feature = "postgres")]
450    if let crate::dialect::Dialect::Postgres { .. } = &dialect {
451        crate::pg::migrations_apply_twice(&kit.modules)
452            .unwrap_or_else(|message| panic!("[postgres] {message}"));
453        check_visibility_and_scope(&kit, module.as_ref(), name, has_well_known);
454        return;
455    }
456    for round in 1..=2 {
457        let fresh = cratefield_adapter_sqlite::SqliteDatabase::in_memory()
458            .unwrap_or_else(|err| panic!("[sqlite] fresh db {round}: {err}"));
459        for module in &kit.modules {
460            fresh
461                .apply_migrations(module.name(), module.migrations().sqlite)
462                .unwrap_or_else(|err| panic!("[sqlite] round {round}, {}: {err}", module.name()));
463        }
464    }
465    check_visibility_and_scope(&kit, module.as_ref(), name, has_well_known);
466}
467
468/// Conformance checks 4-6: undeclared ports stay hidden, concurrent
469/// requests keep their request ids, and a well-known router mounts at
470/// the root only.
471fn check_visibility_and_scope(
472    kit: &TestHarness,
473    module: &dyn Module,
474    name: &str,
475    has_well_known: bool,
476) {
477    // 4. undeclared ports are hidden (declared ones stay visible).
478    // Walks `Port::ALL` rather than a list of its own: a hand-written one
479    // had already lost `Port::Auth` (issue #450).
480    let view = full_fake_ports().view_for(module);
481    for port in Port::ALL {
482        let declared = module.requires().contains(port) || module.optional().contains(port);
483        assert_eq!(
484            view.has(*port),
485            declared,
486            "{name}: port {} must be visible only when declared",
487            port.name()
488        );
489    }
490
491    // 5. two concurrent requests keep their own request ids (ADR 0007).
492    let router_a = kit.router.clone();
493    let router_b = kit.router.clone();
494    let id_a = "conformance-AAAAAAAA";
495    let id_b = "conformance-BBBBBBBB";
496    let make = |router: axum::Router, id: &'static str| {
497        std::thread::spawn(move || {
498            use tower::ServiceExt;
499            let request = axum::http::Request::builder()
500                .uri("/__health")
501                .header("x-request-id", id)
502                .body(axum::body::Body::empty())
503                .expect("request builds");
504            let response = pollster::block_on(router.oneshot(request)).expect("router answers");
505            response
506                .headers()
507                .get("x-request-id")
508                .and_then(|value| value.to_str().ok())
509                .expect("request id echoed")
510                .to_string()
511        })
512    };
513    let handle_a = make(router_a, id_a);
514    let handle_b = make(router_b, id_b);
515    assert_eq!(handle_a.join().expect("a completes"), id_a);
516    assert_eq!(handle_b.join().expect("b completes"), id_b);
517
518    check_well_known_mount(kit, name, has_well_known);
519}
520
521/// Conformance check 6 (issue #46): the module's well-known router, when
522/// present, serves at the root under `/.well-known` and never under
523/// `/v1`; when absent, nothing mounts at `/.well-known`.
524fn check_well_known_mount(kit: &TestHarness, name: &str, has_well_known: bool) {
525    let probe = pollster::block_on(request(
526        &kit.router,
527        axum::http::Method::GET,
528        &format!("/.well-known{WELL_KNOWN_PROBE_PATH}"),
529        None,
530    ));
531    if has_well_known {
532        assert_eq!(
533            probe.status,
534            axum::http::StatusCode::OK,
535            "{name}: well-known router must serve at the root"
536        );
537        let under_v1 = pollster::block_on(request(
538            &kit.router,
539            axum::http::Method::GET,
540            &format!("/v1/{name}/.well-known{WELL_KNOWN_PROBE_PATH}"),
541            None,
542        ));
543        assert_eq!(
544            under_v1.status,
545            axum::http::StatusCode::NOT_FOUND,
546            "{name}: well-known routes must not be nested under /v1"
547        );
548    } else {
549        assert_eq!(
550            probe.status,
551            axum::http::StatusCode::NOT_FOUND,
552            "{name}: nothing must mount at /.well-known without a well-known router"
553        );
554    }
555}
556
557/// One probe of the [`sidecar_parity`] battery: a request whose answer
558/// must be identical whether the module is linked in or reached over a
559/// service binding.
560struct Probe {
561    what: &'static str,
562    method: axum::http::Method,
563    /// Appended to `/v1/<module>`.
564    path: &'static str,
565    body: Option<&'static str>,
566}
567
568/// The request id both mounts are given, so `instance` in a problem body
569/// and the `x-request-id` header can be compared byte for byte. The
570/// harness accepts a client-supplied id that matches its pattern.
571const PARITY_REQUEST_ID: &str = "parity-0123456789abcdef";
572
573/// Sends one probe through `router`, with the fixed request id.
574async fn probe_once(router: &axum::Router, name: &str, probe: &Probe) -> crate::TestResponse {
575    use axum::http::{HeaderValue, Request, header};
576    use tower::ServiceExt;
577
578    let uri = format!("/v1/{name}{}", probe.path);
579    let mut builder = Request::builder()
580        .method(probe.method.clone())
581        .uri(uri)
582        .header(
583            cratefield_core::X_REQUEST_ID,
584            HeaderValue::from_static(PARITY_REQUEST_ID),
585        )
586        .header("cf-connecting-ip", HeaderValue::from_static("203.0.113.9"));
587    let body = match probe.body {
588        Some(json) => {
589            builder = builder.header(header::CONTENT_TYPE, "application/json");
590            axum::body::Body::from(json)
591        }
592        None => axum::body::Body::empty(),
593    };
594    let response = router
595        .clone()
596        .oneshot(builder.body(body).expect("probe request builds"))
597        .await
598        .expect("router is infallible");
599    crate::TestResponse::of(response).await
600}
601
602/// Asserts that a module answers identically in-process and behind a
603/// sidecar mount (issue #64, ADR 0009: a caller cannot tell which).
604///
605/// Both mounts are given the same client-supplied request id, so the
606/// `instance` of a problem body and the `x-request-id` header are
607/// comparable byte for byte. Probes are deliberately module-agnostic —
608/// unknown paths, a malformed body, a wrong method — because the kit
609/// does not know the module's routes and because those are exactly the
610/// paths where the hop could quietly rewrite something.
611///
612/// Also asserted: a body over the harness's 64 KiB cap is refused by the
613/// **host** and never forwarded.
614///
615/// # Panics
616///
617/// Panics naming the probe and the field that diverged.
618pub fn sidecar_parity(module: Box<dyn Module>) {
619    let name = module.name().to_owned();
620    parity_on(&Arc::from(module), &name);
621}
622
623fn parity_on(shared: &Arc<dyn Module>, name: &str) {
624    // In-process: the module is linked into the harness under test.
625    let in_process = TestHarness::from_arcs(
626        vec![shared.clone()],
627        crate::dialect::Dialect::Sqlite,
628        |_| {},
629    );
630
631    // Sidecar: a second harness holds the module, and the host holds a
632    // mount table pointing at it over a fake service binding.
633    let remote = TestHarness::from_arcs(
634        vec![shared.clone()],
635        crate::dialect::Dialect::Sqlite,
636        |_| {},
637    );
638    let (sidecar, dispatcher) = crate::sidecar::shared(crate::sidecar::FakeSidecar::new(
639        "PARITY",
640        remote.router.clone(),
641    ));
642    let table = format!("{{\"{name}\":\"PARITY\"}}");
643    let host = TestHarness::with_builder(
644        Vec::new(),
645        |builder| builder,
646        |ports| {
647            ports.config = Arc::new(cratefield_core::MapConfig::from_pairs([
648                ("HARNESS_SECRET", crate::TEST_HARNESS_SECRET),
649                (cratefield_core::HARNESS_SIDECARS, table.as_str()),
650            ]));
651            ports.dispatcher = Some(dispatcher);
652        },
653    );
654
655    let probes = [
656        Probe {
657            what: "an unknown path under the module prefix",
658            method: axum::http::Method::GET,
659            path: "/__parity_no_such_route",
660            body: None,
661        },
662        Probe {
663            what: "a POST to an unknown path",
664            method: axum::http::Method::POST,
665            path: "/__parity_no_such_route",
666            body: Some(r#"{"parity":true}"#),
667        },
668        Probe {
669            what: "the module root",
670            method: axum::http::Method::GET,
671            path: "",
672            body: None,
673        },
674        Probe {
675            what: "a malformed JSON body at the module root",
676            method: axum::http::Method::POST,
677            path: "",
678            body: Some("{not json"),
679        },
680    ];
681
682    for (sent, probe) in probes.iter().enumerate() {
683        let direct = pollster::block_on(probe_once(&in_process.router, name, probe));
684        let hopped = pollster::block_on(probe_once(&host.router, name, probe));
685        // Without this the axis could pass vacuously: if the mount stopped
686        // forwarding, the host would answer its own 404 and a module that
687        // also answers 404 would compare equal. Every probe must have
688        // crossed the hop.
689        assert_eq!(
690            sidecar.calls(),
691            sent + 1,
692            "[{name}] {} never reached the sidecar: the mount is not forwarding, \
693             so this comparison proves nothing",
694            probe.what
695        );
696        compare(name, probe.what, &direct, &hopped);
697    }
698
699    check_oversized_body_stops_at_the_host(&host, &sidecar, name);
700}
701
702/// A body over the harness cap is refused by the **host** and never
703/// forwarded: the forwarder buffers, so a body it accepted would be held
704/// in the isolate twice (issue #64, amended).
705fn check_oversized_body_stops_at_the_host(
706    host: &TestHarness,
707    sidecar: &Arc<crate::sidecar::FakeSidecar>,
708    name: &str,
709) {
710    use axum::http::{Request, StatusCode, header};
711    use tower::ServiceExt;
712
713    let before = sidecar.calls();
714    let big = "x".repeat(cratefield_core::MAX_BODY_BYTES + 1);
715    let response = pollster::block_on(async {
716        let request = Request::builder()
717            .method(axum::http::Method::POST)
718            .uri(format!("/v1/{name}"))
719            .header(header::CONTENT_TYPE, "application/json")
720            .body(axum::body::Body::from(big))
721            .expect("oversized request builds");
722        let response = host
723            .router
724            .clone()
725            .oneshot(request)
726            .await
727            .expect("router is infallible");
728        crate::TestResponse::of(response).await
729    });
730    assert_eq!(
731        response.status,
732        StatusCode::PAYLOAD_TOO_LARGE,
733        "[{name}] a body over {} bytes must be refused by the host",
734        cratefield_core::MAX_BODY_BYTES
735    );
736    assert_eq!(
737        sidecar.calls(),
738        before,
739        "[{name}] an oversized body must never be forwarded to the sidecar"
740    );
741}
742
743/// Compares one probe's two answers: status, the problem body byte for
744/// byte, and the request id (present exactly once, and the one the
745/// caller sent).
746fn compare(name: &str, what: &str, direct: &crate::TestResponse, hopped: &crate::TestResponse) {
747    assert_eq!(
748        direct.status, hopped.status,
749        "[{name}] status differs over the sidecar hop for {what}"
750    );
751    assert_eq!(
752        direct.body(),
753        hopped.body(),
754        "[{name}] body differs over the sidecar hop for {what}"
755    );
756    for header in [
757        axum::http::header::CONTENT_TYPE.as_str(),
758        axum::http::header::LOCATION.as_str(),
759    ] {
760        assert_eq!(
761            direct.headers.get(header),
762            hopped.headers.get(header),
763            "[{name}] `{header}` differs over the sidecar hop for {what}"
764        );
765    }
766    for (label, response) in [("in-process", direct), ("sidecar", hopped)] {
767        let ids: Vec<_> = response
768            .headers
769            .get_all(cratefield_core::X_REQUEST_ID)
770            .iter()
771            .collect();
772        assert_eq!(
773            ids.len(),
774            1,
775            "[{name}] {label} answered {} request ids for {what}; exactly one is the contract",
776            ids.len()
777        );
778        assert_eq!(
779            ids[0], PARITY_REQUEST_ID,
780            "[{name}] {label} did not echo the caller's request id for {what}"
781        );
782    }
783}
784
785#[cfg(test)]
786mod tests {
787    use super::{UNDECLARED_TABLES, Verdict, personal_data_verdict, unlisted_verdict};
788
789    /// A fixture list, so these cover the mechanism rather than whatever
790    /// happens to be exempt on the day.
791    const FIXTURE: &[(&str, &[&str])] = &[("ledger", &["ledger_entries", "ledger_lines"])];
792
793    fn message(verdict: Verdict) -> String {
794        match verdict {
795            Verdict::Failed(message) | Verdict::Exempt(message) => message,
796            Verdict::Declared => String::new(),
797        }
798    }
799
800    #[test]
801    fn no_module_is_exempt_from_the_personal_data_rule() {
802        // Issue #265: the five modules that could not pass the rule when it
803        // landed are declared, and the list they sat in is empty. The
804        // mechanism stays for the next module that needs it; an entry in it
805        // is a debt, and this is the test that notices one being taken on.
806        assert!(
807            UNDECLARED_TABLES.is_empty(),
808            "a module is exempt from the personal-data rule again: {UNDECLARED_TABLES:?}. \
809             An exemption means a venture composing that module answers an erasure request \
810             without the rows it lists — declare them instead, and open the issue the entry \
811             would have tracked."
812        );
813    }
814
815    #[test]
816    fn a_declared_module_passes() {
817        assert!(matches!(
818            personal_data_verdict("notes", &[], FIXTURE),
819            Verdict::Declared
820        ));
821    }
822
823    #[test]
824    fn an_exempt_module_that_declared_everything_is_told_to_remove_its_entry() {
825        // The other end of the anti-rot rule, and the one this change ran
826        // into: a module that has done the work still fails while its
827        // exemption stands, because an entry left behind is how the next
828        // omission hides behind the last one.
829        let message = message(personal_data_verdict("ledger", &[], FIXTURE));
830        assert!(message.contains("or remove it"), "{message}");
831        assert!(message.contains("#265"), "{message}");
832    }
833
834    #[test]
835    fn an_undeclared_table_fails_and_says_what_to_write() {
836        let message = message(personal_data_verdict("notes", &["note_tags"], FIXTURE));
837        assert!(message.contains("note_tags"), "{message}");
838        assert!(message.contains("PersonalDataSet::none"), "{message}");
839    }
840
841    #[test]
842    fn an_exemption_that_still_describes_its_module_is_printed_not_failed() {
843        let verdict = personal_data_verdict("ledger", &["ledger_entries", "ledger_lines"], FIXTURE);
844        assert!(matches!(verdict, Verdict::Exempt(_)));
845        assert!(message(verdict).contains("exempt under issue #265"));
846    }
847
848    #[test]
849    fn an_exemption_that_no_longer_describes_its_module_fails() {
850        // The anti-rot half. A module that declared one of its listed tables
851        // is a different module from the one that was exempted, and letting
852        // the entry keep covering it is how the next omission hides behind
853        // the last one.
854        let message = message(personal_data_verdict("ledger", &["ledger_lines"], FIXTURE));
855        assert!(message.contains("#265"), "{message}");
856        assert!(message.contains("ledger_entries"), "{message}");
857    }
858
859    #[test]
860    fn an_exempt_module_that_grows_a_new_undeclared_table_fails() {
861        let message = message(personal_data_verdict(
862            "ledger",
863            &["ledger_entries", "ledger_lines", "ledger_fx"],
864            FIXTURE,
865        ));
866        assert!(message.contains("ledger_fx"), "{message}");
867    }
868
869    fn problem(verdict: Result<(), String>) -> String {
870        verdict.err().unwrap_or_default()
871    }
872
873    #[test]
874    fn a_module_that_lists_every_table_it_creates_passes() {
875        assert!(
876            unlisted_verdict(
877                "auth-core",
878                6,
879                &["users", "sessions"],
880                &["users".to_owned(), "sessions".to_owned()],
881            )
882            .is_ok()
883        );
884    }
885
886    #[test]
887    fn a_table_the_migrations_create_and_tables_omits_fails() {
888        // The live shape: `auth-core` creates `deletion_jobs` in migration
889        // 0005 and lists seven tables that do not include it (issue #272).
890        let message = problem(unlisted_verdict(
891            "auth-core",
892            6,
893            &["users"],
894            &["users".to_owned(), "deletion_jobs".to_owned()],
895        ));
896        assert!(message.contains("deletion_jobs"), "{message}");
897        assert!(message.contains("#272"), "{message}");
898        // It has to say what to write, and that the list is also the export's.
899        assert!(message.contains("PersonalDataSet"), "{message}");
900        assert!(message.contains("fz data export"), "{message}");
901    }
902
903    #[test]
904    fn a_scan_that_found_nothing_fails_rather_than_passing_vacuously() {
905        // The failure this epic has hit twice: "no unlisted table" is an
906        // absence assertion, and a scan that has stopped matching satisfies
907        // it forever. A module with migrations and a table list must be able
908        // to show the scan found what it listed.
909        let message = problem(unlisted_verdict("auth-core", 6, &["users"], &[]));
910        assert!(message.contains("stopped matching"), "{message}");
911        assert!(message.contains("users"), "{message}");
912    }
913
914    #[test]
915    fn a_scan_that_found_only_some_of_the_listed_tables_fails() {
916        // Not only the all-or-nothing case: a walk that stops reading after
917        // the first statement of a set would find one table and miss the rest.
918        let message = problem(unlisted_verdict(
919            "auth-core",
920            6,
921            &["users", "sessions"],
922            &["users".to_owned()],
923        ));
924        // The one it missed is named, and what it did find is shown beside
925        // it: a message that only said "something is missing" would send the
926        // reader back to the scan with nothing to go on.
927        assert!(message.contains(r#"lists ["sessions"]"#), "{message}");
928        assert!(message.contains(r#"it found ["users"]"#), "{message}");
929    }
930
931    #[test]
932    fn a_module_with_no_migrations_is_not_asked_to_have_found_anything() {
933        // `auth-passkeys` and its siblings write to `auth-core`'s schema and
934        // ship no migrations of their own; there is nothing for the scan to
935        // read and nothing it could have missed.
936        assert!(unlisted_verdict("auth-passkeys", 0, &[], &[]).is_ok());
937    }
938}