about summary refs log tree commit diff
path: root/tests/search_crate_http.rs
blob: 7248dca34d3284297fe6976b20be38e2a5f84f42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//! Does the ROUTE serve the extracted engine end to end?
//!
//! The seam tests prove the engine answers; this proves the HTTP contract above
//! it — auth, envelope, `lod`, `next` links — is produced unchanged when the
//! engine lives in another crate.
//!
//! Needs `XAPIAN_DB_PATH` pointing at a real index (the 47,040-doc dev index)
//! and `SEARCH_ENGINE=crate`. Hermetic otherwise: no gn3, no network.

use axum::body::Body;
use axum::http::{Request, StatusCode};
use http_body_util::BodyExt;
use tower::util::ServiceExt;

const TEST_JWKS: &str = include_str!("../test/data/test_jwks.json");
use axum::{routing::get, Router};

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_route_serves_the_extracted_engine() {
    unsafe {
        std::env::set_var("SEARCH_ENGINE", "crate");
        std::env::set_var(
            "XAPIAN_DB_PATH",
            std::env::var("XAPIAN_DB_PATH").unwrap_or_else(|_| {
                format!("{}/xapian-index-dev", std::env::var("HOME").unwrap_or_default())
            }),
        );
    }

    // gn-auth's JWKS stub: token verification must not need a live gn-auth.
    let auth_stub = {
        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(|| async { (StatusCode::OK, TEST_JWKS) }),
        );
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        format!("http://127.0.0.1:{port}")
    };
    unsafe { std::env::set_var("AUTH_SERVER_URL", &auth_stub) };
    let token = gn4_test_token(&auth_stub);
    let response = genenetwork4::app()
        .oneshot(
            Request::builder()
                .uri("/search?q=alcohol&type=phenotype&limit=3")
                .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();
    let text = String::from_utf8_lossy(&body).to_string();
    let json: serde_json::Value =
        serde_json::from_str(&text).unwrap_or_else(|e| panic!("json body ({e}); status={status}; body={text:?}"));

    assert_eq!(status, StatusCode::OK, "route status; body={json}");
    let hits = json
        .get("data")
        .and_then(|d| d.as_array())
        .or_else(|| json.as_array())
        .expect("hits array in the envelope");
    assert!(
        !hits.is_empty(),
        "the engine returned no hits for a query the index answers; body={json}"
    );
    let first = &hits[0];
    assert!(first.get("dataset").is_some(), "a hit carries its dataset");
    assert!(first.get("name").is_some(), "a hit carries its name");
    println!(
        "route served {} hit(s), first {}/{}",
        hits.len(),
        first.get("dataset").and_then(|v| v.as_str()).unwrap_or("?"),
        first.get("name").and_then(|v| v.as_str()).unwrap_or("?")
    );
}

/// A token the dev issuer accepts (same shape gn4's own search tests mint).
fn gn4_test_token(issuer: &str) -> String {
    use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
    use serde::Serialize;
    const TEST_PRIVATE_KEY: &str = include_str!("../test/data/test_rsa_private.pem");
    #[derive(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 iss = issuer.to_string();
    let claims = Claims {
        sub: "crate-http-test".into(),
        scope: "profile".into(),
        iss,
        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()
}