ironclaw 0.24.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
//! Multi-tenant isolation tests for the web gateway.
//!
//! Tests cover workspace pool scoping, job handler isolation, and auth
//! enforcement on protected endpoints. Uses `LibSqlBackend::new_local()`
//! with a temporary directory for a real (but ephemeral) database.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use axum::Router;
use axum::body::Body;
use axum::http::{Method, Request, StatusCode};
use axum::middleware;
use axum::routing::{delete, get, post};
use tower::ServiceExt;
use uuid::Uuid;

use crate::channels::web::auth::{
    AuthenticatedUser, MultiAuthState, UserIdentity, auth_middleware,
};
use crate::channels::web::server::{
    ActiveConfigSnapshot, GatewayState, PerUserRateLimiter, PromptQueue, RateLimiter, WorkspacePool,
};
use crate::channels::web::sse::SseManager;

// ── Helpers ────────────────────────────────────────────────────────────

/// Create a two-user `MultiAuthState` for alice and bob.
fn two_user_auth() -> MultiAuthState {
    let mut tokens = HashMap::new();
    tokens.insert(
        "tok-alice".to_string(),
        UserIdentity {
            user_id: "alice".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec!["shared".to_string()],
        },
    );
    tokens.insert(
        "tok-bob".to_string(),
        UserIdentity {
            user_id: "bob".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec!["shared".to_string(), "alice".to_string()],
        },
    );
    MultiAuthState::multi(tokens)
}

/// Build a `GatewayState` with configurable store and prompt queue.
fn build_state(
    store: Option<Arc<dyn crate::db::Database>>,
    prompt_queue: Option<PromptQueue>,
) -> Arc<GatewayState> {
    Arc::new(GatewayState {
        msg_tx: tokio::sync::RwLock::new(None),
        sse: Arc::new(SseManager::new()),
        workspace: None,
        workspace_pool: None,
        session_manager: None,
        log_broadcaster: None,
        log_level_handle: None,
        extension_manager: None,
        tool_registry: None,
        store,
        job_manager: None,
        prompt_queue,
        owner_id: "test".to_string(),
        shutdown_tx: tokio::sync::RwLock::new(None),
        ws_tracker: None,
        llm_provider: None,
        skill_registry: None,
        skill_catalog: None,
        scheduler: None,
        chat_rate_limiter: PerUserRateLimiter::new(30, 60),
        oauth_rate_limiter: RateLimiter::new(10, 60),
        webhook_rate_limiter: RateLimiter::new(10, 60),
        registry_entries: Vec::new(),
        cost_guard: None,
        routine_engine: Arc::new(tokio::sync::RwLock::new(None)),
        startup_time: std::time::Instant::now(),
        active_config: ActiveConfigSnapshot::default(),
        secrets_store: None,
        db_auth: None,
    })
}

/// Create a libSQL-backed test database in a temporary directory.
///
/// Returns the database and a `TempDir` guard — the database file is
/// deleted when the guard is dropped.
#[cfg(feature = "libsql")]
async fn test_db() -> (Arc<dyn crate::db::Database>, tempfile::TempDir) {
    use crate::db::Database;
    let dir = tempfile::tempdir().expect("failed to create temp dir"); // safety: test-only
    let path = dir.path().join("test.db");
    let backend = crate::db::libsql::LibSqlBackend::new_local(&path)
        .await
        .expect("failed to create test LibSqlBackend"); // safety: test-only
    backend
        .run_migrations()
        .await
        .expect("failed to run migrations"); // safety: test-only
    (Arc::new(backend) as Arc<dyn crate::db::Database>, dir)
}

/// Build a minimal Routine for testing.
fn make_routine(user_id: &str, name: &str) -> crate::agent::routine::Routine {
    let now = chrono::Utc::now();
    crate::agent::routine::Routine {
        id: Uuid::new_v4(),
        name: name.to_string(),
        description: format!("Test routine: {name}"),
        user_id: user_id.to_string(),
        enabled: true,
        trigger: crate::agent::routine::Trigger::Cron {
            schedule: "0 9 * * *".to_string(),
            timezone: None,
        },
        action: crate::agent::routine::RoutineAction::Lightweight {
            prompt: "hello".to_string(),
            context_paths: vec![],
            max_tokens: 1024,
            use_tools: false,
            max_tool_rounds: 3,
        },
        guardrails: crate::agent::routine::RoutineGuardrails {
            cooldown: Duration::from_secs(60),
            max_concurrent: 1,
            dedup_window: None,
        },
        notify: crate::agent::routine::NotifyConfig {
            channel: None,
            user: None,
            on_success: false,
            on_failure: true,
            on_attention: true,
        },
        last_run_at: None,
        next_fire_at: None,
        run_count: 0,
        consecutive_failures: 0,
        state: serde_json::json!({}),
        created_at: now,
        updated_at: now,
    }
}

