udb 0.2.1

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
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
use super::*;
use crate::generation::{CatalogManifest, ManifestColumn, ManifestTable};
use crate::planning::broker::{DeletePlanRequest, build_delete_plan};
use crate::runtime::config::UdbConfig;
use crate::runtime::core::DataBrokerRuntime;
use serde_json::json;
use std::sync::Arc;

fn install_test_security() {
    crate::runtime::security::SecurityConfig::install_global(
        crate::runtime::security::SecurityConfig {
            tls_required: false,
            service_identity_required: false,
            mtls_required: false,
            allow_header_scopes: true,
            ..crate::runtime::security::SecurityConfig::default()
        },
    );
}

fn test_manifest() -> CatalogManifest {
    let col_id = ManifestColumn {
        field_name: "id".to_string(),
        column_name: "id".to_string(),
        proto_type: "string".to_string(),
        sql_type: "TEXT".to_string(),
        is_primary: true,
        ..ManifestColumn::default()
    };
    let col_tenant = ManifestColumn {
        field_name: "tenant_id".to_string(),
        column_name: "tenant_id".to_string(),
        proto_type: "string".to_string(),
        sql_type: "TEXT".to_string(),
        not_null: true,
        ..ManifestColumn::default()
    };
    let table = ManifestTable {
        message_name: "Payment".to_string(),
        schema: "payments".to_string(),
        table: "payments".to_string(),
        columns: vec![col_id, col_tenant],
        primary_key: vec!["id".to_string()],
        ..ManifestTable::default()
    };
    CatalogManifest {
        tables: vec![table],
        ..CatalogManifest::default()
    }
}

fn ready_service() -> DataBrokerService {
    install_test_security();
    let svc = DataBrokerService::with_runtime(test_manifest(), DataBrokerRuntime::planning_only());
    if let Ok(mut s) = svc.lifecycle_state.write() {
        *s = FsmState::Completed;
    }
    svc
}

#[test]
fn descriptor_set_exposes_databroker_reflection_surface() {
    let descriptor =
        <prost_types::FileDescriptorSet as prost::Message>::decode(UDB_FILE_DESCRIPTOR_SET)
            .expect("descriptor set should decode");
    assert!(descriptor.file.iter().any(|file| {
        file.package.as_deref() == Some("udb.services.v1")
            || file.package.as_deref() == Some("lifeplus.udb.services.v1")
    }));

    let service = descriptor
        .file
        .iter()
        .flat_map(|file| file.service.iter())
        .find(|service| service.name.as_deref() == Some("DataBroker"))
        .expect("DataBroker service should be in descriptor set");
    let methods = service
        .method
        .iter()
        .filter_map(|method| method.name.as_deref())
        .collect::<std::collections::BTreeSet<_>>();

    assert!(methods.contains("Select"));
    assert!(methods.contains("LookupMessageSchema"));
    assert!(methods.contains("GetHealthReport"));
}

#[tokio::test]
async fn service_runtime_snapshot_is_shared_across_clones() {
    let svc = DataBrokerService::with_runtime(test_manifest(), DataBrokerRuntime::planning_only());
    let clone = svc.clone();
    let next = DataBrokerRuntime::from_config(UdbConfig {
        default_limit: 321,
        ..UdbConfig::default()
    })
    .await;

    svc.runtime.store(Arc::new(next));

    assert_eq!(clone.runtime_snapshot().config().default_limit, 321);
}

#[test]
fn catalog_response_headers_carry_version_and_consistency() {
    let svc = ready_service();
    let response = svc.with_catalog_response_headers(
        Response::new(()),
        &crate::RequestContext {
            project_id: "default".to_string(),
            consistency: "read_your_writes".to_string(),
            primary_read: false,
            ..Default::default()
        },
    );
    let metadata = response.metadata();
    assert!(metadata.contains_key("x-udb-project-id"));
    assert_eq!(
        metadata
            .get("x-udb-consistency-mode")
            .and_then(|value| value.to_str().ok()),
        Some("read_your_writes")
    );
    assert_eq!(
        metadata
            .get("x-udb-primary-read")
            .and_then(|value| value.to_str().ok()),
        Some("false")
    );
}

