heldar-kernel 0.1.8

Heldar kernel — media/DVR control plane, perception ingest + sampler, zone engine, auth, and the worker SDK contract. The open, domain-agnostic platform that domain apps build on.
Documentation
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
//! Stage 4 auth + user/API-key administration.
//!
//! `/auth/login` exchanges username+password for a bearer session token; `/auth/logout` revokes it;
//! `/auth/me` reports the caller. `/users` and `/api-keys` are admin-only management surfaces. All
//! mutations are written to the immutable audit log.

use axum::extract::{Path, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{AppendHeaders, IntoResponse};
use axum::routing::{get, post};
use axum::{Json, Router};
use chrono::Utc;
use serde_json::{json, Value};
use uuid::Uuid;

use crate::auth::{self, Principal, Role};
use crate::error::{AppError, AppResult};
use crate::models::{
    ApiKey, ApiKeyCreate, ApiKeyView, LoginRequest, User, UserCreate, UserUpdate, UserView,
};
use crate::state::AppState;

pub fn router() -> Router<AppState> {
    Router::new()
        .route("/api/v1/auth/login", post(login))
        .route("/api/v1/auth/logout", post(logout))
        .route("/api/v1/auth/me", get(me))
        .route("/api/v1/users", get(list_users).post(create_user))
        .route(
            "/api/v1/users/{id}",
            axum::routing::patch(update_user).delete(delete_user),
        )
        .route("/api/v1/api-keys", get(list_api_keys).post(create_api_key))
        .route(
            "/api/v1/api-keys/{id}",
            axum::routing::delete(delete_api_key),
        )
}

const MIN_PASSWORD_LEN: usize = 8;

async fn login(
    State(st): State<AppState>,
    Json(body): Json<LoginRequest>,
) -> AppResult<impl IntoResponse> {
    let candidate = sqlx::query_as::<_, User>("SELECT * FROM users WHERE username = ?")
        .bind(body.username.trim())
        .fetch_optional(&st.pool)
        .await?;
    // Always run argon2 verification (against a dummy hash when the user is missing/disabled) so
    // login latency does not reveal whether an account exists. The error is uniform too.
    let phc = candidate
        .as_ref()
        .map(|u| u.password_hash.as_str())
        .unwrap_or_else(|| auth::dummy_password_hash());
    let password_ok = auth::verify_password(&body.password, phc);
    let user = match candidate {
        Some(u) if u.active && password_ok => u,
        _ => return Err(AppError::Unauthorized("invalid credentials".into())),
    };
    let (token, expires_at) = auth::issue_session(&st.pool, &st.cfg, &user.id).await?;
    let principal = Principal {
        id: user.id.clone(),
        name: user
            .display_name
            .clone()
            .unwrap_or_else(|| user.username.clone()),
        role: Role::parse(&user.role).unwrap_or(Role::Viewer),
        kind: crate::auth::PrincipalKind::User,
    };
    auth::audit(&st.pool, &principal, "login", "user", &user.id, json!({})).await;
    // Set the session as an HttpOnly cookie (browser auth: not JS-readable, so XSS can't exfiltrate
    // it; the media plane gets it automatically since the SPA is same-origin). The token is still in
    // the body for non-browser clients; browsers should ignore it and rely on the cookie.
    let cookie = auth::session_cookie(&token, &st.cfg);
    let body = Json(json!({
        "token": token,
        "expires_at": expires_at,
        "user": UserView::from(user),
    }));
    Ok((AppendHeaders([(header::SET_COOKIE, cookie)]), body))
}

async fn logout(State(st): State<AppState>, headers: HeaderMap) -> AppResult<impl IntoResponse> {
    if let Some(tok) = auth::token_from_headers(&headers) {
        auth::revoke_session(&st.pool, &tok).await?;
    }
    // Clear the session cookie regardless (idempotent logout).
    let cookie = auth::clear_session_cookie(&st.cfg);
    Ok((
        StatusCode::NO_CONTENT,
        AppendHeaders([(header::SET_COOKIE, cookie)]),
    ))
}

async fn me(principal: Principal) -> AppResult<Json<Value>> {
    Ok(Json(json!({
        "id": principal.id,
        "name": principal.name,
        "role": principal.role.as_str(),
        "kind": match principal.kind {
            crate::auth::PrincipalKind::User => "user",
            crate::auth::PrincipalKind::ApiKey => "api_key",
            crate::auth::PrincipalKind::System => "system",
        },
    })))
}

async fn list_users(
    State(st): State<AppState>,
    principal: Principal,
) -> AppResult<Json<Vec<UserView>>> {
    principal.require(principal.can_admin(), "manage users")?;
    let users = sqlx::query_as::<_, User>("SELECT * FROM users ORDER BY username ASC")
        .fetch_all(&st.pool)
        .await?;
    Ok(Json(users.into_iter().map(UserView::from).collect()))
}

async fn create_user(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<UserCreate>,
) -> AppResult<(StatusCode, Json<UserView>)> {
    principal.require(principal.can_admin(), "create users")?;
    let username = body.username.trim();
    if username.is_empty() {
        return Err(AppError::BadRequest("`username` is required".into()));
    }
    if body.password.len() < MIN_PASSWORD_LEN {
        return Err(AppError::BadRequest(format!(
            "`password` must be at least {MIN_PASSWORD_LEN} characters"
        )));
    }
    let role = body.role.as_deref().unwrap_or("viewer");
    if !Role::is_valid(role) {
        return Err(AppError::BadRequest(
            "`role` must be admin|manager|guard|viewer|integration".into(),
        ));
    }
    let hash = auth::hash_password(&body.password)?;
    let id = format!("usr_{}", Uuid::new_v4().simple());
    let now = Utc::now();
    sqlx::query(
        "INSERT INTO users (id, username, password_hash, role, display_name, active, created_at, updated_at)
         VALUES (?,?,?,?,?,?,?,?)",
    )
    .bind(&id)
    .bind(username)
    .bind(hash)
    .bind(role)
    .bind(&body.display_name)
    .bind(body.active.unwrap_or(true))
    .bind(now)
    .bind(now)
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_user",
        "user",
        &id,
        json!({ "role": role }),
    )
    .await;
    let user = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok((StatusCode::CREATED, Json(UserView::from(user))))
}

