1
pub mod controls;
2
pub mod edit_page;
3
pub mod entity_edit;
4
pub mod list_page;
5
pub mod new_page;
6
pub mod report_seed;
7
pub mod seed;
8
pub mod tenant;
9

            
10
use chrono::Utc;
11
use redis::Client;
12
use std::sync::{Arc, Once};
13
use uuid::Uuid;
14
use web::{AppState, Config, jwt_auth::JWTAuthMiddleware, model::User};
15

            
16
static TEST_ENV_INIT: Once = Once::new();
17

            
18
871
fn ensure_test_env() {
19
871
    TEST_ENV_INIT.call_once(|| {
20
        // `..` because cargo runs a test binary with the CRATE as its working
21
        // directory, while `.env` sits at the workspace root — so the plain
22
        // relative read never matched and every DB test quietly required
23
        // DATABASE_URL to be exported by hand.
24
330
        if std::env::var("DATABASE_URL").is_err()
25
            && let Ok(contents) =
26
                std::fs::read_to_string(".env").or_else(|_| std::fs::read_to_string("../.env"))
27
            && let Some(db_url) = contents
28
                .lines()
29
                .map(str::trim)
30
                .find_map(|line| line.strip_prefix("DATABASE_URL=").map(str::to_string))
31
            && !db_url.trim().is_empty()
32
        {
33
            unsafe {
34
                std::env::set_var("DATABASE_URL", db_url);
35
            }
36
330
        }
37

            
38
330
        if std::env::var("DATABASE_URL").is_err() {
39
            // server::db resolves its URL once, on first use; without one every later test fails.
40
            unsafe {
41
                std::env::set_var(
42
                    "DATABASE_URL",
43
                    "postgres://postgres:postgres@127.0.0.1:5432/postgres",
44
                );
45
            }
46
330
        }
47
330
    });
48
871
}
49

            
50
/// Create a test app state with mock configuration
51
/// A limiter for router tests: trusts no proxy, so requests key on their peer
52
/// (or the unidentified bucket when the harness supplies no connect info).
53
#[must_use]
54
15
pub fn test_limiter() -> Arc<web::rate_limit::AuthLimiter> {
55
15
    Arc::new(web::rate_limit::AuthLimiter::new(
56
15
        web::client_ip::TrustedProxies::from_spec("none"),
57
15
    ))
58
15
}
59

            
60
/// The session store: CI points `REDIS_URL` at its own.
61
1144
pub fn redis_url() -> String {
62
1144
    std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string())