#[test]
fn catalog_response_headers_report_read_fence_state() {
    let svc = ready_service();
    let fence = crate::runtime::consistency::ReadFence {
        min_outbox_lsn: "0/100".to_string(),
        max_wait_ms: 250,
        ..Default::default()
    };
    let response = svc.with_catalog_response_headers(
        Response::new(()),
        &crate::RequestContext {
            consistency: "read_your_writes".to_string(),
            read_fence_json: serde_json::to_string(&fence).unwrap(),
            ..Default::default()
        },
    );
    let metadata = response.metadata();
    assert_eq!(
        metadata
            .get("x-udb-read-fence-present")
            .and_then(|value| value.to_str().ok()),
        Some("true")
    );
    assert_eq!(
        metadata
            .get("x-udb-read-fence-honored")
            .and_then(|value| value.to_str().ok()),
        Some("true")
    );
}

#[tokio::test]
async fn mutation_response_headers_attach_write_receipt() {
    let svc = ready_service();
    let response = svc
        .with_mutation_response_headers(
            MutationResponse {
                mutation_id: "m1".to_string(),
                ..Default::default()
            },
            &crate::RequestContext::default(),
        )
        .await;
    let receipt_json = &response.get_ref().write_receipt_json;
    let receipt: crate::runtime::consistency::WriteReceipt =
        serde_json::from_str(receipt_json).unwrap();
    assert_eq!(
        receipt.manifest_checksum,
        svc.catalog.active().metadata.checksum
    );
    assert!(
        response
            .metadata()
            .get("x-udb-write-receipt")
            .and_then(|value| value.to_str().ok())
            .is_some()
    );
}

// ── Delete planning ───────────────────────────────────────────────────────

#[test]
fn delete_plan_rejects_unknown_message_type() {
    let manifest = test_manifest();
    let req = DeletePlanRequest {
        message_type: "NonExistent".to_string(),
        filter: json!({"id": {"eq": "x"}}),
        context: crate::RequestContext {
            tenant_id: "t1".to_string(),
            ..Default::default()
        },
    };
    let plan = build_delete_plan(&manifest, &req);
    assert!(
        !plan.errors.is_empty(),
        "expected error for unknown message_type"
    );
    assert!(
        plan.errors[0].contains("unknown message_type"),
        "got: {:?}",
        plan.errors
    );
}

#[test]
fn delete_plan_requires_filter_predicate() {
    let manifest = test_manifest();
    let req = DeletePlanRequest {
        message_type: "Payment".to_string(),
        filter: json!({}),
        context: crate::RequestContext {
            tenant_id: "t1".to_string(),
            ..Default::default()
        },
    };
    let plan = build_delete_plan(&manifest, &req);
    assert!(
        !plan.errors.is_empty(),
        "expected error for empty filter; got: {:?}",
        plan.errors
    );
}

#[test]
fn delete_plan_generates_valid_sql() {
    let manifest = test_manifest();
    // validate_write_context requires purpose + udb:write scope;
    // tenant isolation requires a filter on tenant_id.
    // Use $eq operator ("eq" is not a recognised SQL operator key).
    let req = DeletePlanRequest {
        message_type: "Payment".to_string(),
        filter: json!({"id": {"$eq": "abc"}, "tenant_id": {"$eq": "t1"}}),
        context: crate::RequestContext {
            tenant_id: "t1".to_string(),
            purpose: "test".to_string(),
            scopes: vec!["udb:write".to_string()],
            ..Default::default()
        },
    };
    let plan = build_delete_plan(&manifest, &req);
    assert!(
        plan.errors.is_empty(),
        "unexpected errors: {:?}",
        plan.errors
    );
    assert!(
        plan.sql.to_ascii_uppercase().starts_with("DELETE FROM"),
        "sql: {}",
        plan.sql
    );
    assert!(plan.sql.contains("payments"), "sql: {}", plan.sql);
}