async fn update_user(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
    Json(body): Json<UserUpdate>,
) -> AppResult<Json<UserView>> {
    principal.require(principal.can_admin(), "modify users")?;
    let cur = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("user {id} not found")))?;

    let role = body.role.unwrap_or_else(|| cur.role.clone());
    if !Role::is_valid(&role) {
        return Err(AppError::BadRequest(
            "`role` must be admin|manager|guard|viewer|integration".into(),
        ));
    }
    let active = body.active.unwrap_or(cur.active);
    let display_name = body.display_name.or(cur.display_name);
    let password_hash = match body.password {
        Some(p) if p.len() >= MIN_PASSWORD_LEN => auth::hash_password(&p)?,
        Some(_) => {
            return Err(AppError::BadRequest(format!(
                "`password` must be at least {MIN_PASSWORD_LEN} characters"
            )))
        }
        None => cur.password_hash,
    };
    // Lockout guard, ATOMIC: when this change demotes/disables an admin, the UPDATE only applies if
    // ANOTHER active admin still exists at write time. SQLite serializes writers, so two concurrent
    // demotions of different admins cannot both succeed — the second finds the EXISTS false and is
    // rejected, always leaving an admin standing. (A separate COUNT-then-UPDATE would race.)
    let demoting_admin = cur.role == "admin" && (role != "admin" || !active);
    let affected = if demoting_admin {
        sqlx::query(
            "UPDATE users SET password_hash=?, role=?, display_name=?, active=?, updated_at=? \
             WHERE id=? AND EXISTS (SELECT 1 FROM users WHERE role='admin' AND active=1 AND id != ?)",
        )
        .bind(&password_hash)
        .bind(&role)
        .bind(&display_name)
        .bind(active)
        .bind(Utc::now())
        .bind(&id)
        .bind(&id)
        .execute(&st.pool)
        .await?
        .rows_affected()
    } else {
        sqlx::query(
            "UPDATE users SET password_hash=?, role=?, display_name=?, active=?, updated_at=? WHERE id=?",
        )
        .bind(&password_hash)
        .bind(&role)
        .bind(&display_name)
        .bind(active)
        .bind(Utc::now())
        .bind(&id)
        .execute(&st.pool)
        .await?
        .rows_affected()
    };
    if demoting_admin && affected == 0 {
        return Err(AppError::BadRequest(
            "cannot demote or disable the last active admin".into(),
        ));
    }
    // Revoke sessions if the account was disabled.
    if !active {
        let _ = sqlx::query("DELETE FROM sessions WHERE user_id = ?")
            .bind(&id)
            .execute(&st.pool)
            .await;
    }
    auth::audit(
        &st.pool,
        &principal,
        "update_user",
        "user",
        &id,
        json!({ "role": role, "active": active }),
    )
    .await;
    let user = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = ?")
        .bind(&id)
        .fetch_one(&st.pool)
        .await?;
    Ok(Json(UserView::from(user)))
}