/// Build a minimal SandboxJobRecord for testing.
fn make_sandbox_job(user_id: &str, task: &str) -> crate::history::SandboxJobRecord {
    let now = chrono::Utc::now();
    crate::history::SandboxJobRecord {
        id: Uuid::new_v4(),
        task: task.to_string(),
        status: "completed".to_string(),
        user_id: user_id.to_string(),
        project_dir: format!("/tmp/test-{}", Uuid::new_v4()),
        success: Some(true),
        failure_reason: None,
        created_at: now,
        started_at: Some(now),
        completed_at: Some(now),
        credential_grants_json: "[]".to_string(),
    }
}

// ═══════════════════════════════════════════════════════════════════════
// WorkspacePool Tests
// ═══════════════════════════════════════════════════════════════════════

#[cfg(feature = "libsql")]
mod workspace_pool {
    use super::*;
    use crate::config::{WorkspaceConfig, WorkspaceSearchConfig};
    use crate::workspace::EmbeddingCacheConfig;
    use crate::workspace::layer::MemoryLayer;

    #[tokio::test]
    async fn test_workspace_pool_applies_search_config() {
        let (db, _dir) = test_db().await;
        let search_config = WorkspaceSearchConfig {
            rrf_k: 42,
            ..Default::default()
        };
        let pool = WorkspacePool::new(
            db,
            None,
            EmbeddingCacheConfig::default(),
            search_config,
            WorkspaceConfig::default(),
        );
        let identity = UserIdentity {
            user_id: "alice".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec![],
        };
        let ws = pool.get_or_create(&identity).await;
        assert_eq!(ws.user_id(), "alice");
    }

    #[tokio::test]
    async fn test_workspace_pool_applies_memory_layers() {
        let (db, _dir) = test_db().await;
        let layers = vec![MemoryLayer {
            name: "shared-layer".to_string(),
            scope: "shared".to_string(),
            writable: false,
            sensitivity: Default::default(),
        }];
        let ws_config = WorkspaceConfig {
            memory_layers: layers,
            read_scopes: vec![],
        };
        let pool = WorkspacePool::new(
            db,
            None,
            EmbeddingCacheConfig::default(),
            WorkspaceSearchConfig::default(),
            ws_config,
        );
        let identity = UserIdentity {
            user_id: "alice".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec![],
        };
        let ws = pool.get_or_create(&identity).await;
        // Memory layer scope "shared" should appear in read_user_ids.
        assert!(
            ws.read_user_ids().contains(&"shared".to_string()),
            "expected 'shared' in read_user_ids, got {:?}",
            ws.read_user_ids()
        );
    }

    #[tokio::test]
    async fn test_workspace_pool_applies_identity_read_scopes() {
        let (db, _dir) = test_db().await;
        let pool = WorkspacePool::new(
            db,
            None,
            EmbeddingCacheConfig::default(),
            WorkspaceSearchConfig::default(),
            WorkspaceConfig::default(),
        );
        let identity = UserIdentity {
            user_id: "bob".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec!["alice".to_string(), "shared".to_string()],
        };
        let ws = pool.get_or_create(&identity).await;
        assert_eq!(ws.user_id(), "bob");
        assert!(
            ws.read_user_ids().contains(&"alice".to_string()),
            "expected 'alice' in read_user_ids from identity scopes"
        );
        assert!(
            ws.read_user_ids().contains(&"shared".to_string()),
            "expected 'shared' in read_user_ids from identity scopes"
        );
    }