// ── Resource admin: unknown backend → INVALID_ARGUMENT ───────────────────

#[tokio::test]
async fn ensure_resource_unknown_backend() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt
        .ensure_resource_backend("totally_nonexistent_backend", "ks", "{}")
        .await
        .unwrap_err();
    assert_eq!(err.code(), tonic::Code::InvalidArgument);
    assert!(
        err.message().contains("totally_nonexistent_backend"),
        "got: {}",
        err.message()
    );
}

#[tokio::test]
async fn drop_resource_unknown_backend() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt
        .drop_resource_backend("totally_nonexistent_backend", "ks")
        .await
        .unwrap_err();
    assert_eq!(err.code(), tonic::Code::InvalidArgument);
}

#[tokio::test]
async fn list_resources_unknown_backend() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt
        .list_resources_backend("totally_nonexistent_backend")
        .await
        .unwrap_err();
    assert_eq!(err.code(), tonic::Code::InvalidArgument);
}

// ── Resource admin: unconfigured backend → FAILED_PRECONDITION ───────────

#[tokio::test]
async fn ensure_resource_mongodb_unconfigured() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt
        .ensure_resource_backend("mongodb", "col", "{}")
        .await
        .unwrap_err();
    assert_eq!(err.code(), tonic::Code::FailedPrecondition);
    assert!(
        err.message().contains("mongodb not configured"),
        "got: {}",
        err.message()
    );
}

#[tokio::test]
async fn drop_resource_neo4j_unconfigured() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt.drop_resource_backend("neo4j", "lbl").await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::FailedPrecondition);
    assert!(
        err.message().contains("neo4j not configured"),
        "got: {}",
        err.message()
    );
}

#[tokio::test]
async fn list_resources_clickhouse_unconfigured() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt.list_resources_backend("clickhouse").await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::FailedPrecondition);
    assert!(
        err.message().contains("clickhouse not configured"),
        "got: {}",
        err.message()
    );
}

#[tokio::test]
async fn list_resources_s3_unconfigured() {
    let rt = DataBrokerRuntime::planning_only();
    let err = rt.list_resources_backend("s3").await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::FailedPrecondition);
}

// ── GetCapabilities: supported_rpcs completeness ──────────────────────────

fn capabilities_request_with_tenant() -> Request<CapabilitiesRequest> {
    // Safety: test-only; no concurrent env mutation in this test module.
    unsafe {
        std::env::set_var("UDB_MTLS_REQUIRED", "false");
        std::env::set_var("UDB_ALLOW_HEADER_SCOPES", "1");
    }
    let mut req = Request::new(CapabilitiesRequest {
        context: None,
        project_id: String::new(),
    });
    req.metadata_mut()
        .insert("x-tenant-id", "test-tenant".parse().unwrap());
    req.metadata_mut()
        .insert("x-purpose", "admin".parse().unwrap());
    req.metadata_mut()
        .insert("x-scopes", "udb:admin".parse().unwrap());
    req
}

/// Like `ready_service` but with ABAC default-allow, so tests that exercise the
/// full RPC path (rather than auth denial) can reach the handler body.
fn open_service() -> DataBrokerService {
    install_test_security();
    let lifecycle = Arc::new(RwLock::new(FsmState::Completed));
    let policies = Arc::new(RwLock::new(Vec::new()));
    let metrics = Arc::new(PrometheusMetrics::new().expect("metrics"));
    DataBrokerService::with_runtime_and_state(
        test_manifest(),
        DataBrokerRuntime::planning_only(),
        lifecycle,
        policies,
        metrics,
        None,
        true, // abac_default_allow
    )
}

