lenso-organization-postgres-plugin 0.3.0

PostgreSQL-backed Organization Plugin for Lenso vNext.
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
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
//! PostgreSQL-backed Organization behavior for Lenso vNext.

mod operator;
mod schema;

use std::{cell::RefCell, fmt, fmt::Write as _, rc::Rc, time::Duration};

use lenso_capability_organization_admin::{
    CreateOrganizationError, CreateOrganizationRequest, CreateOrganizationResponse,
    OrganizationAdmin, OrganizationAdminEndpoint, OrganizationAdminProvider,
};
use lenso_capability_organization_directory::{
    GetOrganizationError, GetOrganizationRequest, GetOrganizationResponse, OrganizationDirectory,
    OrganizationDirectoryEndpoint, OrganizationDirectoryProvider,
};
use lenso_capability_organization_membership::{
    CheckMembershipError, CheckMembershipRequest, CheckMembershipResponse, OrganizationMembership,
    OrganizationMembershipEndpoint, OrganizationMembershipProvider,
};
use lenso_capability_organization_membership_admin::{
    AddMemberError, AddMemberRequest, AddMemberResponse, OrganizationMembershipAdminAddMember,
    OrganizationMembershipAdminEndpoint, OrganizationMembershipAdminProvider,
    OrganizationMembershipAdminRemoveMember, RemoveMemberError, RemoveMemberRequest,
    RemoveMemberResponse,
};
use lenso_capability_secrets::{ResolveRequest, SecretsClient, SecretsInvocationError};
use lenso_kernel::{
    DeactivateContext, InvocationContext, NativeRequestEndpoint, NativeRequestFuture, PluginFuture,
    PluginLifecycle, PrepareContext, RuntimeFailure,
};
use lenso_native_adapter::{NativePluginFactory, NativePluginFactoryContext, NativePluginInstance};
use lenso_postgres_kit::OwnedPostgres;
use serde::{Deserialize, Serialize};
use sqlx::Row;
use thiserror::Error;
use zeroize::Zeroizing;

use crate::schema::schema_plan;

pub use operator::{OrganizationOperator, OrganizationOperatorError};

pub const PACKAGE_ID: &str = "lenso.organization.postgres";
pub const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
const DEPENDENCY_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct OrganizationConfig {
    schema: String,
    database_url_secret: String,
    #[serde(default)]
    admin_callers: Vec<String>,
    #[serde(default)]
    directory_callers: Vec<String>,
    #[serde(default)]
    membership_admin_callers: Vec<String>,
}

impl OrganizationConfig {
    pub fn new(
        schema: impl Into<String>,
        database_url_secret: impl Into<String>,
        admin_callers: Vec<String>,
    ) -> Result<Self, OrganizationConfigError> {
        let value = Self {
            schema: schema.into(),
            database_url_secret: database_url_secret.into(),
            admin_callers,
            directory_callers: Vec::new(),
            membership_admin_callers: Vec::new(),
        };
        value.validate()?;
        Ok(value)
    }

    pub fn with_membership_admin_callers(
        mut self,
        membership_admin_callers: Vec<String>,
    ) -> Result<Self, OrganizationConfigError> {
        self.membership_admin_callers = membership_admin_callers;
        self.validate()?;
        Ok(self)
    }

    pub fn with_directory_callers(
        mut self,
        directory_callers: Vec<String>,
    ) -> Result<Self, OrganizationConfigError> {
        self.directory_callers = directory_callers;
        self.validate()?;
        Ok(self)
    }

    fn validate(&self) -> Result<(), OrganizationConfigError> {
        schema_plan(self.schema.clone()).map_err(|_| OrganizationConfigError::InvalidSchema)?;
        if !valid_secret_reference(&self.database_url_secret) {
            return Err(OrganizationConfigError::InvalidSecretReference);
        }
        if self.admin_callers.is_empty()
            || self
                .admin_callers
                .iter()
                .any(|value| !valid_name(value, 256))
        {
            return Err(OrganizationConfigError::InvalidAdminCallers);
        }
        if self
            .directory_callers
            .iter()
            .any(|value| !valid_name(value, 256))
        {
            return Err(OrganizationConfigError::InvalidDirectoryCallers);
        }
        if self
            .membership_admin_callers
            .iter()
            .any(|value| !valid_name(value, 256))
        {
            return Err(OrganizationConfigError::InvalidMembershipAdminCallers);
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum OrganizationConfigError {
    #[error("invalid owned PostgreSQL schema")]
    InvalidSchema,
    #[error("invalid database URL secret reference")]
    InvalidSecretReference,
    #[error("at least one valid Organization Admin caller is required")]
    InvalidAdminCallers,
    #[error("every Organization Directory caller must be a valid Instance key")]
    InvalidDirectoryCallers,
    #[error("every Organization Membership Admin caller must be a valid Instance key")]
    InvalidMembershipAdminCallers,
}

#[derive(Clone, Copy, Debug, Default)]
pub struct OrganizationFactory;

impl NativePluginFactory for OrganizationFactory {
    fn package_id(&self) -> &'static str {
        PACKAGE_ID
    }

    fn package_version(&self) -> &'static str {
        PACKAGE_VERSION
    }

    fn instantiate(
        &self,
        context: NativePluginFactoryContext<'_>,
    ) -> Result<NativePluginInstance, RuntimeFailure> {
        if context.entrypoint() != "default" {
            return Err(RuntimeFailure::InvalidResolvedPlan {
                detail: format!(
                    "unsupported Organization entrypoint `{}`",
                    context.entrypoint()
                ),
            });
        }
        let config: OrganizationConfig =
            serde_json::from_str(context.configuration()).map_err(|error| {
                RuntimeFailure::InvalidResolvedPlan {
                    detail: format!("Organization configuration is invalid: {error}"),
                }
            })?;
        config
            .validate()
            .map_err(|error| RuntimeFailure::InvalidResolvedPlan {
                detail: error.to_string(),
            })?;

        let state = Rc::new(RefCell::new(None));
        let provider = OrganizationProvider {
            state: state.clone(),
            admin_callers: config.admin_callers.clone(),
            directory_callers: config.directory_callers.clone(),
            membership_admin_callers: config.membership_admin_callers.clone(),
        };
        let endpoints: Vec<Rc<dyn NativeRequestEndpoint>> = vec![
            Rc::new(OrganizationAdminEndpoint::new(provider.clone())),
            Rc::new(OrganizationDirectoryEndpoint::new(provider.clone())),
            Rc::new(OrganizationMembershipEndpoint::new(provider.clone())),
            Rc::new(OrganizationMembershipAdminEndpoint::new(provider)),
        ];
        Ok(NativePluginInstance::with_lifecycle(
            endpoints,
            OrganizationLifecycle { config, state },
        ))
    }
}

#[derive(Clone)]
struct PreparedOrganization {
    postgres: OwnedPostgres,
}

impl fmt::Debug for PreparedOrganization {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PreparedOrganization")
            .field("schema", &self.postgres.schema())
            .finish()
    }
}

