about summary refs log tree commit diff
path: root/tests
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabui@proton.me>2026-10-13 23:36:39 +0300
committerAlexander_Kabui <alexanderkabui@proton.me>2026-10-14 07:28:51 +0300
commit22ff53e2d65e47df27d76aa7420a146074c00282 (patch)
tree07f550107ebb9501b1fa79e8e8d6b2d48210572d /tests
parenta188b75157516c5e00dd130d9ca8dfbd6cf36679 (diff)
downloadgenenetwork4-22ff53e2d65e47df27d76aa7420a146074c00282.tar.gz
config: GN4_DB_MODE (mariadb optional on dev) + no-DB hardening
* src/config.rs (DbMode, Config.db_mode, parse_db_mode): add
GN4_DB_MODE=dev|production in the layered config; dev runs with no
configured DB; fail-closed parse (a typo refuses).
* src/db.rs (DbError, pool, probe), src/error.rs (ApiError::from_db):
mint a typed 503 db_unavailable at the db::pool() choke point,
distinguishing Unavailable from Query.
* src/main.rs: loud no-DB startup line; production refuses to start
(exit non-zero) before axum::serve.
* src/routes/{accessions,datasets,groups,mapping_methods,publications,species,traits}.rs:
route every DB error through ApiError::from_db.
* src/bin/gn-indexer.rs: refuse to build an index when the DB is unreachable.
* tests/no_db.rs: pin no-DB degradation (search 200 partial, DB routes 503).