#[tokio::test]
async fn get_capabilities_includes_resource_admin_rpcs() {
    let svc = open_service();
    let resp = svc
        .get_capabilities(capabilities_request_with_tenant())
        .await
        .unwrap();
    let rpcs = &resp.get_ref().supported_rpcs;
    for name in [
        "EnsureResource",
        "DropResource",
        "ListResources",
        "GenericDispatch",
    ] {
        assert!(
            rpcs.contains(&name.to_string()),
            "missing '{name}' in supported_rpcs"
        );
    }
}

#[tokio::test]
async fn get_capabilities_includes_cdc_rpcs() {
    let svc = open_service();
    let resp = svc
        .get_capabilities(capabilities_request_with_tenant())
        .await
        .unwrap();
    let rpcs = &resp.get_ref().supported_rpcs;
    for name in ["PauseCdc", "ResumeCdc", "GetCdcStatus", "StepDownCdcLeader"] {
        assert!(
            rpcs.contains(&name.to_string()),
            "missing '{name}' in supported_rpcs"
        );
    }
}

#[tokio::test]
async fn get_capabilities_includes_policy_rpcs() {
    let svc = open_service();
    let resp = svc
        .get_capabilities(capabilities_request_with_tenant())
        .await
        .unwrap();
    let rpcs = &resp.get_ref().supported_rpcs;
    for name in [
        "ListPolicies",
        "PutPolicy",
        "DeletePolicy",
        "ReloadPolicies",
        "LintPolicies",
    ] {
        assert!(
            rpcs.contains(&name.to_string()),
            "missing '{name}' in supported_rpcs"
        );
    }
}

#[tokio::test]
async fn get_capabilities_includes_schema_registry_rpcs() {
    let svc = open_service();
    let resp = svc
        .get_capabilities(capabilities_request_with_tenant())
        .await
        .unwrap();
    let rpcs = &resp.get_ref().supported_rpcs;
    for name in ["LookupMessageSchema", "ListMessageSchemas"] {
        assert!(
            rpcs.contains(&name.to_string()),
            "missing '{name}' in supported_rpcs"
        );
    }
}

#[tokio::test]
async fn lookup_message_schema_returns_descriptor() {
    let svc = open_service();
    let mut req = Request::new(MessageSchemaLookupRequest {
        context: None,
        project_id: String::new(),
        message_type: "Payment".to_string(),
        client_catalog_version: String::new(),
    });
    req.metadata_mut()
        .insert("x-tenant-id", "test-tenant".parse().unwrap());
    req.metadata_mut()
        .insert("x-purpose", "schema".parse().unwrap());
    req.metadata_mut()
        .insert("x-scopes", "udb:admin".parse().unwrap());

    let resp = svc.lookup_message_schema(req).await.unwrap();
    let descriptor = resp
        .get_ref()
        .schema
        .as_ref()
        .expect("descriptor should be present");
    assert_eq!(descriptor.message_type, "Payment");
    assert_eq!(descriptor.table, "payments");
    assert!(descriptor.fields.iter().any(|field| field.name == "id"));
}

#[tokio::test]
async fn lookup_message_schema_rejects_cross_project_non_admin() {
    let svc = open_service();
    let mut req = Request::new(MessageSchemaLookupRequest {
        context: None,
        project_id: "other-project".to_string(),
        message_type: "Payment".to_string(),
        client_catalog_version: String::new(),
    });
    req.metadata_mut()
        .insert("x-tenant-id", "test-tenant".parse().unwrap());
    req.metadata_mut()
        .insert("x-project-id", "bound-project".parse().unwrap());
    req.metadata_mut()
        .insert("x-purpose", "schema".parse().unwrap());
    req.metadata_mut()
        .insert("x-scopes", "udb:read".parse().unwrap());

    let err = svc.lookup_message_schema(req).await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::PermissionDenied);
}

#[tokio::test]
async fn list_message_schemas_returns_active_messages() {
    let svc = open_service();
    let mut req = Request::new(MessageSchemaListRequest {
        context: None,
        project_id: String::new(),
        client_catalog_version: String::new(),
    });
    req.metadata_mut()
        .insert("x-tenant-id", "test-tenant".parse().unwrap());
    req.metadata_mut()
        .insert("x-purpose", "schema".parse().unwrap());
    req.metadata_mut()
        .insert("x-scopes", "udb:admin".parse().unwrap());

    let resp = svc.list_message_schemas(req).await.unwrap();
    assert!(
        resp.get_ref()
            .message_types
            .contains(&"Payment".to_string()),
        "active message list should contain Payment"
    );
}