    #[tokio::test]
    async fn test_workspace_pool_caches_per_user() {
        let (db, _dir) = test_db().await;
        let pool = WorkspacePool::new(
            db,
            None,
            EmbeddingCacheConfig::default(),
            WorkspaceSearchConfig::default(),
            WorkspaceConfig::default(),
        );
        let alice_id = UserIdentity {
            user_id: "alice".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec![],
        };
        let bob_id = UserIdentity {
            user_id: "bob".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec![],
        };

        let alice_ws1 = pool.get_or_create(&alice_id).await;
        let alice_ws2 = pool.get_or_create(&alice_id).await;
        let bob_ws = pool.get_or_create(&bob_id).await;

        // Same user gets the same Arc.
        assert!(Arc::ptr_eq(&alice_ws1, &alice_ws2));
        // Different users get different instances.
        assert!(!Arc::ptr_eq(&alice_ws1, &bob_ws));
        assert_eq!(alice_ws1.user_id(), "alice");
        assert_eq!(bob_ws.user_id(), "bob");
    }

    #[tokio::test]
    async fn test_workspace_pool_combines_global_and_identity_scopes() {
        let (db, _dir) = test_db().await;
        let ws_config = WorkspaceConfig {
            memory_layers: vec![],
            read_scopes: vec!["global-shared".to_string()],
        };
        let pool = WorkspacePool::new(
            db,
            None,
            EmbeddingCacheConfig::default(),
            WorkspaceSearchConfig::default(),
            ws_config,
        );
        let identity = UserIdentity {
            user_id: "alice".to_string(),
            role: "admin".to_string(),
            workspace_read_scopes: vec!["token-scope".to_string()],
        };
        let ws = pool.get_or_create(&identity).await;
        let scopes = ws.read_user_ids();
        // Primary scope
        assert!(scopes.contains(&"alice".to_string()));
        // Global config scope
        assert!(
            scopes.contains(&"global-shared".to_string()),
            "expected global scope 'global-shared', got {:?}",
            scopes
        );
        // Token identity scope
        assert!(
            scopes.contains(&"token-scope".to_string()),
            "expected token scope 'token-scope', got {:?}",
            scopes
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Jobs Handler Isolation Tests
// ═══════════════════════════════════════════════════════════════════════

#[cfg(feature = "libsql")]
mod jobs_isolation {
    use super::*;
    use crate::channels::web::handlers::jobs::{
        jobs_cancel_handler, jobs_prompt_handler, jobs_restart_handler, jobs_summary_handler,
    };
    // SandboxStore methods are accessed through the Database supertrait.

    /// Build a router with job endpoints behind multi-user auth.
    fn jobs_router(state: Arc<GatewayState>, auth: MultiAuthState) -> Router {
        Router::new()
            .route("/api/jobs/summary", get(jobs_summary_handler))
            .route("/api/jobs/{id}/cancel", post(jobs_cancel_handler))
            .route("/api/jobs/{id}/restart", post(jobs_restart_handler))
            .route("/api/jobs/{id}/prompt", post(jobs_prompt_handler))
            .layer(middleware::from_fn_with_state(
                crate::channels::web::auth::CombinedAuthState::from(auth),
                auth_middleware,
            ))
            .with_state(state)
    }

    #[tokio::test]
    async fn test_jobs_summary_scoped_to_user() {
        let (db, _dir) = test_db().await;

        // Insert sandbox jobs for alice and bob.
        let alice_job = make_sandbox_job("alice", "alice task");
        let bob_job = make_sandbox_job("bob", "bob task");
        db.save_sandbox_job(&alice_job).await.unwrap();
        db.save_sandbox_job(&bob_job).await.unwrap();

        let state = build_state(Some(db), None);
        let auth = two_user_auth();
        let app = jobs_router(state, auth);

        // Alice should see 1 job.
        let req = Request::builder()
            .uri("/api/jobs/summary")
            .header("Authorization", "Bearer tok-alice")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body: serde_json::Value =
            serde_json::from_slice(&axum::body::to_bytes(resp.into_body(), 4096).await.unwrap())
                .unwrap();
        assert_eq!(body["total"], 1, "alice should see only her own jobs");

        // Bob should see 1 job.
        let req = Request::builder()
            .uri("/api/jobs/summary")
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body: serde_json::Value =
            serde_json::from_slice(&axum::body::to_bytes(resp.into_body(), 4096).await.unwrap())
                .unwrap();
        assert_eq!(body["total"], 1, "bob should see only his own jobs");
    }

    #[tokio::test]
    async fn test_jobs_restart_rejects_other_user() {
        let (db, _dir) = test_db().await;

        // Insert a failed sandbox job owned by alice.
        let mut alice_job = make_sandbox_job("alice", "alice task");
        alice_job.status = "failed".to_string();
        alice_job.success = Some(false);
        db.save_sandbox_job(&alice_job).await.unwrap();

        let state = build_state(Some(db), None);
        let auth = two_user_auth();
        let app = jobs_router(state, auth);

        // Bob tries to restart alice's job.
        let req = Request::builder()
            .method(Method::POST)
            .uri(format!("/api/jobs/{}/restart", alice_job.id))
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "bob should not be able to restart alice's job"
        );
    }

    #[tokio::test]
    async fn test_jobs_prompt_works_for_agent_jobs() {
        let (db, _dir) = test_db().await;

        // Insert a running sandbox job owned by alice in claude_code mode.
        let mut alice_job = make_sandbox_job("alice", "prompt test");
        alice_job.status = "running".to_string();
        alice_job.success = None;
        alice_job.completed_at = None;
        db.save_sandbox_job(&alice_job).await.unwrap();
        db.update_sandbox_job_mode(alice_job.id, "claude_code")
            .await
            .unwrap();

        let prompt_queue: PromptQueue =
            Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
        let state = build_state(Some(db), Some(prompt_queue.clone()));
        let auth = two_user_auth();
        let app = jobs_router(state, auth);

        // Alice prompts her own job.
        let req = Request::builder()
            .method(Method::POST)
            .uri(format!("/api/jobs/{}/prompt", alice_job.id))
            .header("Authorization", "Bearer tok-alice")
            .header("Content-Type", "application/json")
            .body(Body::from(
                serde_json::to_string(&serde_json::json!({"content": "hello"})).unwrap(),
            ))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "alice should be able to prompt her own job"
        );

        // Verify prompt was enqueued.
        let queue = prompt_queue.lock().await;
        assert!(
            queue.contains_key(&alice_job.id),
            "prompt queue should contain alice's job"
        );
    }

    #[tokio::test]
    async fn test_jobs_prompt_rejects_other_user() {
        let (db, _dir) = test_db().await;

        let mut alice_job = make_sandbox_job("alice", "alice task");
        alice_job.status = "running".to_string();
        alice_job.success = None;
        alice_job.completed_at = None;
        db.save_sandbox_job(&alice_job).await.unwrap();
        db.update_sandbox_job_mode(alice_job.id, "claude_code")
            .await
            .unwrap();

        let prompt_queue: PromptQueue =
            Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
        let state = build_state(Some(db), Some(prompt_queue));
        let auth = two_user_auth();
        let app = jobs_router(state, auth);

        // Bob tries to prompt alice's job.
        let req = Request::builder()
            .method(Method::POST)
            .uri(format!("/api/jobs/{}/prompt", alice_job.id))
            .header("Authorization", "Bearer tok-bob")
            .header("Content-Type", "application/json")
            .body(Body::from(
                serde_json::to_string(&serde_json::json!({"content": "sneaky"})).unwrap(),
            ))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "bob should not be able to prompt alice's job"
        );
    }