63
1144
}
64

            
65
541
pub async fn create_test_app_state() -> Arc<AppState> {
66
541
    ensure_test_env();
67

            
68
541
    let config = Config {
69
541
        site_url: "http://localhost:3000".to_string(),
70
541
        redis_url: redis_url(),
71
541
        access_token_max_age: 15,
72
541
        refresh_token_max_age: 60,
73
541
        ssh: web::config::SshConnectInfo {
74
541
            hostname: "ssh.example.invalid".to_string(),
75
541
            port: 2222,
76
541
            host_fingerprint: "(test)".to_string(),
77
541
        },
78
541
    };
79

            
80
    let redis_client =
81
541
        Client::open(redis_url()).unwrap_or_else(|e| panic!("Invalid session-store URL: {e}"));
82

            
83
541
    AppState::new(config, redis_client)
84
541
}
85

            
86
/// Create a mock user for testing
87
244
pub fn create_mock_user() -> User {
88
244
    User {
89
244
        id: Uuid::new_v4(),
90
244
        name: "Test User".to_string(),
91
244
        email: "test@example.com".to_string(),
92
244
        role: "user".to_string(),
93
244
        photo: "photo.jpg".to_string(),
94
244
        verified: true,
95
244
        created_at: Some(Utc::now()),
96
244
        updated_at: Some(Utc::now()),
97
244
    }
98
244
}
99

            
100
/// A fixed RS256 pair. Generating one per test would put an RSA keygen on the
101
/// shared runtime for no benefit.
102
pub const TEST_PRIVATE_KEY_B64: &str = "LS0tLS1CRUdJTiBQUklWQVRFIEtFWS0tLS0tCk1JSUV2QUlCQURBTkJna3Foa2lHOXcwQkFRRUZBQVNDQktZd2dnU2lBZ0VBQW9JQkFRREptUmdUU1pEY3QySGsKQys5L2xNa1poQWNQL09zQWpQU1B5LytoYzZYNHhkMzFUT0RrS1lzeGhqQXE1RkFmQzJjZTk4VmY3ZmhWYlgyMwpwYU91WVp2ZTY1UUEyRW81VlM1SFFKWUsxUXNSWTVUVzFDQ05MZVJmV3pWSWY4c01YMlNuN09XYStWakZaVW0rCkhPd3pBL0xIUW84QzFzUWZsYUJVWVVIUEJkMTE5a25TU0pIYlNhdTFsZ1ZsUVlvY1FndWVnZ29MVktjcnlZMTgKYitNSXlTRWJCT1lUUDk1YlNKbj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VlcxOXQ2V2pybUdiCjN1dVVBTmhLT1ZVdVIwQ1dDdFVMRVdPVTF0UWdqUzNrWDFzMVNIL0xERjlrcCt6bG12bFl4V1ZKdmh6c013UHkKeDBLUEF0YkVINVdnVkdGQnp3WGRkZlpKMGtpUjIwbXJ0WllGWlVHS0hFSUxub0lLQzFTbks4bU5mRy9qQ01raApHd1RtRXovZVcwaVovVHZzbXFiem80V2dycHlVOTR4SFBWMUJ2bTR3UUk2QVZPb2xySUt1WmpjbkdqcGNNTzU4CkNoWVlSM0R4V2hIL0piOEYyZFZTeGk5M2dnQ3hoSkl4NXNWZ0Z4bEViQzlaUi9ldisyNkFmQUVLUWl6b3E5S0MKdlFJREFRQUIKLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg==";
104

            
105
/// One runtime for the whole test binary; see `supp_macro::shared_runtime_test`.
106
330
pub fn runtime() -> &'static tokio::runtime::Runtime {
107
    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
108
330
    RUNTIME.get_or_init(|| {
109
        // Before any body runs: `server::db` resolves DATABASE_URL once, on
110
        // first use, so the first test to reach it without the .env loaded
111
        // fixes a missing URL for every later one. Only `create_test_app_state` used to do this.
112
330
        ensure_test_env();
113
330
        tokio::runtime::Runtime::new().expect("test runtime")
114
330
    })
115
330
}
116

            
117
/// Create mock JWT auth middleware for testing
118
509
pub fn create_mock_jwt_auth(user: User) -> JWTAuthMiddleware {
119
509
    JWTAuthMiddleware {
120
509
        user,
121
509
        access_token_uuid: Uuid::new_v4(),
122
509
        refreshed: false,
123
509
    }
124
509
}
125

            
126
/// Wraps `router` with a fixed authenticated user and the error renderer,
127
/// the way production serves it.
128
481
pub fn authenticated(
129
481
    router: axum::Router<Arc<AppState>>,
130
481
    state: Arc<AppState>,
131
481
    user: User,
132
481
) -> axum::Router {
133
481
    let jwt_auth = create_mock_jwt_auth(user);
134
481
    router
135
481
        .layer(axum::middleware::from_fn(
136
481
            web::error_render::render_web_error,
137
481
        ))
138
481
        .layer(axum::middleware::from_fn(
139
481
            move |mut req: axum::http::Request<axum::body::Body>, next: axum::middleware::Next| {
140
481
                let jwt_auth = jwt_auth.clone();
141
481
                async move {
142
481
                    req.extensions_mut().insert(jwt_auth);
143
481
                    next.run(req).await
144
481
                }
145
481
            },
146
        ))
147
481
        .with_state(state)
148
481
}
149

            
150
/// Sends `request` and returns the status with the JSON body.
151
33
pub async fn send_json(
152
33
    app: axum::Router,
153
33
    request: axum::http::Request<axum::body::Body>,
154
33
) -> (axum::http::StatusCode, serde_json::Value) {
155
    use tower::ServiceExt;
156
33
    let response = app.oneshot(request).await.expect("response");
157
33
    let status = response.status();
158
33
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
159
33
        .await
160
33
        .expect("body");
161
33
    let body = serde_json::from_slice(&bytes)
162
1
        .unwrap_or_else(|_| serde_json::Value::String(String::from_utf8_lossy(&bytes).into()));
163
33
    (status, body)
164
33
}