#[derive(Clone)]
struct OrganizationProvider {
    state: Rc<RefCell<Option<PreparedOrganization>>>,
    admin_callers: Vec<String>,
    directory_callers: Vec<String>,
    membership_admin_callers: Vec<String>,
}

impl fmt::Debug for OrganizationProvider {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("OrganizationProvider")
            .field("prepared", &self.state.borrow().is_some())
            .field("admin_caller_count", &self.admin_callers.len())
            .field("directory_caller_count", &self.directory_callers.len())
            .field(
                "membership_admin_caller_count",
                &self.membership_admin_callers.len(),
            )
            .finish()
    }
}

impl OrganizationProvider {
    fn prepared(&self) -> Result<PreparedOrganization, RuntimeFailure> {
        self.state
            .borrow()
            .clone()
            .ok_or(RuntimeFailure::PluginFailure {
                detail: "Organization Plugin is not prepared".to_owned(),
            })
    }

    fn authorized_admin_caller<'a>(&self, context: &'a InvocationContext) -> Option<&'a str> {
        context
            .caller_instance()
            .filter(|caller| self.admin_callers.iter().any(|allowed| allowed == *caller))
    }

    fn authorized_membership_admin_caller<'a>(
        &self,
        context: &'a InvocationContext,
    ) -> Option<&'a str> {
        context.caller_instance().filter(|caller| {
            self.membership_admin_callers
                .iter()
                .any(|allowed| allowed == *caller)
        })
    }

    fn authorized_directory_caller<'a>(&self, context: &'a InvocationContext) -> Option<&'a str> {
        context.caller_instance().filter(|caller| {
            self.directory_callers
                .iter()
                .any(|allowed| allowed == *caller)
        })
    }
}

impl OrganizationAdminProvider for OrganizationProvider {
    fn create_organization(
        &self,
        context: InvocationContext,
        request: CreateOrganizationRequest,
    ) -> NativeRequestFuture<OrganizationAdmin> {
        let caller_instance = self.authorized_admin_caller(&context).map(str::to_owned);
        let prepared = self.prepared();
        Box::pin(async move {
            let Some(caller_instance) = caller_instance else {
                return Ok(Err(CreateOrganizationError::Forbidden));
            };
            let name = request.name.trim().to_owned();
            if !valid_name(&request.idempotency_key, 256)
                || !valid_organization_name(&request.name)
                || !valid_slug(&request.slug)
                || !valid_name(&request.owner_subject, 256)
            {
                return Ok(Err(CreateOrganizationError::InvalidOrganization));
            }
            let prepared = prepared?;
            create_organization_in_postgres(prepared, caller_instance, request, name).await
        })
    }
}

impl OrganizationMembershipAdminProvider for OrganizationProvider {
    fn add_member(
        &self,
        context: InvocationContext,
        request: AddMemberRequest,
    ) -> NativeRequestFuture<OrganizationMembershipAdminAddMember> {
        let caller_instance = self
            .authorized_membership_admin_caller(&context)
            .map(str::to_owned);
        let prepared = self.prepared();
        Box::pin(async move {
            let Some(caller_instance) = caller_instance else {
                return Ok(Err(AddMemberError::Forbidden));
            };
            if !valid_membership_request(
                &request.idempotency_key,
                &request.organization_id,
                &request.subject,
            ) {
                return Ok(Err(AddMemberError::InvalidRequest));
            }
            let prepared = prepared?;
            add_member_in_postgres(prepared, caller_instance, request).await
        })
    }

    fn remove_member(
        &self,
        context: InvocationContext,
        request: RemoveMemberRequest,
    ) -> NativeRequestFuture<OrganizationMembershipAdminRemoveMember> {
        let caller_instance = self
            .authorized_membership_admin_caller(&context)
            .map(str::to_owned);
        let prepared = self.prepared();
        Box::pin(async move {
            let Some(caller_instance) = caller_instance else {
                return Ok(Err(RemoveMemberError::Forbidden));
            };
            if !valid_membership_request(
                &request.idempotency_key,
                &request.organization_id,
                &request.subject,
            ) {
                return Ok(Err(RemoveMemberError::InvalidRequest));
            }
            let prepared = prepared?;
            remove_member_in_postgres(prepared, caller_instance, request).await
        })
    }
}

impl OrganizationDirectoryProvider for OrganizationProvider {
    fn get_organization(
        &self,
        context: InvocationContext,
        request: GetOrganizationRequest,
    ) -> NativeRequestFuture<OrganizationDirectory> {
        let authorized = self.authorized_directory_caller(&context).is_some();
        let prepared = self.prepared();
        Box::pin(async move {
            if !authorized {
                return Ok(Err(GetOrganizationError::Forbidden));
            }
            if !valid_name(&request.organization_id, 256) {
                return Ok(Err(GetOrganizationError::InvalidRequest));
            }
            let prepared = prepared?;
            let row: Option<(String, String, bool, i64)> = sqlx::query_as(
                "SELECT name,slug,archived_at IS NULL,revision FROM organizations WHERE organization_id=$1",
            )
            .bind(&request.organization_id)
            .fetch_optional(prepared.postgres.pool())
            .await
            .map_err(|source| {
                runtime(OrganizationError::Database {
                    operation: "get organization directory entry",
                    source,
                })
            })?;
            let Some((name, slug, active, revision)) = row else {
                return Ok(Err(GetOrganizationError::OrganizationNotFound));
            };
            Ok(Ok(GetOrganizationResponse {
                active,
                name,
                organization_id: request.organization_id,
                revision: revision.to_string(),
                slug,
            }))
        })
    }
}

#[derive(Debug)]
enum MembershipCommandReplay {
    Exact {
        membership_id: String,
        revision: i64,
    },
    Conflict,
}