    #[tokio::test]
    async fn test_jobs_cancel_rejects_other_user() {
        let (db, _dir) = test_db().await;

        let mut alice_job = make_sandbox_job("alice", "alice running");
        alice_job.status = "running".to_string();
        alice_job.success = None;
        alice_job.completed_at = None;
        db.save_sandbox_job(&alice_job).await.unwrap();

        let state = build_state(Some(db), None);
        let auth = two_user_auth();
        let app = jobs_router(state, auth);

        // Bob tries to cancel alice's job.
        let req = Request::builder()
            .method(Method::POST)
            .uri(format!("/api/jobs/{}/cancel", alice_job.id))
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "bob should not be able to cancel alice's job"
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Routines Isolation Tests
// ═══════════════════════════════════════════════════════════════════════

#[cfg(feature = "libsql")]
mod routines_isolation {
    use super::*;
    use crate::channels::web::handlers::routines::{
        routines_delete_handler, routines_detail_handler, routines_list_handler,
        routines_summary_handler, routines_toggle_handler,
    };
    // RoutineStore methods are accessed through the Database supertrait.

    fn routines_router(state: Arc<GatewayState>, auth: MultiAuthState) -> Router {
        Router::new()
            .route("/api/routines", get(routines_list_handler))
            .route("/api/routines/summary", get(routines_summary_handler))
            .route("/api/routines/{id}", get(routines_detail_handler))
            .route("/api/routines/{id}/toggle", post(routines_toggle_handler))
            .route("/api/routines/{id}", delete(routines_delete_handler))
            .layer(middleware::from_fn_with_state(
                crate::channels::web::auth::CombinedAuthState::from(auth),
                auth_middleware,
            ))
            .with_state(state)
    }

    #[tokio::test]
    async fn test_routines_isolation() {
        let (db, _dir) = test_db().await;

        // Create routines for alice and bob.
        let alice_routine = make_routine("alice", "alice-daily");
        let bob_routine = make_routine("bob", "bob-daily");
        db.create_routine(&alice_routine).await.unwrap();
        db.create_routine(&bob_routine).await.unwrap();

        let state = build_state(Some(db), None);
        let auth = two_user_auth();
        let app = routines_router(state, auth);

        // Alice sees only her routine in the list.
        let req = Request::builder()
            .uri("/api/routines")
            .header("Authorization", "Bearer tok-alice")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body: serde_json::Value =
            serde_json::from_slice(&axum::body::to_bytes(resp.into_body(), 8192).await.unwrap())
                .unwrap();
        let routines = body["routines"].as_array().unwrap();
        assert_eq!(routines.len(), 1, "alice should see only her routines");
        assert_eq!(routines[0]["name"], "alice-daily");

        // Bob sees only his routine.
        let req = Request::builder()
            .uri("/api/routines")
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body: serde_json::Value =
            serde_json::from_slice(&axum::body::to_bytes(resp.into_body(), 8192).await.unwrap())
                .unwrap();
        let routines = body["routines"].as_array().unwrap();
        assert_eq!(routines.len(), 1, "bob should see only his routines");
        assert_eq!(routines[0]["name"], "bob-daily");

        // Bob cannot view alice's routine detail.
        let req = Request::builder()
            .uri(format!("/api/routines/{}", alice_routine.id))
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "bob should not see alice's routine detail"
        );

        // Bob cannot toggle alice's routine.
        let req = Request::builder()
            .method(Method::POST)
            .uri(format!("/api/routines/{}/toggle", alice_routine.id))
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "bob should not toggle alice's routine"
        );

        // Bob cannot delete alice's routine.
        let req = Request::builder()
            .method(Method::DELETE)
            .uri(format!("/api/routines/{}", alice_routine.id))
            .header("Authorization", "Bearer tok-bob")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::NOT_FOUND,
            "bob should not delete alice's routine"
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Handler Auth Enforcement Tests
// ═══════════════════════════════════════════════════════════════════════

mod auth_enforcement {
    use super::*;

    /// Dummy handler that extracts `AuthenticatedUser` — if the auth middleware
    /// rejects the request, this handler is never reached.
    async fn authed_handler(AuthenticatedUser(_user): AuthenticatedUser) -> &'static str {
        "ok"
    }

    /// Build a router with the real auth middleware and dummy handlers at all
    /// the paths we want to verify require authentication.
    fn auth_test_router(auth: MultiAuthState) -> Router {
        let state = build_state(None, None);
        Router::new()
            // Routines
            .route("/api/routines", get(authed_handler))
            .route("/api/routines/summary", get(authed_handler))
            .route("/api/routines/{id}", get(authed_handler))
            .route("/api/routines/{id}/toggle", post(authed_handler))
            .route("/api/routines/{id}", delete(authed_handler))
            // Skills
            .route("/api/skills", get(authed_handler))
            .route("/api/skills/search", post(authed_handler))
            .route("/api/skills/install", post(authed_handler))
            .route("/api/skills/{name}", delete(authed_handler))
            // Logs
            .route("/api/logs/events", get(authed_handler))
            .route("/api/logs/level", get(authed_handler).put(authed_handler))
            // Gateway status
            .route("/api/gateway/status", get(authed_handler))
            .layer(middleware::from_fn_with_state(
                crate::channels::web::auth::CombinedAuthState::from(auth),
                auth_middleware,
            ))
            .with_state(state)
    }

    /// Send a request without auth and assert it returns UNAUTHORIZED.
    async fn assert_requires_auth(app: &Router, method: Method, uri: &str) {
        let req = Request::builder()
            .method(method.clone())
            .uri(uri)
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::UNAUTHORIZED,
            "{} {} should require auth",
            method,
            uri
        );
    }