async fn delete_user(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<StatusCode> {
    principal.require(principal.can_admin(), "delete users")?;
    if principal.id == id {
        return Err(AppError::BadRequest(
            "cannot delete your own account".into(),
        ));
    }
    let cur = sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = ?")
        .bind(&id)
        .fetch_optional(&st.pool)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("user {id} not found")))?;
    // Atomic last-admin guard (see update_user): the conditional DELETE removes an admin only if
    // another active admin still exists, so concurrent deletes cannot drain the admins to zero.
    let affected = if cur.role == "admin" {
        sqlx::query(
            "DELETE FROM users WHERE id = ? AND EXISTS (SELECT 1 FROM users WHERE role='admin' AND active=1 AND id != ?)",
        )
        .bind(&id)
        .bind(&id)
        .execute(&st.pool)
        .await?
        .rows_affected()
    } else {
        sqlx::query("DELETE FROM users WHERE id = ?")
            .bind(&id)
            .execute(&st.pool)
            .await?
            .rows_affected()
    };
    if cur.role == "admin" && affected == 0 {
        return Err(AppError::BadRequest(
            "cannot delete the last active admin".into(),
        ));
    }
    auth::audit(&st.pool, &principal, "delete_user", "user", &id, json!({})).await;
    Ok(StatusCode::NO_CONTENT)
}

async fn list_api_keys(
    State(st): State<AppState>,
    principal: Principal,
) -> AppResult<Json<Vec<ApiKeyView>>> {
    principal.require(principal.can_admin(), "manage API keys")?;
    let keys = sqlx::query_as::<_, ApiKey>("SELECT * FROM api_keys ORDER BY created_at DESC")
        .fetch_all(&st.pool)
        .await?;
    Ok(Json(keys.into_iter().map(ApiKeyView::from).collect()))
}

async fn create_api_key(
    State(st): State<AppState>,
    principal: Principal,
    Json(body): Json<ApiKeyCreate>,
) -> AppResult<(StatusCode, Json<Value>)> {
    principal.require(principal.can_admin(), "create API keys")?;
    if body.name.trim().is_empty() {
        return Err(AppError::BadRequest("`name` is required".into()));
    }
    let role = body.role.as_deref().unwrap_or("integration");
    if !Role::is_valid(role) {
        return Err(AppError::BadRequest(
            "`role` must be admin|manager|guard|viewer|integration".into(),
        ));
    }
    let key = auth::random_token(auth::APIKEY_PREFIX);
    let prefix: String = key.chars().take(12).collect();
    let id = format!("key_{}", Uuid::new_v4().simple());
    sqlx::query(
        "INSERT INTO api_keys (id, name, key_hash, key_prefix, role, active, created_at)
         VALUES (?,?,?,?,?,1,?)",
    )
    .bind(&id)
    .bind(body.name.trim())
    .bind(auth::token_hash(&key))
    .bind(&prefix)
    .bind(role)
    .bind(Utc::now())
    .execute(&st.pool)
    .await?;
    auth::audit(
        &st.pool,
        &principal,
        "create_api_key",
        "api_key",
        &id,
        json!({ "role": role }),
    )
    .await;
    // The full key is returned exactly once; only its hash is stored.
    Ok((
        StatusCode::CREATED,
        Json(json!({ "id": id, "name": body.name.trim(), "role": role, "key": key })),
    ))
}