async fn add_member_in_postgres(
    prepared: PreparedOrganization,
    caller_instance: String,
    request: AddMemberRequest,
) -> Result<Result<AddMemberResponse, AddMemberError>, RuntimeFailure> {
    let generated_membership_id = random_id("member_").map_err(runtime)?;
    let mut transaction = prepared
        .postgres
        .pool()
        .begin()
        .await
        .map_err(|source| database_runtime("begin member addition", source))?;
    let reserved = reserve_membership_command(
        &mut transaction,
        &caller_instance,
        &request.idempotency_key,
        "add_member",
        &request.organization_id,
        &request.subject,
    )
    .await?;
    if !reserved {
        let replay = read_membership_command_replay(
            &mut transaction,
            &caller_instance,
            &request.idempotency_key,
            "add_member",
            &request.organization_id,
            &request.subject,
        )
        .await?;
        let MembershipCommandReplay::Exact {
            membership_id,
            revision,
        } = replay
        else {
            return Ok(Err(AddMemberError::IdempotencyConflict));
        };
        transaction
            .commit()
            .await
            .map_err(|source| database_runtime("commit member addition replay", source))?;
        return Ok(Ok(AddMemberResponse {
            created: false,
            membership_id,
            revision: revision.to_string(),
        }));
    }
    if !lock_active_organization(&mut transaction, &request.organization_id).await? {
        return Ok(Err(AddMemberError::OrganizationNotFound));
    }
    let existing: Option<(String, i64)> = sqlx::query_as(
        "SELECT membership_id,revision FROM organization_memberships WHERE organization_id=$1 AND subject=$2 AND removed_at IS NULL FOR UPDATE",
    )
    .bind(&request.organization_id)
    .bind(&request.subject)
    .fetch_optional(&mut *transaction)
    .await
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "read active member for addition",
            source,
        })
    })?;
    let (membership_id, revision, created) = if let Some((membership_id, revision)) = existing {
        (membership_id, revision, false)
    } else {
        sqlx::query(
            "INSERT INTO organization_memberships (membership_id,organization_id,subject,is_owner,revision) VALUES ($1,$2,$3,false,1)",
        )
        .bind(&generated_membership_id)
        .bind(&request.organization_id)
        .bind(&request.subject)
        .execute(&mut *transaction)
        .await
        .map_err(|source| {
            runtime(OrganizationError::Database {
                operation: "insert organization member",
                source,
            })
        })?;
        (generated_membership_id, 1, true)
    };
    complete_membership_command(
        &mut transaction,
        &caller_instance,
        &request.idempotency_key,
        &membership_id,
        revision,
        created,
    )
    .await?;
    transaction
        .commit()
        .await
        .map_err(|source| database_runtime("commit member addition", source))?;
    Ok(Ok(AddMemberResponse {
        created,
        membership_id,
        revision: revision.to_string(),
    }))
}

async fn remove_member_in_postgres(
    prepared: PreparedOrganization,
    caller_instance: String,
    request: RemoveMemberRequest,
) -> Result<Result<RemoveMemberResponse, RemoveMemberError>, RuntimeFailure> {
    let mut transaction = prepared
        .postgres
        .pool()
        .begin()
        .await
        .map_err(|source| database_runtime("begin member removal", source))?;
    let reserved = reserve_membership_command(
        &mut transaction,
        &caller_instance,
        &request.idempotency_key,
        "remove_member",
        &request.organization_id,
        &request.subject,
    )
    .await?;
    if !reserved {
        let replay = read_membership_command_replay(
            &mut transaction,
            &caller_instance,
            &request.idempotency_key,
            "remove_member",
            &request.organization_id,
            &request.subject,
        )
        .await?;
        let MembershipCommandReplay::Exact {
            membership_id,
            revision,
        } = replay
        else {
            return Ok(Err(RemoveMemberError::IdempotencyConflict));
        };
        transaction
            .commit()
            .await
            .map_err(|source| database_runtime("commit member removal replay", source))?;
        return Ok(Ok(RemoveMemberResponse {
            membership_id,
            removed: false,
            revision: revision.to_string(),
        }));
    }
    if !lock_active_organization(&mut transaction, &request.organization_id).await? {
        return Ok(Err(RemoveMemberError::OrganizationNotFound));
    }
    let existing: Option<(String, bool, i64)> = sqlx::query_as(
        "SELECT membership_id,is_owner,revision FROM organization_memberships WHERE organization_id=$1 AND subject=$2 AND removed_at IS NULL FOR UPDATE",
    )
    .bind(&request.organization_id)
    .bind(&request.subject)
    .fetch_optional(&mut *transaction)
    .await
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "read active member for removal",
            source,
        })
    })?;
    let Some((membership_id, is_owner, revision)) = existing else {
        return Ok(Err(RemoveMemberError::MembershipNotFound));
    };
    if is_owner {
        return Ok(Err(RemoveMemberError::OwnerProtected));
    }
    let next_revision = next_membership_revision(revision)?;
    sqlx::query(
        "UPDATE organization_memberships SET removed_at=transaction_timestamp(),updated_at=transaction_timestamp(),revision=$3 WHERE organization_id=$1 AND membership_id=$2 AND removed_at IS NULL",
    )
    .bind(&request.organization_id)
    .bind(&membership_id)
    .bind(next_revision)
    .execute(&mut *transaction)
    .await
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "remove organization member",
            source,
        })
    })?;
    complete_membership_command(
        &mut transaction,
        &caller_instance,
        &request.idempotency_key,
        &membership_id,
        next_revision,
        true,
    )
    .await?;
    transaction
        .commit()
        .await
        .map_err(|source| database_runtime("commit member removal", source))?;
    Ok(Ok(RemoveMemberResponse {
        membership_id,
        removed: true,
        revision: next_revision.to_string(),
    }))
}

async fn reserve_membership_command(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    caller_instance: &str,
    idempotency_key: &str,
    operation: &str,
    organization_id: &str,
    subject: &str,
) -> Result<bool, RuntimeFailure> {
    sqlx::query(
        "INSERT INTO organization_membership_commands (caller_instance,idempotency_key,operation,organization_id,subject) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (caller_instance,idempotency_key) DO NOTHING",
    )
    .bind(caller_instance)
    .bind(idempotency_key)
    .bind(operation)
    .bind(organization_id)
    .bind(subject)
    .execute(&mut **transaction)
    .await
    .map(|result| result.rows_affected() == 1)
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "reserve membership command",
            source,
        })
    })
}

async fn read_membership_command_replay(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    caller_instance: &str,
    idempotency_key: &str,
    operation: &str,
    organization_id: &str,
    subject: &str,
) -> Result<MembershipCommandReplay, RuntimeFailure> {
    let row: (
        String,
        String,
        String,
        Option<String>,
        Option<i64>,
        Option<bool>,
    ) = sqlx::query_as(
        "SELECT operation,organization_id,subject,membership_id,result_revision,changed FROM organization_membership_commands WHERE caller_instance=$1 AND idempotency_key=$2 FOR UPDATE",
    )
    .bind(caller_instance)
    .bind(idempotency_key)
    .fetch_one(&mut **transaction)
    .await
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "read membership command replay",
            source,
        })
    })?;
    if row.0 != operation || row.1 != organization_id || row.2 != subject {
        return Ok(MembershipCommandReplay::Conflict);
    }
    let (Some(membership_id), Some(revision), Some(_changed)) = (row.3, row.4, row.5) else {
        return Err(runtime(OrganizationError::Invariant {
            detail: "committed membership command has no result",
        }));
    };
    Ok(MembershipCommandReplay::Exact {
        membership_id,
        revision,
    })
}