His ask (DM 2026-10-12): "Make it an option to switch it off for
development machines? I mean mariadb." The no-DB hardening is ours
(review-driven). Default GN4_DB_MODE left unflipped (=dev); the flip needs
owner sign-off.
Diffstat (limited to 'tests')
-rw-r--r--tests/no_db.rs148
1 files changed, 148 insertions, 0 deletions
diff --git a/tests/no_db.rs b/tests/no_db.rs
new file mode 100644
index 0000000..4680c61
--- /dev/null
+++ b/tests/no_db.rs
@@ -0,0 +1,148 @@
+//! NO-DB graceful-degradation gate (lane gn4-devdb, gate 4).
+//!
+//! Pinned no-DB arrangement: `SQL_URI` points at a CLOSED port
+//! (`127.0.0.1:1`), never the hardcoded default (`127.0.0.1/db_webqtl`)
+//! and never an unset SQL_URI that could reach a live DB. The pool build
+//! therefore fails and `db::pool()` mints `DbError::Unavailable`, which
+//! is what the routes must translate: DB-backed routes -> typed
+//! `503 db_unavailable`; /search still returns hits, with the
+//! PublishXRef enrichment omitted (never a 500).
+//!
+//! gn3 and gn-auth are stubbed exactly as in tests/search.rs, so no
+//! network is needed. This file is its own test binary (its own
+//! process), so the shared connection pool is fresh and SQL_URI is set
+//! before the first DB touch; the env keys it writes belong to this
+//! single-threaded sequence only.
+
+use axum::Router;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use axum::routing::get;
+use http_body_util::BodyExt;
+use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
+use serde_json::{Value, json};
+use tower::ServiceExt;
+
+const TEST_JWKS: &str = include_str!("../test/data/test_jwks.json");
+const TEST_PRIVATE_KEY: &str = include_str!("../test/data/test_rsa_private.pem");
+
+/// The pinned no-DB SQL_URI: a port nothing listens on.
+const CLOSED_PORT_SQL_URI: &str = "mysql://webqtlout:webqtlout@127.0.0.1:1/db_webqtl";
+
+async fn serve_gn3() -> (StatusCode, String) {
+    // One phenotype hit whose dataset ends in "Publish": the enrichment
+    // path will try the database for locus/abbreviation.
+    (
+        StatusCode::OK,
+        json!([{"name": "10199", "dataset": "BXDPublish", "lrs": 5.0}]).to_string(),
+    )
+}
+
+async fn gn3_stub_url() -> String {
+    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+    let port = listener.local_addr().unwrap().port();
+    let app = Router::new().route("/api/search/", get(serve_gn3));
+    tokio::spawn(async move {
+        axum::serve(listener, app).await.unwrap();
+    });
+    format!("http://127.0.0.1:{port}/api/")
+}
+
+async fn serve_jwks() -> (StatusCode, &'static str) {
+    (StatusCode::OK, TEST_JWKS)
+}
+
+async fn gn_auth_stub_url() -> String {
+    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+    let port = listener.local_addr().unwrap().port();
+    let app = Router::new().route("/auth/public-jwks", get(serve_jwks));
+    tokio::spawn(async move {
+        axum::serve(listener, app).await.unwrap();
+    });
+    format!("http://127.0.0.1:{port}")
+}
+
+fn sign_test_token(issuer: &str) -> String {
+    #[derive(serde::Serialize)]
+    struct Claims {
+        sub: String,
+        scope: String,
+        iss: String,
+        iat: u64,
+        exp: u64,
+    }
+    let now = std::time::SystemTime::now()
+        .duration_since(std::time::UNIX_EPOCH)
+        .unwrap()
+        .as_secs();
+    let claims = Claims {
+        sub: "no-db-test-user".to_string(),
+        scope: "profile".to_string(),
+        iss: issuer.to_string(),
+        iat: now,
+        exp: now + 3600,
+    };
+    let key = EncodingKey::from_rsa_pem(TEST_PRIVATE_KEY.as_bytes()).unwrap();
+    encode(&Header::new(Algorithm::RS256), &claims, &key).unwrap()
+}
+
+fn set(key: &str, value: &str) {
+    // SAFETY: single-threaded env sequence in this dedicated test binary.
+    unsafe { std::env::set_var(key, value) };
+}
+
+async fn get_json(uri: &str, token: &str) -> (StatusCode, Value) {
+    let response = genenetwork4::app()
+        .oneshot(
+            Request::builder()
+                .uri(uri)
+                .header("Authorization", format!("Bearer {token}"))
+                .body(Body::empty())
+                .unwrap(),
+        )
+        .await
+        .unwrap();
+    let status = response.status();
+    let body = response.into_body().collect().await.unwrap().to_bytes();
+    (status, serde_json::from_slice(&body).unwrap())
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn no_db_mode_degrades_gracefully() {
+    // Pin the no-DB arrangement BEFORE anything can build a pool.
+    set("SQL_URI", CLOSED_PORT_SQL_URI);
+    set("GN3_URL", &gn3_stub_url().await);
+    let gn_auth_stub = gn_auth_stub_url().await;
+    set("AUTH_SERVER_URL", &gn_auth_stub);
+    let token = sign_test_token(&gn_auth_stub);
+
+    // A DB-backed route answers the typed 503, not a 500: db::pool()'s
+    // Unavailable is minted for exactly this.
+    let (status, body) = get_json("/species", &token).await;
+    assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
+    assert_eq!(body["code"], "db_unavailable");
+    assert_eq!(body["status"], 503);
+
+    // Unknown names cannot be distinguished from known ones without a
+    // database, so a name lookup is also 503 here (the 404-vs-503
+    // distinction is preserved only when the DB is reachable; see gate 3
+    // and REPORT.md).
+    let (status, body) = get_json("/species/NoSuchSpecies", &token).await;
+    assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
+    assert_eq!(body["code"], "db_unavailable");
+
+    // /search still works: hits are returned, enrichment fields are
+    // null, and the response is marked partial -- never a 500.
+    let (status, body) = get_json("/search?q=alcohol&type=phenotype&limit=5", &token).await;
+    assert_eq!(status, StatusCode::OK);
+    assert_eq!(body["meta"]["state"], "partial");
+    let hits = body["data"].as_array().unwrap();
+    assert_eq!(hits.len(), 1);
+    assert!(hits[0]["locus"].is_null());
+    assert!(hits[0]["abbreviation"].is_null());
+    let notes = body["notes"].as_array().unwrap();
+    assert!(
+        notes.iter().any(|n| n.as_str().unwrap_or("").contains("database unavailable")),
+        "expected a partial note about the database, got {notes:?}"
+    );
+}