    /// Send a request with a valid token and assert it succeeds.
    async fn assert_passes_with_token(app: &Router, method: Method, uri: &str, token: &str) {
        let req = Request::builder()
            .method(method.clone())
            .uri(uri)
            .header("Authorization", format!("Bearer {token}"))
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::OK,
            "{} {} should pass with valid token",
            method,
            uri
        );
    }

    #[tokio::test]
    async fn test_routines_handlers_require_auth() {
        let auth = MultiAuthState::single("secret-tok".to_string(), "user".to_string());
        let app = auth_test_router(auth);
        let id = Uuid::new_v4();

        assert_requires_auth(&app, Method::GET, "/api/routines").await;
        assert_requires_auth(&app, Method::GET, "/api/routines/summary").await;
        assert_requires_auth(&app, Method::GET, &format!("/api/routines/{id}")).await;
        assert_requires_auth(&app, Method::POST, &format!("/api/routines/{id}/toggle")).await;
        assert_requires_auth(&app, Method::DELETE, &format!("/api/routines/{id}")).await;
    }

    #[tokio::test]
    async fn test_skills_handlers_require_auth() {
        let auth = MultiAuthState::single("secret-tok".to_string(), "user".to_string());
        let app = auth_test_router(auth);

        assert_requires_auth(&app, Method::GET, "/api/skills").await;
        assert_requires_auth(&app, Method::POST, "/api/skills/search").await;
        assert_requires_auth(&app, Method::POST, "/api/skills/install").await;
        assert_requires_auth(&app, Method::DELETE, "/api/skills/test-skill").await;
    }

    #[tokio::test]
    async fn test_logs_handlers_require_auth() {
        let auth = MultiAuthState::single("secret-tok".to_string(), "user".to_string());
        let app = auth_test_router(auth);

        assert_requires_auth(&app, Method::GET, "/api/logs/events").await;
        assert_requires_auth(&app, Method::GET, "/api/logs/level").await;
        assert_requires_auth(&app, Method::PUT, "/api/logs/level").await;
    }

    #[tokio::test]
    async fn test_gateway_status_requires_auth() {
        let auth = MultiAuthState::single("secret-tok".to_string(), "user".to_string());
        let app = auth_test_router(auth);

        assert_requires_auth(&app, Method::GET, "/api/gateway/status").await;
    }

    #[tokio::test]
    async fn test_valid_token_passes_all_endpoints() {
        let auth = MultiAuthState::single("secret-tok".to_string(), "user".to_string());
        let app = auth_test_router(auth);
        let id = Uuid::new_v4();

        assert_passes_with_token(&app, Method::GET, "/api/routines", "secret-tok").await;
        assert_passes_with_token(&app, Method::GET, "/api/skills", "secret-tok").await;
        assert_passes_with_token(&app, Method::GET, "/api/logs/events", "secret-tok").await;
        assert_passes_with_token(&app, Method::GET, "/api/gateway/status", "secret-tok").await;
        assert_passes_with_token(
            &app,
            Method::GET,
            &format!("/api/routines/{id}"),
            "secret-tok",
        )
        .await;
    }

    #[tokio::test]
    async fn test_wrong_token_rejected_on_all_endpoints() {
        let auth = MultiAuthState::single("secret-tok".to_string(), "user".to_string());
        let app = auth_test_router(auth);

        // Wrong token should be rejected.
        let req = Request::builder()
            .uri("/api/routines")
            .header("Authorization", "Bearer wrong-tok")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);

        let req = Request::builder()
            .uri("/api/gateway/status")
            .header("Authorization", "Bearer wrong-tok")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Admin Endpoint Role Enforcement Tests