async fn complete_membership_command(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    caller_instance: &str,
    idempotency_key: &str,
    membership_id: &str,
    revision: i64,
    changed: bool,
) -> Result<(), RuntimeFailure> {
    sqlx::query(
        "UPDATE organization_membership_commands SET membership_id=$3,result_revision=$4,changed=$5,completed_at=transaction_timestamp() WHERE caller_instance=$1 AND idempotency_key=$2 AND completed_at IS NULL",
    )
    .bind(caller_instance)
    .bind(idempotency_key)
    .bind(membership_id)
    .bind(revision)
    .bind(changed)
    .execute(&mut **transaction)
    .await
    .and_then(|result| {
        if result.rows_affected() == 1 {
            Ok(result)
        } else {
            Err(sqlx::Error::RowNotFound)
        }
    })
    .map(|_| ())
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "complete membership command",
            source,
        })
    })
}

async fn lock_active_organization(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    organization_id: &str,
) -> Result<bool, RuntimeFailure> {
    sqlx::query_scalar::<_, bool>(
        "SELECT archived_at IS NULL FROM organizations WHERE organization_id=$1 FOR UPDATE",
    )
    .bind(organization_id)
    .fetch_optional(&mut **transaction)
    .await
    .map(|value| value.unwrap_or(false))
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "lock organization for membership command",
            source,
        })
    })
}

async fn create_organization_in_postgres(
    prepared: PreparedOrganization,
    caller_instance: String,
    request: CreateOrganizationRequest,
    name: String,
) -> Result<Result<CreateOrganizationResponse, CreateOrganizationError>, RuntimeFailure> {
    let organization_id = random_id("org_").map_err(runtime)?;
    let owner_membership_id = random_id("member_").map_err(runtime)?;
    let mut transaction = prepared.postgres.pool().begin().await.map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "begin organization creation",
            source,
        })
    })?;
    if !reserve_creation(
        &mut transaction,
        &caller_instance,
        &request,
        &name,
        &organization_id,
        &owner_membership_id,
    )
    .await?
    {
        let response = match read_creation_replay(
            &mut transaction,
            &caller_instance,
            &request,
            &name,
        )
        .await?
        {
            Ok(response) => response,
            Err(error) => return Ok(Err(error)),
        };
        transaction.commit().await.map_err(|source| {
            runtime(OrganizationError::Database {
                operation: "commit organization creation replay",
                source,
            })
        })?;
        return Ok(Ok(response));
    }
    if let Err(error) = insert_organization_and_owner(
        &mut transaction,
        &request,
        &name,
        &organization_id,
        &owner_membership_id,
    )
    .await?
    {
        return Ok(Err(error));
    }
    transaction.commit().await.map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "commit organization creation",
            source,
        })
    })?;
    Ok(Ok(CreateOrganizationResponse {
        created: true,
        organization_id,
        owner_membership_id,
    }))
}

async fn reserve_creation(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    caller_instance: &str,
    request: &CreateOrganizationRequest,
    name: &str,
    organization_id: &str,
    owner_membership_id: &str,
) -> Result<bool, RuntimeFailure> {
    sqlx::query(
        "INSERT INTO organization_creation_requests (caller_instance,idempotency_key,name,slug,owner_subject,organization_id,owner_membership_id) VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (caller_instance,idempotency_key) DO NOTHING",
    )
    .bind(caller_instance)
    .bind(&request.idempotency_key)
    .bind(name)
    .bind(&request.slug)
    .bind(&request.owner_subject)
    .bind(organization_id)
    .bind(owner_membership_id)
    .execute(&mut **transaction)
    .await
    .map(|result| result.rows_affected() == 1)
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "reserve organization creation",
            source,
        })
    })
}

async fn read_creation_replay(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    caller_instance: &str,
    request: &CreateOrganizationRequest,
    name: &str,
) -> Result<Result<CreateOrganizationResponse, CreateOrganizationError>, RuntimeFailure> {
    let (stored_name, stored_slug, stored_owner, organization_id, owner_membership_id): (
        String,
        String,
        String,
        String,
        String,
    ) = sqlx::query_as(
        "SELECT name,slug,owner_subject,organization_id,owner_membership_id FROM organization_creation_requests WHERE caller_instance=$1 AND idempotency_key=$2",
    )
    .bind(caller_instance)
    .bind(&request.idempotency_key)
    .fetch_one(&mut **transaction)
    .await
    .map_err(|source| {
        runtime(OrganizationError::Database {
            operation: "read organization creation replay",
            source,
        })
    })?;
    if stored_name != name || stored_slug != request.slug || stored_owner != request.owner_subject {
        return Ok(Err(CreateOrganizationError::IdempotencyConflict));
    }
    Ok(Ok(CreateOrganizationResponse {
        created: false,
        organization_id,
        owner_membership_id,
    }))
}

async fn insert_organization_and_owner(
    transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
    request: &CreateOrganizationRequest,
    name: &str,
    organization_id: &str,
    owner_membership_id: &str,
) -> Result<Result<(), CreateOrganizationError>, RuntimeFailure> {
    let inserted =
        sqlx::query("INSERT INTO organizations (organization_id,name,slug) VALUES ($1,$2,$3)")
            .bind(organization_id)
            .bind(name)
            .bind(&request.slug)
            .execute(&mut **transaction)
            .await;
    if let Err(error) = inserted {
        if error
            .as_database_error()
            .and_then(|database| database.constraint())
            == Some("organizations_active_slug_key")
        {
            return Ok(Err(CreateOrganizationError::SlugConflict));
        }
        return Err(runtime(OrganizationError::Database {
            operation: "insert organization",
            source: error,
        }));
    }
    sqlx::query("INSERT INTO organization_memberships (membership_id,organization_id,subject,is_owner) VALUES ($1,$2,$3,true)")
        .bind(owner_membership_id)
        .bind(organization_id)
        .bind(&request.owner_subject)
        .execute(&mut **transaction)
        .await
        .map_err(|source| runtime(OrganizationError::Database { operation: "insert owner membership", source }))?;
    Ok(Ok(()))
}