#[tokio::test]
async fn list_message_schemas_rejects_cross_project_non_admin() {
    let svc = open_service();
    let mut req = Request::new(MessageSchemaListRequest {
        context: None,
        project_id: "other-project".to_string(),
        client_catalog_version: String::new(),
    });
    req.metadata_mut()
        .insert("x-tenant-id", "test-tenant".parse().unwrap());
    req.metadata_mut()
        .insert("x-project-id", "bound-project".parse().unwrap());
    req.metadata_mut()
        .insert("x-purpose", "schema".parse().unwrap());
    req.metadata_mut()
        .insert("x-scopes", "udb:read".parse().unwrap());

    let err = svc.list_message_schemas(req).await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::PermissionDenied);
}

#[tokio::test]
async fn get_capabilities_includes_backend_capability_matrix() {
    let svc = open_service();
    let resp = svc
        .get_capabilities(capabilities_request_with_tenant())
        .await
        .unwrap();
    let matrix = &resp.get_ref().backend_capabilities;
    // C9 complete: every backend in the enum is now wired. No more
    // metadata-only exclusions to assert against.
    let _ = matrix;
    #[cfg(feature = "redis")]
    {
        let redis = matrix
            .iter()
            .find(|entry| entry.backend == "redis")
            .expect("redis capability entry");
        assert!(redis.operations.contains(&"query".to_string()));
        assert!(redis.operations.contains(&"mutate".to_string()));
        assert_eq!(redis.unsupported_error_code, "UDB_UNSUPPORTED_OPERATION");
    }
}

#[test]
fn pagination_helpers_bound_limit_and_emit_next_token() {
    assert_eq!(bounded_list_limit(0), 100);
    assert_eq!(bounded_list_limit(5000), 1000);
    assert_eq!(page_offset("25"), 25);
    assert_eq!(page_offset("bad"), 0);
    assert_eq!(next_page_token(20, 10, 10), "30");
    assert_eq!(next_page_token(20, 10, 3), "");
}

#[test]
fn portal_permissions_distinguish_viewer_and_operator() {
    let svc = ready_service();
    let viewer = SecurityContext {
        scopes: vec!["udb:portal:viewer".to_string()],
        ..SecurityContext::default()
    };
    assert!(
        svc.require_portal_permission(&viewer, "GetAdminSummary", false)
            .is_ok()
    );
    assert_eq!(
        svc.require_portal_permission(&viewer, "RetrySagaCompensation", true)
            .unwrap_err()
            .code(),
        tonic::Code::PermissionDenied
    );

    let operator = SecurityContext {
        scopes: vec!["udb:portal:operator".to_string()],
        ..SecurityContext::default()
    };
    assert!(
        svc.require_portal_permission(&operator, "RetrySagaCompensation", true)
            .is_ok()
    );
}

// ── Broker v2 authz gate (UDB_AUTHZ_V2) — items 124-131 ──────────────────
// These drive `DataBrokerService::authorize()` with the v2 decision engine
// forced on per-instance (`set_authz_v2_override`), so the broker-level
// allow/deny path is exercised deterministically — no live Postgres, no gRPC
// server. The env flag `UDB_AUTHZ_V2` is a cached `OnceLock` and cannot vary
// per test, which is exactly why the per-instance override exists. The broker
// passes the raw RPC name (`Select`/`Upsert`/`PutPolicy`) as the operation, so
// a matching policy carries the same operation string.

fn v2_service(policies: Vec<crate::runtime::security::AbacPolicy>) -> DataBrokerService {
    let mut svc = ready_service(); // abac_default_allow = false
    if let Ok(mut p) = svc.abac_policies.write() {
        *p = policies;
    }
    svc.set_authz_v2_override(true);
    svc
}