// ═══════════════════════════════════════════════════════════════════════

mod admin_role_enforcement {
    use super::*;
    use crate::channels::web::handlers::users::{
        users_activate_handler, users_detail_handler, users_list_handler, users_suspend_handler,
        users_update_handler,
    };
    use axum::routing::patch;

    /// Build a router with admin user endpoints behind multi-user auth.
    /// Uses a member-role token and an admin-role token.
    fn admin_router() -> Router {
        let mut tokens = HashMap::new();
        tokens.insert(
            "tok-admin".to_string(),
            UserIdentity {
                user_id: "admin-user".to_string(),
                role: "admin".to_string(),
                workspace_read_scopes: vec![],
            },
        );
        tokens.insert(
            "tok-member".to_string(),
            UserIdentity {
                user_id: "member-user".to_string(),
                role: "member".to_string(),
                workspace_read_scopes: vec![],
            },
        );
        let auth = MultiAuthState::multi(tokens);
        let state = build_state(None, None);

        Router::new()
            .route("/api/admin/users", get(users_list_handler))
            .route("/api/admin/users/{id}", get(users_detail_handler))
            .route("/api/admin/users/{id}", patch(users_update_handler))
            .route("/api/admin/users/{id}/suspend", post(users_suspend_handler))
            .route(
                "/api/admin/users/{id}/activate",
                post(users_activate_handler),
            )
            .layer(middleware::from_fn_with_state(
                crate::channels::web::auth::CombinedAuthState::from(auth),
                auth_middleware,
            ))
            .with_state(state)
    }