impl OrganizationMembershipProvider for OrganizationProvider {
    fn check_membership(
        &self,
        _context: InvocationContext,
        request: CheckMembershipRequest,
    ) -> NativeRequestFuture<OrganizationMembership> {
        let prepared = self.prepared();
        Box::pin(async move {
            if !valid_name(&request.organization_id, 256) || !valid_name(&request.subject, 256) {
                return Ok(Err(CheckMembershipError::InvalidRequest));
            }
            let prepared = prepared?;
            let row = sqlx::query(
                "SELECT EXISTS(SELECT 1 FROM organizations WHERE organization_id=$1 AND archived_at IS NULL) AS organization_exists, COALESCE((SELECT removed_at IS NULL FROM organization_memberships WHERE organization_id=$1 AND subject=$2 ORDER BY created_at DESC LIMIT 1),false) AS active, COALESCE((SELECT is_owner AND removed_at IS NULL FROM organization_memberships WHERE organization_id=$1 AND subject=$2 ORDER BY created_at DESC LIMIT 1),false) AS owner",
            )
            .bind(&request.organization_id)
            .bind(&request.subject)
            .fetch_one(prepared.postgres.pool())
            .await
            .map_err(|source| runtime(OrganizationError::Database { operation: "check organization membership", source }))?;
            let organization_exists: bool =
                row.try_get("organization_exists").map_err(|source| {
                    runtime(OrganizationError::Database {
                        operation: "decode organization existence",
                        source,
                    })
                })?;
            if !organization_exists {
                return Ok(Err(CheckMembershipError::OrganizationNotFound));
            }
            let active = row.try_get("active").map_err(|source| {
                runtime(OrganizationError::Database {
                    operation: "decode organization membership",
                    source,
                })
            })?;
            let owner = row.try_get("owner").map_err(|source| {
                runtime(OrganizationError::Database {
                    operation: "decode organization ownership",
                    source,
                })
            })?;
            Ok(Ok(CheckMembershipResponse { active, owner }))
        })
    }
}

#[derive(Debug)]
struct OrganizationLifecycle {
    config: OrganizationConfig,
    state: Rc<RefCell<Option<PreparedOrganization>>>,
}

impl PluginLifecycle for OrganizationLifecycle {
    fn prepare(&self, context: PrepareContext) -> PluginFuture {
        let config = self.config.clone();
        let state = self.state.clone();
        let dependencies = context.dependencies().clone();
        let cancellation = context.cancellation();
        Box::pin(async move {
            let secrets = SecretsClient::from_dependencies(&dependencies)?;
            let invocation =
                dependencies.invocation_context_after(DEPENDENCY_TIMEOUT, cancellation)?;
            let database_url = secrets
                .resolve_with_context(
                    invocation,
                    ResolveRequest {
                        reference: config.database_url_secret.clone(),
                    },
                )
                .await
                .map_err(|error| match error {
                    SecretsInvocationError::Domain(_) => RuntimeFailure::PluginFailure {
                        detail: format!(
                            "database URL secret `{}` was rejected",
                            config.database_url_secret
                        ),
                    },
                    SecretsInvocationError::Runtime(error) => error,
                })?;
            let database_url = Zeroizing::new(database_url.value);
            let postgres = OwnedPostgres::prepare(
                &database_url,
                schema_plan(config.schema).map_err(|error| {
                    RuntimeFailure::InvalidResolvedPlan {
                        detail: error.to_string(),
                    }
                })?,
            )
            .await
            .map_err(|error| RuntimeFailure::PluginFailure {
                detail: error.to_string(),
            })?;
            state.replace(Some(PreparedOrganization { postgres }));
            Ok(())
        })
    }

    fn deactivate(&self, _context: DeactivateContext) -> PluginFuture {
        let prepared = self.state.borrow_mut().take();
        Box::pin(async move {
            if let Some(prepared) = prepared {
                prepared.postgres.pool().close().await;
            }
            Ok(())
        })
    }
}

#[derive(Debug, Error)]
enum OrganizationError {
    #[error("PostgreSQL operation `{operation}` failed")]
    Database {
        operation: &'static str,
        #[source]
        source: sqlx::Error,
    },
    #[error("random source unavailable")]
    Random,
    #[error("Organization invariant failed: {detail}")]
    Invariant { detail: &'static str },
}

fn runtime(error: impl fmt::Display) -> RuntimeFailure {
    RuntimeFailure::PluginFailure {
        detail: error.to_string(),
    }
}

fn database_runtime(operation: &'static str, source: sqlx::Error) -> RuntimeFailure {
    runtime(OrganizationError::Database { operation, source })
}

fn next_membership_revision(revision: i64) -> Result<i64, RuntimeFailure> {
    revision.checked_add(1).ok_or_else(|| {
        runtime(OrganizationError::Invariant {
            detail: "membership revision overflow",
        })
    })
}

fn random_id(prefix: &str) -> Result<String, OrganizationError> {
    let mut bytes = [0_u8; 18];
    getrandom::fill(&mut bytes).map_err(|_| OrganizationError::Random)?;
    let mut id = String::with_capacity(prefix.len() + bytes.len() * 2);
    id.push_str(prefix);
    for byte in bytes {
        write!(&mut id, "{byte:02x}").expect("writing to String cannot fail");
    }
    Ok(id)
}

fn valid_organization_name(value: &str) -> bool {
    let value = value.trim();
    !value.is_empty() && value.len() <= 200 && !value.chars().any(char::is_control)
}

fn valid_slug(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= 100
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
        && !value.starts_with('-')
        && !value.ends_with('-')
}

fn valid_name(value: &str, max: usize) -> bool {
    !value.is_empty()
        && value.len() <= max
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'))
}

fn valid_membership_request(idempotency_key: &str, organization_id: &str, subject: &str) -> bool {
    valid_name(idempotency_key, 256) && valid_name(organization_id, 256) && valid_name(subject, 256)
}

fn valid_secret_reference(reference: &str) -> bool {
    !reference.is_empty()
        && reference.len() <= 256
        && !reference.starts_with('/')
        && !reference.ends_with('/')
        && !reference.contains("//")
        && reference
            .split('/')
            .all(|segment| segment != "." && segment != "..")
        && reference
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'/'))
}

#[cfg(test)]
mod tests {
    use super::*;
    use lenso_kernel::CancellationToken;
    use lenso_postgres_kit::{Migration, SchemaOperator, SchemaPlan};
    use sqlx::{AssertSqlSafe, Executor};

    const LEGACY_MIGRATIONS: &[Migration] = &[Migration::new(
        1,
        "create-organizations",
        include_str!("../migrations/001_create_organizations.sql"),
    )];

    fn legacy_schema_plan(schema: impl Into<std::sync::Arc<str>>) -> SchemaPlan {
        SchemaPlan::new(schema, LEGACY_MIGRATIONS).unwrap()
    }

    #[test]
    fn configuration_rejects_ambient_admin_authority() {
        let error = OrganizationConfig::new("organization", "organization/database", Vec::new())
            .unwrap_err();
        assert_eq!(error, OrganizationConfigError::InvalidAdminCallers);
    }

    #[test]
    fn configuration_rejects_invalid_directory_caller_keys() {
        let error = OrganizationConfig::new(
            "organization",
            "organization/database",
            vec!["business-admin".to_owned()],
        )
        .unwrap()
        .with_directory_callers(vec!["invalid caller".to_owned()])
        .unwrap_err();
        assert_eq!(error, OrganizationConfigError::InvalidDirectoryCallers);
    }

    #[test]
    fn slugs_are_stable_and_narrow() {
        assert!(valid_slug("acme-platform"));
        assert!(!valid_slug("Acme Platform"));
        assert!(!valid_slug("-acme"));
    }

