1
use axum::response::IntoResponse;
2
use axum::{
3
    Router,
4
    body::Body,
5
    http::{Request, StatusCode},
6
    routing::{get, post},
7
};
8
use serde_json::json;
9
use tests_integration::tenant_guard::TestTenant;
10
use tower::ServiceExt;
11

            
12
use crate::common::{create_mock_jwt_auth, create_mock_user, create_test_app_state};
13

            
14
5
async fn body_of(response: axum::response::Response) -> String {
15
5
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
16
5
        .await
17
5
        .expect("response body");
18
5
    String::from_utf8(bytes.to_vec()).expect("utf-8 body")
19
5
}
20

            
21
#[supp_macro::shared_runtime_test]
22
1
async fn test_login_handler_with_valid_json() {
23
1
    let app_state = create_test_app_state().await;
24
1
    let app = Router::new()
25
1
        .route("/auth/login", post(web::login::login_user_handler))
26
1
        .with_state(app_state);
27

            
28
1
    let login_data = json!({
29
1
        "email": "test@example.com",
30
1
        "password": "password123"
31
    });
32

            
33
1
    let response = app
34
1
        .oneshot(
35
1
            Request::builder()
36
1
                .method("POST")
37
1
                .uri("/auth/login")
38
1
                .header("content-type", "application/json")
39
1
                .body(Body::from(login_data.to_string()))
40
1
                .unwrap(),
41
1
        )
42
1
        .await
43
        .unwrap();
44

            
45
1
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
46
1
    assert_eq!(
47
1
        body_of(response).await,
48
1
        r#"{"message":"Invalid email or password","status":"error"}"#
49
    );
50
}
51

            
52
#[supp_macro::shared_runtime_test]
53
1
async fn test_login_handler_missing_content_type() {
54
1
    let app_state = create_test_app_state().await;
55
1
    let app = Router::new()
56
1
        .route("/auth/login", post(web::login::login_user_handler))
57
1
        .with_state(app_state);
58

            
59
1
    let login_data = json!({
60
1
        "email": "test@example.com",
61
1
        "password": "password123"
62
    });
63

            
64
1
    let response = app
65
1
        .oneshot(
66
1
            Request::builder()
67
1
                .method("POST")
68
1
                .uri("/auth/login")
69
1
                .body(Body::from(login_data.to_string()))
70
1
                .unwrap(),
71
1
        )
72
1
        .await
73
        .unwrap();
74

            
75
1
    assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
76
1
    assert!(body_of(response).await.contains("application/json"));
77
}
78

            
79
#[supp_macro::shared_runtime_test]
80
1
async fn test_register_handler_missing_fields() {
81
1
    let app_state = create_test_app_state().await;
82
1
    let app = Router::new()
83
1
        .route("/auth/register", post(web::register::register_user_handler))
84
1
        .with_state(app_state);
85

            
86
1
    let register_data = json!({
87
1
        "name": "Test User"
88
        // Missing email and password
89
    });
90

            
91
1
    let response = app
92
1
        .oneshot(
93
1
            Request::builder()
94
1
                .method("POST")
95
1
                .uri("/auth/register")
96
1
                .header("content-type", "application/json")
97
1
                .body(Body::from(register_data.to_string()))
98
1
                .unwrap(),
99
1
        )
100
1
        .await
101
        .unwrap();
102

            
103
1
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
104
1
    assert!(body_of(response).await.contains("missing field `email`"));
105
}
106

            
107
#[supp_macro::shared_runtime_test]
108
1
async fn test_refresh_handler_without_cookie() {
109
1
    let app_state = create_test_app_state().await;
110
1
    let app = Router::new()
111
1
        .route(
112
1
            "/auth/refresh",
113
1
            get(web::session::refresh_access_token_handler),
114
1
        )
115
1
        // The route lives behind `auth` in production, which is what inserts
116
1
        // this extension; without it axum rejects before the handler runs.
117
1
        .layer(axum::Extension(create_mock_jwt_auth(create_mock_user())))
118
1
        .with_state(app_state);
119

            
120
1
    let response = app
121
1
        .oneshot(
122
1
            Request::builder()
123
1
                .method("GET")
124
1
                .uri("/auth/refresh")
125
1
                .body(Body::empty())
126
1
                .unwrap(),
127
1
        )
128
1
        .await
129
        .unwrap();
130

            
131
1
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
132
}
133

            
134
#[supp_macro::shared_runtime_test]
135
1
async fn test_refresh_handler_with_simple_invalid_cookie() {
136
1
    let app_state = create_test_app_state().await;
137
1
    let app = Router::new()
138
1
        .route(
139
1
            "/auth/refresh",
140
1
            get(web::session::refresh_access_token_handler),
141
1
        )
142
1
        // The route lives behind `auth` in production, which is what inserts
143
1
        // this extension; without it axum rejects before the handler runs.
144
1
        .layer(axum::Extension(create_mock_jwt_auth(create_mock_user())))
145
1
        .with_state(app_state);
146

            
147
1
    let response = app
148
1
        .oneshot(
149
1
            Request::builder()
150
1
                .method("GET")
151
1
                .uri("/auth/refresh")
152
1
                .header("cookie", "refresh_token=invalid")
153
1
                .body(Body::empty())
154
1
                .unwrap(),
155
1
        )
156
1
        .await
157
        .unwrap();
158

            
159
1
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
160
}
161

            
162
/// Registration must produce a *verified* user.
163
///
164
/// `jwt_auth` re-reads `users.verified` on every authenticated request and 401s
165
/// when it is false, and nothing in the codebase ever sets the flag — there is
166
/// no verification endpoint and no email flow. So an account created with the
167
/// column default authenticates once and is then unusable, which is exactly
168
/// what the first real registration hit on 2026-09-06. Registration is
169
/// admin-gated, so the admin creating the account has already vouched for it.
170
#[supp_macro::shared_runtime_test]
171
1
async fn test_register_handler_creates_a_verified_user() {
172
1
    let app_state = create_test_app_state().await;
173
1
    let app = Router::new()
174
1
        .route("/auth/register", post(web::register::register_user_handler))
175
1
        .with_state(app_state);
176

            
177
1
    let email = format!(
178
        "verified-probe-{}@example.com",
179
1
        uuid::Uuid::new_v4().simple()
180
    );
181
1
    let _tenant = TestTenant::registered(email.clone());
182
1
    let response = app
183
1
        .oneshot(
184
1
            Request::builder()
185
1
                .method("POST")
186
1
                .uri("/auth/register")
187
1
                .header("content-type", "application/json")
188
1
                .body(Body::from(
189
1
                    json!({ "name": "Verified Probe", "email": email, "password": "password123" })
190
1
                        .to_string(),
191
1
                ))
192
1
                .unwrap(),
193
1
        )
194
1
        .await
195
        .unwrap();
196

            
197
1
    let mut conn = server::db::get_connection().await.expect("connection");
198
1
    let verified: Option<bool> = sqlx::query_scalar("SELECT verified FROM users WHERE email = $1")
199
1
        .bind(&email)
200
1
        .fetch_optional(&mut *conn)
201
1
        .await
202
1
        .expect("the directory lookup");
203

            
204
1
    assert_eq!(response.status(), StatusCode::OK, "registration failed");
205
1
    let verified = verified.expect("the registered row");
206

            
207
1
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
208
1
        .await
209
1
        .expect("response body");
210
1
    let fragment = String::from_utf8(body.to_vec()).expect("html body");
211

            
212
1
    assert_eq!(
213
1
        fragment,
214
1
        format!(r#"<div class="success-alert">User {email} created</div>"#)
215
    );
216
1
    assert!(
217
1
        verified,
218
        "a registered user must be verified; an unverified one 401s on every request"
219
    );
220
}
221

            
222
/// The A2 gate itself: `verify` compares the token's generation against the
223
/// directory. Nothing else covers that join — the server tests cover the bump,
224
/// the token tests cover the claim riding in the signature.
225
#[supp_macro::shared_runtime_test]
226
1
async fn test_password_change_stops_existing_tokens_verifying() {
227
1
    let id = uuid::Uuid::new_v4();
228
1
    let _row = TestTenant::directory_row(id);
229
1
    seed_directory_user(id).await;
230

            
231
1
    let token = web::token::generate_jwt_token(
232
1
        id,
233
1
        15,
234
1
        crate::common::TEST_PRIVATE_KEY_B64,
235
1
        web::token::TokenType::Access,
236
1
        0,
237
1
    )
238
1
    .expect("sign")
239
1
    .token
240
1
    .expect("token string");
241
4
    let verifies = async || {
242
2
        web::auth_keys::verify(&token, web::token::TokenType::Access)
243
2
            .await
244
2
            .expect("the directory is reachable in this test")
245
            .is_some()
246
4
    };
247

            
248
1
    let before = verifies().await;
249
1
    let changed = server::command::user::change_password(id, "password123", "password456").await;
250
1
    let after = verifies().await;
251

            
252
1
    assert!(before, "a freshly minted token must verify");
253
1
    assert!(changed.is_ok(), "the password change must succeed");
254
1
    assert!(!after, "it must stop verifying once the password changes");
255
}
256

            
257
/// A directory row whose password is `password123`, with the fixture public key
258
/// so `verify` can check a token we signed locally. No tenant database: `verify`
259
/// reads only the global directory.
260
1
async fn seed_directory_user(id: uuid::Uuid) {
261
1
    let hash = argon2::PasswordHasher::hash_password(&argon2::Argon2::default(), b"password123")
262
1
        .expect("hash")
263
1
        .to_string();
264
1
    let mut conn = server::db::get_connection().await.expect("connection");
265
1
    sqlx::query(
266
1
        "INSERT INTO users (id, user_name, email, user_password, database_name, \
267
1
         jwt_public_key, verified) VALUES ($1, 'pw-probe', $2, $3, 'unused', $4, TRUE)",
268
1
    )
269
1
    .bind(id)
270
1
    .bind(format!("pwchange-{}@example.test", id.simple()))
271
1
    .bind(&hash)
272
1
    .bind(crate::common::TEST_PUBLIC_KEY_B64)
273
1
    .execute(&mut *conn)
274
1
    .await
275
1
    .expect("seed the probe row");
276
1
}
277

            
278
#[supp_macro::shared_runtime_test]
279
1
async fn a_session_refreshed_on_the_way_in_is_reported_not_redeemed() {
280
1
    let app_state = create_test_app_state().await;
281
1
    let mut jwt = create_mock_jwt_auth(create_mock_user());
282
1
    jwt.refreshed = true;
283

            
284
1
    let response = web::session::refresh_access_token_handler(
285
1
        axum_extra::extract::CookieJar::default(),
286
1
        axum::Extension(jwt),
287
1
        axum::extract::State(app_state),
288
1
    )
289
1
    .await
290
1
    .expect("the refresh is reported")
291
    .into_response();
292

            
293
1
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
294
1
        .await
295
        .unwrap();
296
1
    let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
297
1
    assert_eq!(body["refreshed_by"], "session");
298
}
299

            
300
3
async fn post_register(app: &Router, email: &str) -> axum::response::Response {
301
3
    app.clone()
302
3
        .oneshot(
303
3
            Request::builder()
304
3
                .method("POST")
305
3
                .uri("/auth/register")
306
3
                .header("content-type", "application/json")
307
3
                .body(Body::from(
308
3
                    json!({ "name": "Twice", "email": email, "password": "password123" })
309
3
                        .to_string(),
310
3
                ))
311
3
                .unwrap(),
312
3
        )
313
3
        .await
314
        .unwrap()
315
3
}
316

            
317
#[supp_macro::shared_runtime_test]
318
1
async fn test_register_handler_refuses_the_same_email_twice() {
319
1
    let app = Router::new()
320
1
        .route("/auth/register", post(web::register::register_user_handler))
321
1
        .with_state(create_test_app_state().await);
322
1
    let email = format!("twice-{}@example.com", uuid::Uuid::new_v4().simple());
323
1
    let _tenant = TestTenant::registered(email.clone());
324

            
325
1
    let first = post_register(&app, &email).await;
326
1
    let second = post_register(&app, &format!("  {}  ", email.to_uppercase())).await;
327

            
328
1
    assert_eq!(first.status(), StatusCode::OK);
329
1
    assert_eq!(second.status(), StatusCode::CONFLICT);
330
1
    assert_eq!(
331
1
        body_of(second).await,
332
1
        r#"{"message":"User with that email already exists","status":"error"}"#
333
    );
334
}
335

            
336
#[supp_macro::shared_runtime_test]
337
1
async fn test_register_handler_refuses_a_blank_email() {
338
1
    let app = Router::new()
339
1
        .route("/auth/register", post(web::register::register_user_handler))
340
1
        .with_state(create_test_app_state().await);
341

            
342
1
    let response = post_register(&app, " \t ").await;
343

            
344
1
    assert_eq!(response.status(), StatusCode::BAD_REQUEST);
345
1
    assert_eq!(
346
1
        body_of(response).await,
347
1
        r#"{"message":"Email must not be empty","status":"error"}"#
348
    );
349
}