fn billing_ctx(scopes: &[&str]) -> SecurityContext {
    SecurityContext {
        tenant_id: "acme".to_string(),
        purpose: "billing".to_string(),
        service_identity: "svc:billing".to_string(),
        scopes: scopes.iter().map(|s| s.to_string()).collect(),
        ..SecurityContext::default()
    }
}

fn allow_policy(operation: &str, scope: &str) -> crate::runtime::security::AbacPolicy {
    crate::runtime::security::AbacPolicy {
        effect: crate::runtime::security::PolicyEffect::Allow,
        service_identity: "svc:billing".to_string(),
        tenant_id: "*".to_string(),
        purpose: "billing".to_string(),
        message_type: "*".to_string(),
        operation: operation.to_string(),
        required_scope: scope.to_string(),
    }
}

#[tokio::test]
async fn broker_v2_select_allowed_with_matching_policy() {
    // 124: a Select policy granting the caller's scope/purpose → authorized.
    let svc = v2_service(vec![allow_policy("Select", "udb:read")]);
    let ctx = billing_ctx(&["udb:read"]);
    assert!(
        svc.authorize(&ctx, "Payment", "Select").await.is_ok(),
        "matching v2 policy must authorize Select"
    );
}

#[tokio::test]
async fn broker_v2_select_denied_without_policy() {
    // 125: no policy + deny-by-default → PermissionDenied.
    let svc = v2_service(vec![]);
    let ctx = billing_ctx(&["udb:read"]);
    let err = svc.authorize(&ctx, "Payment", "Select").await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::PermissionDenied);
}

#[tokio::test]
async fn broker_v2_upsert_allowed_with_matching_policy() {
    // 126: an Upsert policy authorizes the matching write.
    let svc = v2_service(vec![allow_policy("Upsert", "udb:write")]);
    let ctx = billing_ctx(&["udb:write"]);
    assert!(
        svc.authorize(&ctx, "Payment", "Upsert").await.is_ok(),
        "matching v2 policy must authorize Upsert"
    );
}

#[tokio::test]
async fn broker_v2_admin_rpc_denied_without_grant() {
    // 127: a read grant does not authorize an admin mutation under v2 — the
    // operation selector must match, so PutPolicy is denied.
    let svc = v2_service(vec![allow_policy("Select", "udb:read")]);
    let ctx = billing_ctx(&["udb:read", "udb:admin"]);
    let err = svc
        .authorize(&ctx, "Policy", "PutPolicy")
        .await
        .unwrap_err();
    assert_eq!(err.code(), tonic::Code::PermissionDenied);
}

#[tokio::test]
async fn broker_v2_external_roles_alone_do_not_bypass_policy() {
    // 128: a caller carrying external IdP "roles" as scopes but with no UDB
    // policy granting the operation is denied. External identity is mapped, but
    // UDB authorization is never bypassed by the upstream roles alone.
    let svc = v2_service(vec![]);
    let ctx = billing_ctx(&["role:admin", "role:billing-manager"]);
    let err = svc.authorize(&ctx, "Payment", "Select").await.unwrap_err();
    assert_eq!(err.code(), tonic::Code::PermissionDenied);
}

#[tokio::test]
async fn broker_v2_policy_reload_updates_decisions() {
    // 131: hot-reloading the shared ABAC store changes the decision without
    // rebuilding the service.
    let svc = v2_service(vec![]);
    let ctx = billing_ctx(&["udb:read"]);
    assert_eq!(
        svc.authorize(&ctx, "Payment", "Select")
            .await
            .unwrap_err()
            .code(),
        tonic::Code::PermissionDenied,
        "deny-by-default before any policy is loaded"
    );
    svc.abac_policies
        .write()
        .unwrap()
        .push(allow_policy("Select", "udb:read"));
    assert!(
        svc.authorize(&ctx, "Payment", "Select").await.is_ok(),
        "the reloaded grant must take effect on the next decision"
    );
}