    /// Assert a request returns FORBIDDEN for a member token.
    async fn assert_forbidden_for_member(app: &Router, method: Method, uri: &str) {
        let req = Request::builder()
            .method(method)
            .uri(uri)
            .header("Authorization", "Bearer tok-member")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_eq!(
            resp.status(),
            StatusCode::FORBIDDEN,
            "expected 403 for member on {}",
            uri
        );
    }

    #[tokio::test]
    async fn test_admin_user_endpoints_reject_member_role() {
        let app = admin_router();

        assert_forbidden_for_member(&app, Method::GET, "/api/admin/users").await;
        assert_forbidden_for_member(&app, Method::GET, "/api/admin/users/some-id").await;
        assert_forbidden_for_member(&app, Method::POST, "/api/admin/users/some-id/suspend").await;
        assert_forbidden_for_member(&app, Method::POST, "/api/admin/users/some-id/activate").await;
    }

    #[tokio::test]
    async fn test_admin_user_endpoints_accept_admin_role() {
        let app = admin_router();

        // Admin token should pass auth (will get 503 since no DB, but not 403).
        let req = Request::builder()
            .uri("/api/admin/users")
            .header("Authorization", "Bearer tok-admin")
            .body(Body::empty())
            .unwrap();
        let resp = app.clone().oneshot(req).await.unwrap();
        assert_ne!(
            resp.status(),
            StatusCode::FORBIDDEN,
            "admin should not get 403"
        );
    }
}

// ═══════════════════════════════════════════════════════════════════════
// DbAuthenticator Cache Bounded Tests
// ═══════════════════════════════════════════════════════════════════════

mod db_auth_cache {
    use super::*;
    use std::time::Instant;

    #[tokio::test]
    async fn test_cache_bounded_by_max_entries() {
        // Access the internal cache and verify LRU eviction.
        // We can't easily test through `authenticate()` since it hits the DB,
        // so we test the LRU cache directly.
        let cap = std::num::NonZeroUsize::new(4).unwrap(); // safety: test-only, 4 is non-zero
        let cache: lru::LruCache<[u8; 32], (UserIdentity, Instant)> = lru::LruCache::new(cap);
        let cache = Arc::new(tokio::sync::RwLock::new(cache));

        {
            let mut c = cache.write().await;
            for i in 0..10u8 {
                let mut hash = [0u8; 32];
                hash[0] = i;
                c.put(
                    hash,
                    (
                        UserIdentity {
                            user_id: format!("user-{i}"),
                            role: "member".to_string(),
                            workspace_read_scopes: vec![],
                        },
                        Instant::now(),
                    ),
                );
            }
            // Cache must be bounded at capacity, not grown to 10.
            assert_eq!(c.len(), 4, "cache should be bounded to capacity"); // safety: test assertion
        }
    }
}