async fn delete_api_key(
    State(st): State<AppState>,
    principal: Principal,
    Path(id): Path<String>,
) -> AppResult<StatusCode> {
    principal.require(principal.can_admin(), "delete API keys")?;
    let res = sqlx::query("DELETE FROM api_keys WHERE id = ?")
        .bind(&id)
        .execute(&st.pool)
        .await?;
    if res.rows_affected() == 0 {
        return Err(AppError::NotFound(format!("api key {id} not found")));
    }
    auth::audit(
        &st.pool,
        &principal,
        "delete_api_key",
        "api_key",
        &id,
        json!({}),
    )
    .await;
    Ok(StatusCode::NO_CONTENT)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::services::recorder::RecorderManager;
    use crate::services::sampler::SamplerManager;
    use std::sync::Arc;

    /// Build a minimal in-memory AppState (single connection so the :memory: DB persists across
    /// queries) with real migrations applied, mirroring the helper used by the other route tests.
    async fn test_state(auth_enabled: bool) -> AppState {
        let pool = sqlx::sqlite::SqlitePoolOptions::new()
            .max_connections(1)
            .connect("sqlite::memory:")
            .await
            .unwrap();
        crate::db::run_migrations(&pool).await.unwrap();
        let mut cfg = Config::from_env();
        cfg.auth_enabled = auth_enabled;
        let cfg = Arc::new(cfg);
        AppState {
            recorder: RecorderManager::new(pool.clone(), cfg.clone()),
            sampler: SamplerManager::new(pool.clone(), cfg.clone()),
            mirror: None,
            consumers: Arc::new(Vec::new()),
            modules: Arc::new(Vec::new()),
            catalog: Arc::new(crate::services::registry::CatalogService::new(&cfg)),
            http: reqwest::Client::new(),
            started_at: chrono::Utc::now(),
            pool,
            cfg,
        }
    }

    fn viewer() -> Principal {
        Principal {
            id: "usr_viewer".into(),
            name: "vee".into(),
            role: Role::Viewer,
            kind: auth::PrincipalKind::User,
        }
    }

    #[tokio::test]
    async fn me_reports_principal_role_and_kind() {
        // System admin (auth-disabled implicit principal) reports role=admin, kind=system.
        let Json(v) = me(Principal::system_admin()).await.unwrap();
        assert_eq!(v["id"], "system");
        assert_eq!(v["name"], "system");
        assert_eq!(v["role"], "admin");
        assert_eq!(v["kind"], "system");

        // A user-kind principal maps to kind=user and echoes its role.
        let Json(v) = me(viewer()).await.unwrap();
        assert_eq!(v["role"], "viewer");
        assert_eq!(v["kind"], "user");
    }

    #[tokio::test]
    async fn create_user_validation_rejects_bad_input() {
        let st = test_state(false).await;

        // Empty (whitespace-only) username.
        let err = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "   ".into(),
                password: "x".repeat(MIN_PASSWORD_LEN),
                role: None,
                display_name: None,
                active: None,
            }),
        )
        .await
        .err()
        .unwrap();
        match err {
            AppError::BadRequest(m) => assert!(m.contains("username")),
            other => panic!("expected BadRequest, got {other:?}"),
        }

        // Password shorter than MIN_PASSWORD_LEN.
        let err = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "joe".into(),
                password: "x".repeat(MIN_PASSWORD_LEN - 1),
                role: None,
                display_name: None,
                active: None,
            }),
        )
        .await
        .err()
        .unwrap();
        match err {
            AppError::BadRequest(m) => assert!(m.contains("password")),
            other => panic!("expected BadRequest, got {other:?}"),
        }

        // Unrecognized role.
        let err = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "joe".into(),
                password: "x".repeat(MIN_PASSWORD_LEN),
                role: Some("superuser".into()),
                display_name: None,
                active: None,
            }),
        )
        .await
        .err()
        .unwrap();
        match err {
            AppError::BadRequest(m) => assert!(m.contains("role")),
            other => panic!("expected BadRequest, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn create_user_defaults_and_list_orders() {
        let st = test_state(false).await;

        // Surrounding whitespace is trimmed; role defaults to viewer; active defaults to true.
        let (status, Json(uv)) = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "  bravo  ".into(),
                password: "x".repeat(MIN_PASSWORD_LEN),
                role: None,
                display_name: None,
                active: None,
            }),
        )
        .await
        .unwrap();
        assert_eq!(status, StatusCode::CREATED);
        assert_eq!(uv.username, "bravo");
        assert_eq!(uv.role, "viewer");
        assert!(uv.active);

        let _ = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "alpha".into(),
                password: "x".repeat(MIN_PASSWORD_LEN),
                role: Some("manager".into()),
                display_name: Some("Al".into()),
                active: None,
            }),
        )
        .await
        .unwrap();

        // list_users is ordered by username ASC.
        let Json(users) = list_users(State(st.clone()), Principal::system_admin())
            .await
            .unwrap();
        assert_eq!(users.len(), 2);
        assert_eq!(users[0].username, "alpha");
        assert_eq!(users[1].username, "bravo");
        assert_eq!(users[0].role, "manager");
    }

    #[tokio::test]
    async fn non_admin_is_forbidden() {
        let st = test_state(false).await;

        let err = list_users(State(st.clone()), viewer()).await.err().unwrap();
        assert!(matches!(err, AppError::Forbidden(_)));

        let err = create_api_key(
            State(st.clone()),
            viewer(),
            Json(ApiKeyCreate {
                name: "k".into(),
                role: None,
            }),
        )
        .await
        .err()
        .unwrap();
        assert!(matches!(err, AppError::Forbidden(_)));
    }

    #[tokio::test]
    async fn delete_user_rejects_self() {
        let st = test_state(false).await;
        // system_admin has id "system"; deleting that same id hits the self-deletion guard before
        // any existence check.
        let err = delete_user(
            State(st.clone()),
            Principal::system_admin(),
            Path("system".to_string()),
        )
        .await
        .err()
        .unwrap();
        assert!(matches!(err, AppError::BadRequest(_)));
    }

    #[tokio::test]
    async fn update_user_protects_last_admin() {
        let st = test_state(false).await;

        // The only admin in the table.
        let (_, Json(admin)) = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "rootadmin".into(),
                password: "x".repeat(MIN_PASSWORD_LEN),
                role: Some("admin".into()),
                display_name: None,
                active: None,
            }),
        )
        .await
        .unwrap();

        // Demoting the last active admin is refused.
        let err = update_user(
            State(st.clone()),
            Principal::system_admin(),
            Path(admin.id.clone()),
            Json(UserUpdate {
                role: Some("viewer".into()),
                ..Default::default()
            }),
        )
        .await
        .err()
        .unwrap();
        assert!(matches!(err, AppError::BadRequest(_)));
    }

    /// AppState around a caller-provided pool — for concurrency tests needing a shared,
    /// multi-connection DB (the single-connection in-memory `test_state` would serialize the race).
    async fn state_with_pool(pool: sqlx::SqlitePool) -> AppState {
        let mut cfg = Config::from_env();
        cfg.auth_enabled = false;
        let cfg = std::sync::Arc::new(cfg);
        AppState {
            recorder: RecorderManager::new(pool.clone(), cfg.clone()),
            sampler: SamplerManager::new(pool.clone(), cfg.clone()),
            mirror: None,
            consumers: std::sync::Arc::new(Vec::new()),
            modules: std::sync::Arc::new(Vec::new()),
            catalog: std::sync::Arc::new(crate::services::registry::CatalogService::new(&cfg)),
            http: reqwest::Client::new(),
            started_at: chrono::Utc::now(),
            pool,
            cfg,
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn concurrent_demotion_cannot_drain_the_last_admin() {
        // Temp-FILE DB so the pool's connections see each other's committed writes — the
        // single-connection in-memory pool used elsewhere would serialize and hide the race.
        let dbpath =
            std::env::temp_dir().join(format!("heldar-authrace-{}.db", std::process::id()));
        let _ = std::fs::remove_file(&dbpath);
        let url = format!("sqlite://{}?mode=rwc", dbpath.display());
        let pool = sqlx::sqlite::SqlitePoolOptions::new()
            .max_connections(4)
            .connect(&url)
            .await
            .unwrap();
        crate::db::run_migrations(&pool).await.unwrap();
        let st = state_with_pool(pool.clone()).await;

        // Exactly two active admins.
        let mut ids = Vec::new();
        for u in ["admin_a", "admin_b"] {
            let (_, Json(v)) = create_user(
                State(st.clone()),
                Principal::system_admin(),
                Json(UserCreate {
                    username: u.into(),
                    password: "x".repeat(MIN_PASSWORD_LEN),
                    role: Some("admin".into()),
                    display_name: None,
                    active: None,
                }),
            )
            .await
            .unwrap();
            ids.push(v.id);
        }

        let demote = || {
            Json(UserUpdate {
                role: Some("viewer".into()),
                ..Default::default()
            })
        };
        // Demote BOTH admins at once. Old check-then-act: both pass -> zero admins. Atomic guard:
        // at least one is rejected, an admin always remains.
        let (r1, r2) = tokio::join!(
            update_user(
                State(st.clone()),
                Principal::system_admin(),
                Path(ids[0].clone()),
                demote(),
            ),
            update_user(
                State(st.clone()),
                Principal::system_admin(),
                Path(ids[1].clone()),
                demote(),
            ),
        );

        let rejected = [r1.is_err(), r2.is_err()]
            .into_iter()
            .filter(|e| *e)
            .count();
        let remaining: i64 =
            sqlx::query_scalar("SELECT COUNT(*) FROM users WHERE role='admin' AND active=1")
                .fetch_one(&pool)
                .await
                .unwrap();
        let _ = std::fs::remove_file(&dbpath);
        assert!(
            remaining >= 1,
            "LOCKOUT: concurrent demotions drained all active admins (remaining={remaining})"
        );
        assert!(
            rejected >= 1,
            "at least one of two concurrent last-admin demotions must be rejected"
        );
    }

    #[tokio::test]
    async fn create_api_key_shape_and_validation() {
        let st = test_state(false).await;

        // Empty name is rejected.
        let err = create_api_key(
            State(st.clone()),
            Principal::system_admin(),
            Json(ApiKeyCreate {
                name: "  ".into(),
                role: None,
            }),
        )
        .await
        .err()
        .unwrap();
        assert!(matches!(err, AppError::BadRequest(_)));

        // Valid creation: role defaults to integration, the secret is prefixed and returned once.
        let (status, Json(v)) = create_api_key(
            State(st.clone()),
            Principal::system_admin(),
            Json(ApiKeyCreate {
                name: "  cam-bridge  ".into(),
                role: None,
            }),
        )
        .await
        .unwrap();
        assert_eq!(status, StatusCode::CREATED);
        assert_eq!(v["name"], "cam-bridge");
        assert_eq!(v["role"], "integration");
        let key = v["key"].as_str().unwrap();
        assert!(key.starts_with(auth::APIKEY_PREFIX));
    }

    #[tokio::test]
    async fn login_unknown_wrong_then_success() {
        let st = test_state(false).await;

        // No users yet -> unknown user is uniformly Unauthorized.
        let err = login(
            State(st.clone()),
            Json(LoginRequest {
                username: "ghost".into(),
                password: "whatever1".into(),
            }),
        )
        .await
        .err()
        .unwrap();
        assert!(matches!(err, AppError::Unauthorized(_)));

        // Seed an operator.
        let _ = create_user(
            State(st.clone()),
            Principal::system_admin(),
            Json(UserCreate {
                username: "operator".into(),
                password: "operator-pass".into(),
                role: Some("manager".into()),
                display_name: None,
                active: None,
            }),
        )
        .await
        .unwrap();

        // Wrong password for an existing user is also Unauthorized.
        let err = login(
            State(st.clone()),
            Json(LoginRequest {
                username: "operator".into(),
                password: "not-the-pass".into(),
            }),
        )
        .await
        .err()
        .unwrap();
        assert!(matches!(err, AppError::Unauthorized(_)));

        // Correct credentials succeed: 200, an HttpOnly session cookie, and one persisted session.
        let resp = login(
            State(st.clone()),
            Json(LoginRequest {
                username: "operator".into(),
                password: "operator-pass".into(),
            }),
        )
        .await
        .unwrap()
        .into_response();
        assert_eq!(resp.status(), StatusCode::OK);
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(set_cookie.contains(auth::SESSION_COOKIE));
        assert!(set_cookie.contains("HttpOnly"));

        let sessions: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM sessions")
            .fetch_one(&st.pool)
            .await
            .unwrap();
        assert_eq!(sessions, 1);
    }

    #[tokio::test]
    async fn logout_is_no_content_and_clears_cookie() {
        let st = test_state(false).await;
        // No credentials present -> still a clean, idempotent logout.
        let resp = logout(State(st.clone()), HeaderMap::new())
            .await
            .unwrap()
            .into_response();
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .unwrap()
            .to_str()
            .unwrap();
        assert!(set_cookie.contains(auth::SESSION_COOKIE));
        assert!(set_cookie.contains("Max-Age=0"));
    }
}