#[tokio::test]
async fn broker_v2_matches_legacy_abac_decisions() {
    // 132 gate: the v2 decision engine must agree with the legacy `evaluate_abac`
    // path on allow/deny for the same inputs, so flipping the broker default to
    // v2 is safe. We run an identical matrix through both paths (toggled by the
    // per-instance override) and assert the outcomes match.
    let policies = vec![
        allow_policy("Select", "udb:read"),
        crate::runtime::security::AbacPolicy {
            effect: crate::runtime::security::PolicyEffect::Deny,
            service_identity: "svc:billing".to_string(),
            tenant_id: "*".to_string(),
            purpose: "billing".to_string(),
            message_type: "*".to_string(),
            operation: "Delete".to_string(),
            required_scope: String::new(),
        },
    ];
    let cases = [
        (billing_ctx(&["udb:read"]), "Payment", "Select"), // matching allow
        (billing_ctx(&[]), "Payment", "Select"),           // missing required scope
        (billing_ctx(&["udb:read"]), "Payment", "Delete"), // explicit deny wins
        (billing_ctx(&["udb:write"]), "Payment", "Upsert"), // no matching policy
    ];
    for (ctx, msg, op) in cases {
        let mut legacy = v2_service(policies.clone());
        legacy.set_authz_v2_override(false);
        let legacy_ok = legacy.authorize(&ctx, msg, op).await.is_ok();

        let v2 = v2_service(policies.clone()); // override = true
        let v2_ok = v2.authorize(&ctx, msg, op).await.is_ok();

        assert_eq!(
            legacy_ok, v2_ok,
            "v2 and legacy ABAC disagree for {msg}/{op} (legacy={legacy_ok}, v2={v2_ok})"
        );
    }
}

// ── Authorization: deny-by-default scope enforcement ─────────────────────

#[tokio::test]
async fn ensure_resource_handler_denied_without_policy() {
    let svc = ready_service(); // abac_default_allow = false, no policies
    let req = Request::new(ResourceAdminRequest {
        context: None,
        backend: "mongodb".to_string(),
        resource_name: "col".to_string(),
        spec_json: "{}".to_string(),
        idempotency_key: String::new(),
        dry_run: false,
    });
    let err = svc.ensure_resource(req).await.unwrap_err();
    // Without credentials: Unauthenticated (missing tenant_id) or PermissionDenied (ABAC deny)
    assert!(
        err.code() == tonic::Code::PermissionDenied
            || err.code() == tonic::Code::Unavailable
            || err.code() == tonic::Code::Unauthenticated,
        "expected auth denial, got {:?}",
        err.code()
    );
}

#[tokio::test]
async fn drop_resource_handler_denied_without_policy() {
    let svc = ready_service();
    let req = Request::new(ResourceAdminRequest {
        context: None,
        backend: "neo4j".to_string(),
        resource_name: "label".to_string(),
        spec_json: String::new(),
        idempotency_key: String::new(),
        dry_run: false,
    });
    let err = svc.drop_resource(req).await.unwrap_err();
    assert!(
        err.code() == tonic::Code::PermissionDenied
            || err.code() == tonic::Code::Unavailable
            || err.code() == tonic::Code::Unauthenticated,
        "expected auth denial, got {:?}",
        err.code()
    );
}

#[tokio::test]
async fn list_resources_handler_denied_without_policy() {
    let svc = ready_service();
    let req = Request::new(ResourceAdminRequest {
        context: None,
        backend: "clickhouse".to_string(),
        resource_name: String::new(),
        spec_json: String::new(),
        idempotency_key: String::new(),
        dry_run: false,
    });
    let err = svc.list_resources(req).await.unwrap_err();
    assert!(
        err.code() == tonic::Code::PermissionDenied
            || err.code() == tonic::Code::Unavailable
            || err.code() == tonic::Code::Unauthenticated,
        "expected auth denial, got {:?}",
        err.code()
    );
}