    #[test]
    fn generated_ids_do_not_repeat() {
        assert_ne!(random_id("org_").unwrap(), random_id("org_").unwrap());
    }

    #[tokio::test]
    async fn forbidden_admin_is_a_domain_error_before_storage_access() {
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(None)),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: Vec::new(),
            membership_admin_callers: Vec::new(),
        };
        let context = InvocationContext::new(1, None, CancellationToken::new())
            .with_caller_instance("untrusted");
        let result = provider
            .create_organization(
                context,
                CreateOrganizationRequest {
                    idempotency_key: "forbidden-create".to_owned(),
                    name: "Acme".to_owned(),
                    owner_subject: "usr_owner".to_owned(),
                    slug: "acme".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(result, Err(CreateOrganizationError::Forbidden));
    }

    #[tokio::test]
    async fn invalid_idempotency_key_is_rejected_before_storage_access() {
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(None)),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: Vec::new(),
            membership_admin_callers: Vec::new(),
        };
        let context = InvocationContext::new(1, None, CancellationToken::new())
            .with_caller_instance("business-admin");
        let result = provider
            .create_organization(
                context,
                CreateOrganizationRequest {
                    idempotency_key: String::new(),
                    name: "Acme".to_owned(),
                    owner_subject: "usr_owner".to_owned(),
                    slug: "acme".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(result, Err(CreateOrganizationError::InvalidOrganization));
    }

    #[tokio::test]
    async fn forbidden_membership_admin_is_a_domain_error_before_storage_access() {
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(None)),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: Vec::new(),
            membership_admin_callers: vec!["membership-admin".to_owned()],
        };
        let context = InvocationContext::new(1, None, CancellationToken::new())
            .with_caller_instance("untrusted");

        let add = provider
            .add_member(
                context.clone(),
                AddMemberRequest {
                    idempotency_key: "add-member".to_owned(),
                    organization_id: "org_acme".to_owned(),
                    subject: "usr_member".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(add, Err(AddMemberError::Forbidden));

        let remove = provider
            .remove_member(
                context,
                RemoveMemberRequest {
                    idempotency_key: "remove-member".to_owned(),
                    organization_id: "org_acme".to_owned(),
                    subject: "usr_member".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(remove, Err(RemoveMemberError::Forbidden));
    }

    #[tokio::test]
    async fn invalid_membership_admin_request_is_rejected_before_storage_access() {
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(None)),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: Vec::new(),
            membership_admin_callers: vec!["membership-admin".to_owned()],
        };
        let context = InvocationContext::new(1, None, CancellationToken::new())
            .with_caller_instance("membership-admin");

        let add = provider
            .add_member(
                context.clone(),
                AddMemberRequest {
                    idempotency_key: String::new(),
                    organization_id: "org_acme".to_owned(),
                    subject: "usr_member".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(add, Err(AddMemberError::InvalidRequest));

        let remove = provider
            .remove_member(
                context,
                RemoveMemberRequest {
                    idempotency_key: "remove-member".to_owned(),
                    organization_id: "org_acme".to_owned(),
                    subject: "invalid subject".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(remove, Err(RemoveMemberError::InvalidRequest));
    }

    #[tokio::test]
    async fn directory_authorization_and_validation_happen_before_storage_access() {
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(None)),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: vec!["directory-consumer".to_owned()],
            membership_admin_callers: Vec::new(),
        };
        let request = GetOrganizationRequest {
            organization_id: "org_acme".to_owned(),
        };
        let forbidden = provider
            .get_organization(
                InvocationContext::new(1, None, CancellationToken::new())
                    .with_caller_instance("untrusted"),
                request,
            )
            .await
            .unwrap();
        assert_eq!(forbidden, Err(GetOrganizationError::Forbidden));

        let invalid = provider
            .get_organization(
                InvocationContext::new(2, None, CancellationToken::new())
                    .with_caller_instance("directory-consumer"),
                GetOrganizationRequest {
                    organization_id: String::new(),
                },
            )
            .await
            .unwrap();
        assert_eq!(invalid, Err(GetOrganizationError::InvalidRequest));
    }

    #[tokio::test]
    async fn unprepared_membership_reports_runtime_failure() {
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(None)),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: Vec::new(),
            membership_admin_callers: Vec::new(),
        };
        let result = provider
            .check_membership(
                InvocationContext::new(1, None, CancellationToken::new()),
                CheckMembershipRequest {
                    organization_id: "org_missing".to_owned(),
                    subject: "usr_owner".to_owned(),
                },
            )
            .await;
        assert!(matches!(result, Err(RuntimeFailure::PluginFailure { .. })));
    }

    #[tokio::test]
    #[ignore = "requires LENSO_POSTGRES_TEST_URL"]
    #[allow(
        clippy::too_many_lines,
        reason = "the acceptance scenario keeps concurrent creation and every replay boundary together"
    )]
    async fn concurrent_create_is_caller_scoped_idempotent_and_preserves_ownership() {
        let database_url =
            std::env::var("LENSO_POSTGRES_TEST_URL").expect("LENSO_POSTGRES_TEST_URL is required");
        let schema = random_id("organization_test_").unwrap();
        OrganizationOperator::setup(&database_url, &schema)
            .await
            .unwrap();
        let postgres = OwnedPostgres::prepare(&database_url, schema_plan(schema.clone()).unwrap())
            .await
            .unwrap();
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(Some(PreparedOrganization { postgres }))),
            admin_callers: vec!["business-admin".to_owned(), "second-admin".to_owned()],
            directory_callers: vec!["directory-consumer".to_owned()],
            membership_admin_callers: vec!["membership-admin".to_owned()],
        };
        let admin_context = InvocationContext::new(1, None, CancellationToken::new())
            .with_caller_instance("business-admin");
        let create_request = CreateOrganizationRequest {
            idempotency_key: "create-acme".to_owned(),
            name: "Acme".to_owned(),
            owner_subject: "usr_owner".to_owned(),
            slug: "acme".to_owned(),
        };
        let first_creation =
            provider.create_organization(admin_context.clone(), create_request.clone());
        let concurrent_replay = provider.create_organization(
            InvocationContext::new(2, None, CancellationToken::new())
                .with_caller_instance("business-admin"),
            create_request.clone(),
        );
        let (first_creation, concurrent_replay) = tokio::join!(first_creation, concurrent_replay);
        let first_creation = first_creation.unwrap().unwrap();
        let concurrent_replay = concurrent_replay.unwrap().unwrap();
        assert_ne!(first_creation.created, concurrent_replay.created);
        assert_eq!(
            first_creation.organization_id,
            concurrent_replay.organization_id
        );
        assert_eq!(
            first_creation.owner_membership_id,
            concurrent_replay.owner_membership_id
        );
        let created = if first_creation.created {
            first_creation
        } else {
            concurrent_replay
        };
        let membership = provider
            .check_membership(
                InvocationContext::new(3, None, CancellationToken::new()),
                CheckMembershipRequest {
                    organization_id: created.organization_id.clone(),
                    subject: "usr_owner".to_owned(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(membership.active);
        assert!(membership.owner);

        let replay = provider
            .create_organization(admin_context.clone(), create_request.clone())
            .await
            .unwrap()
            .unwrap();
        assert!(!replay.created);
        assert_eq!(replay.organization_id, created.organization_id);
        assert_eq!(replay.owner_membership_id, created.owner_membership_id);

        let conflict = provider
            .create_organization(
                admin_context.clone(),
                CreateOrganizationRequest {
                    owner_subject: "usr_other".to_owned(),
                    ..create_request
                },
            )
            .await
            .unwrap();
        assert_eq!(conflict, Err(CreateOrganizationError::IdempotencyConflict));

        let second_caller = provider
            .create_organization(
                InvocationContext::new(4, None, CancellationToken::new())
                    .with_caller_instance("second-admin"),
                CreateOrganizationRequest {
                    idempotency_key: "create-acme".to_owned(),
                    name: "Second".to_owned(),
                    owner_subject: "usr_second".to_owned(),
                    slug: "second".to_owned(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(second_caller.created);
        assert_ne!(second_caller.organization_id, created.organization_id);

        let duplicate = provider
            .create_organization(
                admin_context,
                CreateOrganizationRequest {
                    idempotency_key: "create-another-acme".to_owned(),
                    name: "Another Acme".to_owned(),
                    owner_subject: "usr_other".to_owned(),
                    slug: "acme".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(duplicate, Err(CreateOrganizationError::SlugConflict));

        let cleanup_pool = sqlx::PgPool::connect(&database_url).await.unwrap();
        cleanup_pool
            .execute(AssertSqlSafe(format!("DROP SCHEMA \"{schema}\" CASCADE")))
            .await
            .unwrap();
        cleanup_pool.close().await;
    }

    #[tokio::test]
    #[ignore = "requires LENSO_POSTGRES_TEST_URL"]
    #[allow(
        clippy::too_many_lines,
        reason = "the acceptance scenario keeps membership concurrency, replay, and owner protection together"
    )]
    async fn membership_admin_is_caller_scoped_idempotent_and_owner_safe() {
        let database_url =
            std::env::var("LENSO_POSTGRES_TEST_URL").expect("LENSO_POSTGRES_TEST_URL is required");
        let schema = random_id("org_member_test_").unwrap();
        OrganizationOperator::setup(&database_url, &schema)
            .await
            .unwrap();
        let postgres = OwnedPostgres::prepare(&database_url, schema_plan(schema.clone()).unwrap())
            .await
            .unwrap();
        let provider = OrganizationProvider {
            state: Rc::new(RefCell::new(Some(PreparedOrganization { postgres }))),
            admin_callers: vec!["business-admin".to_owned()],
            directory_callers: vec!["directory-consumer".to_owned()],
            membership_admin_callers: vec![
                "membership-admin".to_owned(),
                "second-membership-admin".to_owned(),
            ],
        };
        let organization = provider
            .create_organization(
                InvocationContext::new(1, None, CancellationToken::new())
                    .with_caller_instance("business-admin"),
                CreateOrganizationRequest {
                    idempotency_key: "create-membership-test".to_owned(),
                    name: "Membership Test".to_owned(),
                    owner_subject: "usr_owner".to_owned(),
                    slug: "membership-test".to_owned(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        let directory_entry = provider
            .get_organization(
                InvocationContext::new(2, None, CancellationToken::new())
                    .with_caller_instance("directory-consumer"),
                GetOrganizationRequest {
                    organization_id: organization.organization_id.clone(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(directory_entry.active);
        assert_eq!(directory_entry.name, "Membership Test");
        assert_eq!(directory_entry.slug, "membership-test");
        assert_eq!(directory_entry.revision, "1");

        let missing_directory_entry = provider
            .get_organization(
                InvocationContext::new(3, None, CancellationToken::new())
                    .with_caller_instance("directory-consumer"),
                GetOrganizationRequest {
                    organization_id: "org_missing".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(
            missing_directory_entry,
            Err(GetOrganizationError::OrganizationNotFound)
        );
        let add_request = AddMemberRequest {
            idempotency_key: "add-primary-member".to_owned(),
            organization_id: organization.organization_id.clone(),
            subject: "usr_member".to_owned(),
        };
        let first_add = provider.add_member(
            InvocationContext::new(4, None, CancellationToken::new())
                .with_caller_instance("membership-admin"),
            add_request.clone(),
        );
        let concurrent_replay = provider.add_member(
            InvocationContext::new(5, None, CancellationToken::new())
                .with_caller_instance("membership-admin"),
            add_request.clone(),
        );
        let (first_add, concurrent_replay) = tokio::join!(first_add, concurrent_replay);
        let first_add = first_add.unwrap().unwrap();
        let concurrent_replay = concurrent_replay.unwrap().unwrap();
        assert_ne!(first_add.created, concurrent_replay.created);
        assert_eq!(first_add.membership_id, concurrent_replay.membership_id);
        assert_eq!(first_add.revision, "1");
        assert_eq!(concurrent_replay.revision, "1");

        let active = provider
            .check_membership(
                InvocationContext::new(4, None, CancellationToken::new()),
                CheckMembershipRequest {
                    organization_id: organization.organization_id.clone(),
                    subject: "usr_member".to_owned(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(active.active);
        assert!(!active.owner);

        let conflict = provider
            .add_member(
                InvocationContext::new(5, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                AddMemberRequest {
                    subject: "usr_other".to_owned(),
                    ..add_request.clone()
                },
            )
            .await
            .unwrap();
        assert_eq!(conflict, Err(AddMemberError::IdempotencyConflict));

        let second_caller = provider
            .add_member(
                InvocationContext::new(6, None, CancellationToken::new())
                    .with_caller_instance("second-membership-admin"),
                AddMemberRequest {
                    subject: "usr_second".to_owned(),
                    ..add_request.clone()
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(second_caller.created);

        let owner_removal = provider
            .remove_member(
                InvocationContext::new(7, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                RemoveMemberRequest {
                    idempotency_key: "remove-owner".to_owned(),
                    organization_id: organization.organization_id.clone(),
                    subject: "usr_owner".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(owner_removal, Err(RemoveMemberError::OwnerProtected));

        let remove_request = RemoveMemberRequest {
            idempotency_key: "remove-primary-member".to_owned(),
            organization_id: organization.organization_id.clone(),
            subject: "usr_member".to_owned(),
        };
        let removal = provider
            .remove_member(
                InvocationContext::new(8, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                remove_request.clone(),
            )
            .await
            .unwrap()
            .unwrap();
        assert!(removal.removed);
        assert_eq!(removal.membership_id, first_add.membership_id);
        assert_eq!(removal.revision, "2");

        let replay = provider
            .remove_member(
                InvocationContext::new(9, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                remove_request,
            )
            .await
            .unwrap()
            .unwrap();
        assert!(!replay.removed);
        assert_eq!(replay.membership_id, first_add.membership_id);
        assert_eq!(replay.revision, "2");

        let inactive = provider
            .check_membership(
                InvocationContext::new(10, None, CancellationToken::new()),
                CheckMembershipRequest {
                    organization_id: organization.organization_id.clone(),
                    subject: "usr_member".to_owned(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(!inactive.active);
        assert!(!inactive.owner);

        let prepared = provider.prepared().unwrap();
        sqlx::query(
            "UPDATE organizations SET archived_at=transaction_timestamp(),revision=2 WHERE organization_id=$1",
        )
        .bind(&organization.organization_id)
        .execute(prepared.postgres.pool())
        .await
        .unwrap();
        let archived_directory_entry = provider
            .get_organization(
                InvocationContext::new(11, None, CancellationToken::new())
                    .with_caller_instance("directory-consumer"),
                GetOrganizationRequest {
                    organization_id: organization.organization_id.clone(),
                },
            )
            .await
            .unwrap()
            .unwrap();
        assert!(!archived_directory_entry.active);
        assert_eq!(archived_directory_entry.revision, "2");

        let archived_replay = provider
            .add_member(
                InvocationContext::new(12, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                add_request.clone(),
            )
            .await
            .unwrap()
            .unwrap();
        assert!(!archived_replay.created);
        assert_eq!(archived_replay.membership_id, first_add.membership_id);
        assert_eq!(archived_replay.revision, "1");

        let archived_new_command = provider
            .add_member(
                InvocationContext::new(13, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                AddMemberRequest {
                    idempotency_key: "archived-new-command".to_owned(),
                    organization_id: organization.organization_id.clone(),
                    subject: "usr_after_archive".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(
            archived_new_command,
            Err(AddMemberError::OrganizationNotFound)
        );

        let operation_conflict = provider
            .remove_member(
                InvocationContext::new(14, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                RemoveMemberRequest {
                    idempotency_key: add_request.idempotency_key,
                    organization_id: organization.organization_id.clone(),
                    subject: add_request.subject,
                },
            )
            .await
            .unwrap();
        assert_eq!(
            operation_conflict,
            Err(RemoveMemberError::IdempotencyConflict)
        );

        let missing_organization = provider
            .add_member(
                InvocationContext::new(15, None, CancellationToken::new())
                    .with_caller_instance("membership-admin"),
                AddMemberRequest {
                    idempotency_key: "missing-organization".to_owned(),
                    organization_id: "org_missing".to_owned(),
                    subject: "usr_member".to_owned(),
                },
            )
            .await
            .unwrap();
        assert_eq!(
            missing_organization,
            Err(AddMemberError::OrganizationNotFound)
        );

        prepared.postgres.pool().close().await;
        let cleanup_pool = sqlx::PgPool::connect(&database_url).await.unwrap();
        cleanup_pool
            .execute(AssertSqlSafe(format!("DROP SCHEMA \"{schema}\" CASCADE")))
            .await
            .unwrap();
        cleanup_pool.close().await;
    }

    #[tokio::test]
    #[ignore = "requires LENSO_POSTGRES_TEST_URL"]
    async fn upgrade_projects_legacy_owner_and_rejects_an_ownerless_active_organization() {
        let database_url =
            std::env::var("LENSO_POSTGRES_TEST_URL").expect("LENSO_POSTGRES_TEST_URL is required");
        let schema = random_id("organization_upgrade_test_").unwrap();
        SchemaOperator::connect(&database_url, legacy_schema_plan(schema.clone()))
            .await
            .unwrap()
            .setup()
            .await
            .unwrap();
        let legacy = OwnedPostgres::prepare(&database_url, legacy_schema_plan(schema.clone()))
            .await
            .unwrap();

        sqlx::query("INSERT INTO organizations (organization_id,name,slug) VALUES ('org_good','Good','good'),('org_bad','Bad','bad')")
            .execute(legacy.pool())
            .await
            .unwrap();
        sqlx::query("INSERT INTO organization_roles (role_id,organization_id,name,permissions,system_key) VALUES ('role_good','org_good','Owner',ARRAY['organization.read'],'owner'),('role_bad','org_bad','Member',ARRAY['organization.read'],NULL)")
            .execute(legacy.pool())
            .await
            .unwrap();
        sqlx::query("INSERT INTO organization_memberships (membership_id,organization_id,subject,role_id) VALUES ('membership_good','org_good','usr_good','role_good'),('membership_bad','org_bad','usr_bad','role_bad')")
            .execute(legacy.pool())
            .await
            .unwrap();

        assert!(
            OrganizationOperator::upgrade(&database_url, &schema)
                .await
                .is_err()
        );
        let legacy_roles_remain: bool =
            sqlx::query_scalar("SELECT to_regclass('organization_roles') IS NOT NULL")
                .fetch_one(legacy.pool())
                .await
                .unwrap();
        assert!(legacy_roles_remain);

        sqlx::query("UPDATE organization_roles SET system_key='owner' WHERE role_id='role_bad'")
            .execute(legacy.pool())
            .await
            .unwrap();
        legacy.pool().close().await;
        OrganizationOperator::upgrade(&database_url, &schema)
            .await
            .unwrap();
        let upgraded = OwnedPostgres::prepare(&database_url, schema_plan(schema.clone()).unwrap())
            .await
            .unwrap();
        let owner_count: i64 = sqlx::query_scalar(
            "SELECT count(*) FROM organization_memberships WHERE removed_at IS NULL AND is_owner",
        )
        .fetch_one(upgraded.pool())
        .await
        .unwrap();
        assert_eq!(owner_count, 2);
        let legacy_roles_remain: bool =
            sqlx::query_scalar("SELECT to_regclass('organization_roles') IS NOT NULL")
                .fetch_one(upgraded.pool())
                .await
                .unwrap();
        assert!(!legacy_roles_remain);
        let creation_receipts_exist: bool =
            sqlx::query_scalar("SELECT to_regclass('organization_creation_requests') IS NOT NULL")
                .fetch_one(upgraded.pool())
                .await
                .unwrap();
        assert!(creation_receipts_exist);

        upgraded.pool().close().await;
        let cleanup_pool = sqlx::PgPool::connect(&database_url).await.unwrap();
        cleanup_pool
            .execute(AssertSqlSafe(format!("DROP SCHEMA \"{schema}\" CASCADE")))
            .await
            .unwrap();
        cleanup_pool.close().await;
    }
}