strike48-connector 0.3.6

Rust SDK for the Strike48 Connector Framework
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
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
//! One-Time Token (OTT) authentication provider for secure connector authentication.
//!
//! This module supports 4 deployment options:
//!
//! 1. PRE-APPROVAL (OTT): Admin creates OTT → Connector uses it to register
//!    - Set STRIKE48_REGISTRATION_TOKEN or STRIKE48_REGISTRATION_TOKEN_FILE
//!    - Connector generates keypair and registers with public key
//!
//! 2. POST-APPROVAL: Connector connects → Admin approves → OTT via gRPC stream
//!    - No env vars needed, credentials issued after approval
//!
//! 3. K8S CERT-MANAGER: cert-manager creates keypair → All pods share it
//!    - Set STRIKE48_PRIVATE_KEY_PATH to the mounted secret path
//!    - Set STRIKE48_CLIENT_ID to the pre-configured client ID
//!    - Set STRIKE48_AUTH_URL to the auth realm URL
//!
//! 4. DIRECT AUTH: Operator creates auth client directly
//!    - Set STRIKE48_PRIVATE_KEY_PATH to the private key file
//!    - Set STRIKE48_CLIENT_ID to the auth client ID
//!    - Set STRIKE48_AUTH_URL to the auth realm URL

use crate::error::{ConnectorError, Result};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::time::sleep;

/// Default retry configuration for HTTP requests
const MAX_RETRIES: u32 = 3;
const INITIAL_RETRY_DELAY_MS: u64 = 500;
const MAX_RETRY_DELAY_MS: u64 = 5000;

const DEFAULT_OTT_PATHS: &[&str] = &[
    "/var/run/secrets/matrix/registration-token",
    ".matrix/registration-token",
];

const DEFAULT_PRIVATE_KEY_PATHS: &[&str] = &[
    "/var/run/secrets/matrix/connector-key.pem",
    "/var/run/secrets/matrix/tls.key",
];

#[derive(Debug, Clone, Serialize, Deserialize)]
struct OttData {
    token: String,
    #[serde(rename = "matrix_url")]
    api_url: Option<String>,
    #[serde(rename = "keycloak_url")]
    auth_url: Option<String>,
    #[serde(rename = "expires_at")]
    expires_at: Option<String>,
    #[serde(rename = "connector_type")]
    connector_type: Option<String>,
    #[serde(rename = "tenant_id")]
    tenant_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Credentials {
    #[serde(rename = "client_id")]
    pub client_id: String,
    #[serde(rename = "keycloak_url")]
    pub auth_url: String,
    #[serde(rename = "tenant_id")]
    pub tenant_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kid: Option<String>,
}

#[derive(Debug, Clone)]
struct DirectConfig {
    private_key_path: String,
    client_id: String,
    auth_url: String,
}

pub struct OttProvider {
    api_url: Option<String>,
    keys_dir: PathBuf,
    credentials_dir: PathBuf,
    /// Private key PEM string (RSA PKCS#1, RSA PKCS#8, or EC PKCS#8)
    private_key_pem: Option<String>,
    credentials: Option<Credentials>,
    access_token: Option<String>,
    token_expires_at: Option<u64>,
    connector_type: Option<String>,
    instance_id: Option<String>,
    direct_config: Option<DirectConfig>,
    http_client: Client,
}

impl OttProvider {
    pub fn new(connector_type: Option<String>, instance_id: Option<String>) -> Self {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
        let keys_dir =
            std::env::var("STRIKE48_KEYS_DIR").unwrap_or_else(|_| format!("{home}/.strike48/keys"));
        let credentials_dir = format!("{home}/.strike48/credentials");

        let api_url = std::env::var("STRIKE48_API_URL").ok();

        // Check for direct configuration
        let direct_config = Self::load_direct_config();

        // rustls 0.23 requires a process-level CryptoProvider before any TLS
        // operation. The gRPC transport only installs it in its TLS path; if
        // the SDK is configured for plaintext gRPC (or WS) but later needs to
        // talk to Keycloak over HTTPS during the OTT post-approval flow,
        // reqwest's rustls will fail with no error context. Install the
        // aws-lc-rs provider here so any reqwest::Client we build below can
        // successfully complete a TLS handshake. The call is idempotent —
        // a second installer is silently ignored.
        let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

        let http_client = if std::env::var("MATRIX_TLS_INSECURE")
            .map(|v| v.eq_ignore_ascii_case("true") || v == "1")
            .unwrap_or(false)
        {
            tracing::warn!(
                "TLS certificate verification DISABLED for OTT/Keycloak HTTPS \
                 (MATRIX_TLS_INSECURE=true). Do NOT use in production!"
            );
            Client::builder()
                .danger_accept_invalid_certs(true)
                .build()
                .unwrap_or_else(|_| Client::new())
        } else {
            Client::new()
        };

        Self {
            api_url,
            keys_dir: PathBuf::from(keys_dir),
            credentials_dir: PathBuf::from(credentials_dir),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type,
            instance_id,
            direct_config,
            http_client,
        }
    }

    fn load_direct_config() -> Option<DirectConfig> {
        let private_key_path = std::env::var("STRIKE48_PRIVATE_KEY_PATH")
            .ok()
            .or_else(Self::find_default_private_key)?;

        let client_id = std::env::var("STRIKE48_CLIENT_ID").ok()?;
        let auth_url = std::env::var("STRIKE48_AUTH_URL").ok()?;

        if Path::new(&private_key_path).exists() {
            Some(DirectConfig {
                private_key_path,
                client_id,
                auth_url,
            })
        } else {
            None
        }
    }

    fn find_default_private_key() -> Option<String> {
        for path in DEFAULT_PRIVATE_KEY_PATHS {
            if Path::new(path).exists() {
                return Some(path.to_string());
            }
        }
        None
    }

    pub fn has_direct_config(&self) -> bool {
        self.direct_config.is_some()
    }

    pub fn initialize_from_direct_config(&mut self) -> Result<Credentials> {
        let config = self.direct_config.as_ref().ok_or_else(|| {
            ConnectorError::InvalidConfig("Direct config not available".to_string())
        })?;

        self.private_key_pem = Some(Self::load_private_key_from_path(&config.private_key_path)?);

        let tenant_id = std::env::var("TENANT_ID").map_err(|_| {
            ConnectorError::InvalidConfig(
                "TENANT_ID is required for direct-config auth".to_string(),
            )
        })?;
        let credentials = Credentials {
            client_id: config.client_id.clone(),
            auth_url: config.auth_url.clone(),
            tenant_id,
            kid: None,
        };

        self.credentials = Some(credentials.clone());
        Ok(credentials)
    }

    pub fn has_ott(&self) -> bool {
        self.load_ott().is_some()
    }

    /// Validate that a server-supplied registration URL points at the
    /// configured Matrix API origin (scheme + host + port).
    ///
    /// - When `configured` is `Some` (i.e. `STRIKE48_API_URL` is set),
    ///   the call only succeeds if `target` shares the configured origin.
    /// - When `configured` is `None` (dev / local CLI usage), a `warn!`
    ///   is emitted and validation is skipped. Production deployments
    ///   should always set `STRIKE48_API_URL`.
    pub(crate) fn validate_register_origin(target: &str, configured: Option<&str>) -> Result<()> {
        let configured = match configured {
            Some(c) if !c.trim().is_empty() => c,
            _ => {
                tracing::warn!(
                    "STRIKE48_API_URL is not configured; skipping OTT register-URL \
                     allowlist check (dev only). Set STRIKE48_API_URL in production \
                     to enforce a same-origin policy on server-supplied register URLs."
                );
                return Ok(());
            }
        };

        let target_origin = parse_origin(target).ok_or_else(|| {
            ConnectorError::InvalidConfig(format!(
                "OTT register URL is not a valid HTTP(S) URL: {target}"
            ))
        })?;
        let allowed_origin = parse_origin(configured).ok_or_else(|| {
            ConnectorError::InvalidConfig(format!(
                "STRIKE48_API_URL is not a valid HTTP(S) URL: {configured}"
            ))
        })?;

        if target_origin == allowed_origin {
            Ok(())
        } else {
            Err(ConnectorError::InvalidConfig(format!(
                "OTT register URL origin {target_origin:?} does not match \
                 STRIKE48_API_URL origin {allowed_origin:?}; refusing to send \
                 credentials to an unapproved host"
            )))
        }
    }

    fn load_ott(&self) -> Option<OttData> {
        // Priority 1: Inline environment variable
        if let Ok(ott_value) = std::env::var("STRIKE48_REGISTRATION_TOKEN") {
            return Self::parse_ott(&ott_value);
        }

        // Priority 2: File path from environment
        if let Ok(ott_file) = std::env::var("STRIKE48_REGISTRATION_TOKEN_FILE")
            && Path::new(&ott_file).exists()
        {
            return Self::load_ott_from_file(&ott_file);
        }

        // Priority 3: Default paths
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
        for ott_path in DEFAULT_OTT_PATHS {
            let full_path = if ott_path.starts_with('/') {
                ott_path.to_string()
            } else {
                format!("{home}/{ott_path}")
            };
            if Path::new(&full_path).exists() {
                return Self::load_ott_from_file(&full_path);
            }
        }

        None
    }

    fn load_ott_from_file(file_path: &str) -> Option<OttData> {
        fs::read_to_string(file_path)
            .ok()
            .map(|content| content.trim().to_string())
            .and_then(|content| Self::parse_ott(&content))
    }

    fn parse_ott(value: &str) -> Option<OttData> {
        // Try direct JSON parse first
        if value.starts_with('{') {
            return serde_json::from_str(value).ok();
        }

        // Try base64 decode
        use base64::{Engine as _, engine::general_purpose::STANDARD};
        if let Ok(decoded) = STANDARD.decode(value)
            && let Ok(utf8) = String::from_utf8(decoded)
            && let Ok(ott_data) = serde_json::from_str::<OttData>(&utf8)
        {
            return Some(ott_data);
        }

        // Assume it's just the token string
        Some(OttData {
            token: value.to_string(),
            api_url: None,
            auth_url: None,
            expires_at: None,
            connector_type: None,
            tenant_id: None,
        })
    }

    fn get_private_key_path(&self, connector_type: &str, instance_id: Option<&str>) -> PathBuf {
        let filename = format!(
            "{}_{}.pem",
            connector_type,
            instance_id.unwrap_or("default")
        );
        self.keys_dir.join(filename)
    }

    pub async fn register_with_ott(
        &mut self,
        connector_type: &str,
        instance_id: Option<&str>,
    ) -> Result<Credentials> {
        let ott_data = self
            .load_ott()
            .ok_or_else(|| ConnectorError::InvalidConfig("No OTT found".to_string()))?;

        // Get or generate keypair for private_key_jwt authentication
        let public_key_pem = self
            .get_or_create_keypair_for_connector(connector_type, instance_id)
            .await?;

        // Register with Strike48 API
        let api_url = ott_data
            .api_url
            .as_ref()
            .or(self.api_url.as_ref())
            .ok_or_else(|| ConnectorError::InvalidConfig("API URL not configured".to_string()))?;

        let register_url = format!("{api_url}/api/connectors/register-with-ott");

        // Build payload with public key for private_key_jwt authentication
        let payload = serde_json::json!({
            "token": ott_data.token,
            "public_key": public_key_pem,
            "connector_type": connector_type,
            "instance_id": instance_id,
        });

        let response = self
            .http_client
            .post(&register_url)
            .json(&payload)
            .send()
            .await
            .map_err(|e| ConnectorError::ConnectionError(format!("HTTP request failed: {e}")))?;

        if response.status().is_success() {
            let credentials: Credentials = response.json().await.map_err(|e| {
                ConnectorError::SerializationError(format!("Failed to parse response: {e}"))
            })?;

            self.save_credentials(connector_type, instance_id, &credentials)?;
            self.credentials = Some(credentials.clone());
            Ok(credentials)
        } else if response.status() == 401 {
            Err(ConnectorError::InvalidConfig(
                "Invalid or expired OTT".to_string(),
            ))
        } else {
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());
            Err(ConnectorError::RegistrationError(format!(
                "OTT registration failed: {error_text}"
            )))
        }
    }

    async fn get_or_create_keypair_for_connector(
        &mut self,
        connector_type: &str,
        instance_id: Option<&str>,
    ) -> Result<String> {
        let key_path = self.get_private_key_path(connector_type, instance_id);

        if key_path.exists() {
            let pem = fs::read_to_string(&key_path)
                .map_err(|e| std::io::Error::other(format!("Failed to read private key: {e}")))?;

            // Try to extract EC public key from existing key
            if let Ok(public_key_pem) = Self::extract_ec_public_key_pem(&pem) {
                self.private_key_pem = Some(pem);
                self.connector_type = Some(connector_type.to_string());
                self.instance_id = instance_id.map(|s| s.to_string());
                return Ok(public_key_pem);
            }

            // Legacy RSA key — generate new EC key for re-registration
            tracing::info!(
                "Upgrading legacy RSA key to EC P-256 for connector {}",
                connector_type
            );
        }

        // Generate new EC P-256 keypair
        let (private_pem, public_pem) = Self::generate_ec_keypair()?;

        // Save private key
        if !self.keys_dir.exists() {
            fs::create_dir_all(&self.keys_dir).map_err(|e| {
                std::io::Error::other(format!("Failed to create keys directory: {e}"))
            })?;
        }

        fs::write(&key_path, private_pem.as_bytes())
            .map_err(|e| std::io::Error::other(format!("Failed to write private key: {e}")))?;

        // Set permissions (Unix only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&key_path)?.permissions();
            perms.set_mode(0o600);
            fs::set_permissions(&key_path, perms)?;
        }

        self.private_key_pem = Some(private_pem);
        self.connector_type = Some(connector_type.to_string());
        self.instance_id = instance_id.map(|s| s.to_string());

        Ok(public_pem)
    }

    fn load_private_key_from_path(key_path: &str) -> Result<String> {
        let pem = fs::read_to_string(key_path)
            .map_err(|e| std::io::Error::other(format!("Failed to read private key: {e}")))?;

        // Validate it looks like a PEM key
        if !pem.contains("BEGIN") || !pem.contains("PRIVATE KEY") {
            return Err(ConnectorError::InvalidConfig(
                "File does not contain a PEM private key".to_string(),
            ));
        }

        Ok(pem)
    }

    /// Generate a new EC P-256 keypair, returning (private_pem, public_pem).
    fn generate_ec_keypair() -> Result<(String, String)> {
        use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1_SIGNING, EcdsaKeyPair, KeyPair as _};

        let rng = aws_lc_rs::rand::SystemRandom::new();
        let pkcs8_doc = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng)
            .map_err(|e| ConnectorError::Other(format!("Failed to generate EC keypair: {e}")))?;

        let key_pair =
            EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8_doc.as_ref()).map_err(
                |e| ConnectorError::Other(format!("Failed to parse generated keypair: {e}")),
            )?;

        let private_pem = Self::der_to_pem(pkcs8_doc.as_ref(), "PRIVATE KEY");
        let public_key_bytes = key_pair.public_key().as_ref();
        let spki_der = Self::ec_p256_public_key_to_spki(public_key_bytes);
        let public_pem = Self::der_to_pem(&spki_der, "PUBLIC KEY");

        Ok((private_pem, public_pem))
    }

    /// Try to extract an EC public key PEM from a PKCS#8 private key PEM.
    /// Returns Err if the key is not a valid EC P-256 PKCS#8 key.
    fn extract_ec_public_key_pem(private_key_pem: &str) -> Result<String> {
        use aws_lc_rs::signature::{ECDSA_P256_SHA256_ASN1_SIGNING, EcdsaKeyPair, KeyPair as _};

        let der = Self::pem_to_der(private_key_pem)?;
        let key_pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &der)
            .map_err(|e| ConnectorError::Other(format!("Not a valid EC P-256 key: {e}")))?;

        let public_key_bytes = key_pair.public_key().as_ref();
        let spki_der = Self::ec_p256_public_key_to_spki(public_key_bytes);
        Ok(Self::der_to_pem(&spki_der, "PUBLIC KEY"))
    }

    /// Build the SPKI (SubjectPublicKeyInfo) DER encoding for a P-256 public key.
    fn ec_p256_public_key_to_spki(public_key_bytes: &[u8]) -> Vec<u8> {
        // Fixed ASN.1 prefix for P-256 SPKI:
        //   SEQUENCE { SEQUENCE { OID ecPublicKey, OID P-256 }, BIT STRING { ... } }
        let prefix: &[u8] = &[
            0x30, 0x59, // SEQUENCE (89 bytes)
            0x30, 0x13, // SEQUENCE (19 bytes) — AlgorithmIdentifier
            0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, // OID 1.2.840.10045.2.1
            0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01,
            0x07, // OID 1.2.840.10045.3.1.7
            0x03, 0x42, 0x00, // BIT STRING (66 bytes, 0 unused bits)
        ];
        let mut spki = Vec::with_capacity(prefix.len() + public_key_bytes.len());
        spki.extend_from_slice(prefix);
        spki.extend_from_slice(public_key_bytes);
        spki
    }

    /// Convert DER bytes to PEM format with the given label.
    fn der_to_pem(der: &[u8], label: &str) -> String {
        use base64::{Engine as _, engine::general_purpose::STANDARD};
        let b64 = STANDARD.encode(der);
        let mut pem = format!("-----BEGIN {label}-----\n");
        for chunk in b64.as_bytes().chunks(64) {
            pem.push_str(std::str::from_utf8(chunk).unwrap());
            pem.push('\n');
        }
        pem.push_str(&format!("-----END {label}-----\n"));
        pem
    }

    /// Decode a PEM string to DER bytes (strips headers, base64-decodes).
    fn pem_to_der(pem: &str) -> Result<Vec<u8>> {
        use base64::{Engine as _, engine::general_purpose::STANDARD};
        let b64: String = pem
            .lines()
            .filter(|line| !line.starts_with("-----"))
            .collect();
        STANDARD
            .decode(&b64)
            .map_err(|e| ConnectorError::Other(format!("Failed to decode PEM: {e}")))
    }

    pub fn load_saved_credentials(
        &mut self,
        connector_type: &str,
        instance_id: Option<&str>,
    ) -> Option<Credentials> {
        let filename = format!(
            "{}_{}.json",
            connector_type,
            instance_id.unwrap_or("default")
        );
        let filepath = self.credentials_dir.join(&filename);

        tracing::debug!("Looking for saved credentials at: {}", filepath.display());

        if filepath.exists() {
            tracing::debug!("Credentials file found, loading...");
            if let Ok(data) = fs::read_to_string(&filepath) {
                if let Ok(creds) = serde_json::from_str::<Credentials>(&data) {
                    tracing::debug!(
                        "Loaded credentials from {}: client_id={}",
                        filepath.display(),
                        creds.client_id
                    );
                    self.credentials = Some(creds.clone());
                    return Some(creds);
                } else {
                    tracing::warn!(
                        "Failed to parse credentials JSON from {}",
                        filepath.display()
                    );
                }
            } else {
                tracing::warn!("Failed to read credentials file: {}", filepath.display());
            }
        } else {
            tracing::debug!("Credentials file not found: {}", filepath.display());
        }

        None
    }

    fn save_credentials(
        &self,
        connector_type: &str,
        instance_id: Option<&str>,
        credentials: &Credentials,
    ) -> Result<()> {
        if !self.credentials_dir.exists() {
            fs::create_dir_all(&self.credentials_dir).map_err(|e| {
                std::io::Error::other(format!("Failed to create credentials directory: {e}"))
            })?;
        }

        let filename = format!(
            "{}_{}.json",
            connector_type,
            instance_id.unwrap_or("default")
        );
        let filepath = self.credentials_dir.join(filename);

        let json = serde_json::to_string_pretty(credentials).map_err(|e| {
            ConnectorError::SerializationError(format!("Failed to serialize credentials: {e}"))
        })?;

        fs::write(&filepath, json)
            .map_err(|e| std::io::Error::other(format!("Failed to write credentials: {e}")))?;

        // Credential JSON files contain the Keycloak `client_id` and the
        // tenant the connector authenticates as. They live alongside the
        // private key under `~/.strike48/credentials`; tighten the mode so
        // only the owning user can read them, matching the private key.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = fs::metadata(&filepath)?.permissions();
            perms.set_mode(0o600);
            fs::set_permissions(&filepath, perms)?;
        }

        Ok(())
    }

    pub async fn register_public_key_with_ott_data(
        &mut self,
        ott: &str,
        api_url: &str,
        register_url: &str,
        connector_type: &str,
        instance_id: Option<&str>,
    ) -> Result<Credentials> {
        // Ensure we have a keypair
        let public_key_pem = self
            .get_or_create_keypair_for_connector(connector_type, instance_id)
            .await?;

        // Build full URL
        let full_url = if register_url.starts_with("http") {
            register_url.to_string()
        } else {
            format!("{}{}", api_url.trim_end_matches('/'), register_url)
        };

        // Defence-in-depth: the `matrix_api_url` and `register_url` come
        // from a `CredentialsIssued` server message. If `STRIKE48_API_URL`
        // is configured (it is in production deployments), refuse to dial
        // any host that does not share its origin. Without the allowlist,
        // a compromised or misconfigured server could send the connector
        // its bearer token and public key to an attacker-controlled host.
        let configured_api_url = std::env::var("STRIKE48_API_URL").ok();
        Self::validate_register_origin(&full_url, configured_api_url.as_deref())?;

        tracing::debug!(
            "OTT registration: api_url={}, register_url={}, full_url={}",
            api_url,
            register_url,
            full_url
        );
        tracing::debug!(
            "OTT registration: sending token for connector_type={}",
            connector_type
        );

        let payload = serde_json::json!({
            "token": ott,
            "public_key": public_key_pem,
            "connector_type": connector_type,
            "instance_id": instance_id,
        });

        tracing::debug!(
            "OTT registration payload: connector_type={}, instance_id={:?}",
            connector_type,
            instance_id
        );

        // Retry logic for OTT registration
        // In multi-pod deployments, the OTT is stored in Horde.Registry (CRDT)
        // which may take a few seconds to sync across pods. Retry handles this race.
        const MAX_RETRIES: u32 = 4;
        const INITIAL_DELAY_MS: u64 = 500;
        const MAX_DELAY_MS: u64 = 3000;

        let mut last_error = None;

        for attempt in 0..MAX_RETRIES {
            if attempt > 0 {
                let delay = std::cmp::min(INITIAL_DELAY_MS * 2_u64.pow(attempt - 1), MAX_DELAY_MS);
                tracing::warn!(
                    "OTT registration retry {}/{} after {}ms (waiting for cluster sync)",
                    attempt + 1,
                    MAX_RETRIES,
                    delay
                );
                tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
            }

            let response = match self.http_client.post(&full_url).json(&payload).send().await {
                Ok(resp) => resp,
                Err(e) => {
                    last_error = Some(format!("HTTP request failed: {e}"));
                    continue;
                }
            };

            tracing::debug!(
                "OTT registration response status: {} (attempt {})",
                response.status(),
                attempt + 1
            );

            if response.status().is_success() {
                let credentials: Credentials = response.json().await.map_err(|e| {
                    ConnectorError::SerializationError(format!("Failed to parse response: {e}"))
                })?;

                // Save credentials to disk for persistence across restarts
                self.save_credentials(connector_type, instance_id, &credentials)?;
                self.credentials = Some(credentials.clone());
                return Ok(credentials);
            }

            // Check if it's a retryable error (401 = OTT not found, might be sync delay)
            let status = response.status();
            let error_text = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());

            if status.as_u16() == 401 && error_text.contains("Invalid or expired") {
                // This could be Horde sync delay - retry
                last_error = Some(error_text);
                continue;
            }

            // Non-retryable error
            return Err(ConnectorError::RegistrationError(format!(
                "Post-approval OTT registration failed: {error_text}"
            )));
        }

        // All retries exhausted
        Err(ConnectorError::RegistrationError(format!(
            "Post-approval OTT registration failed after {} retries: {}",
            MAX_RETRIES,
            last_error.unwrap_or_else(|| "Unknown error".to_string())
        )))
    }

    pub async fn get_token(&mut self) -> Result<String> {
        // Check if we have a valid cached token
        if let (Some(token), Some(expires_at)) = (&self.access_token, self.token_expires_at) {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();
            if now < expires_at - 30 {
                return Ok(token.clone());
            }
        }

        let credentials = self
            .credentials
            .as_ref()
            .ok_or_else(|| ConnectorError::InvalidConfig("No credentials available".to_string()))?
            .clone();

        // Use private_key_jwt authentication
        self.get_token_via_private_key_jwt(&credentials).await
    }

    /// Clear the cached access token.
    ///
    /// This should be called when the token is rejected (e.g., 401 from server)
    /// to force a fresh token request on the next get_token() call.
    pub fn clear_token_cache(&mut self) {
        self.access_token = None;
        self.token_expires_at = None;
        tracing::debug!("Token cache cleared");
    }

    /// Delete the saved credentials file from disk for this connector instance.
    ///
    /// Call this when credentials are known to be invalid (e.g. repeated JWT decode
    /// failures) so that the next startup doesn't re-load broken credentials and
    /// enter an infinite auth-failure loop. After calling this, the connector will
    /// fall through to the post-approval flow on the next connection attempt.
    pub fn delete_saved_credentials(&self) {
        if let (Some(connector_type), instance_id) =
            (&self.connector_type, self.instance_id.as_deref())
        {
            let filename = format!(
                "{}_{}.json",
                connector_type,
                instance_id.unwrap_or("default")
            );
            let filepath = self.credentials_dir.join(&filename);
            if filepath.exists() {
                match std::fs::remove_file(&filepath) {
                    Ok(()) => {
                        tracing::info!("Deleted stale credentials file: {}", filepath.display())
                    }
                    Err(e) => tracing::warn!(
                        "Failed to delete stale credentials file {}: {}",
                        filepath.display(),
                        e
                    ),
                }
            }
        }
    }

    /// Reset all in-memory credential and token state.
    ///
    /// Clears loaded credentials, cached access token, and token expiry so the
    /// next `get_token()` call starts from a clean slate. Does not touch disk —
    /// call `delete_saved_credentials()` first if you also want to remove the
    /// persisted file.
    pub fn reset(&mut self) {
        self.credentials = None;
        self.private_key_pem = None;
        self.access_token = None;
        self.token_expires_at = None;
        tracing::debug!("OttProvider state reset");
    }

    /// Check if credentials are loaded (useful for connection state checks).
    #[allow(dead_code)]
    pub fn has_credentials(&self) -> bool {
        self.credentials.is_some()
    }

    async fn get_token_via_private_key_jwt(&mut self, credentials: &Credentials) -> Result<String> {
        // Load private key if not already loaded
        if self.private_key_pem.is_none() {
            if let Some(connector_type) = &self.connector_type {
                let key_path =
                    self.get_private_key_path(connector_type, self.instance_id.as_deref());
                if let Some(key_path_str) = key_path.to_str() {
                    self.private_key_pem = Some(Self::load_private_key_from_path(key_path_str)?);
                } else {
                    return Err(ConnectorError::InvalidConfig(
                        "Invalid key path".to_string(),
                    ));
                }
            } else {
                return Err(ConnectorError::InvalidConfig(
                    "Connector identity not set".to_string(),
                ));
            }
        }

        let private_key_pem = self.private_key_pem.as_ref().ok_or_else(|| {
            ConnectorError::InvalidConfig("Private key not available".to_string())
        })?;

        // Create client assertion JWT
        let client_assertion = self.create_client_assertion(private_key_pem, credentials)?;

        // Exchange for access token
        let token_url = format!(
            "{}/protocol/openid-connect/token",
            credentials.auth_url.trim_end_matches('/')
        );

        let mut params = HashMap::new();
        params.insert("grant_type", "client_credentials");
        params.insert("client_id", &credentials.client_id);
        params.insert(
            "client_assertion_type",
            "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
        );
        params.insert("client_assertion", &client_assertion);

        // Retry with exponential backoff for resilience against transient failures
        let mut last_error = None;
        let mut delay_ms = INITIAL_RETRY_DELAY_MS;

        for attempt in 1..=MAX_RETRIES {
            tracing::debug!(
                "Token request attempt {}/{} to {}",
                attempt,
                MAX_RETRIES,
                token_url
            );

            match self.http_client.post(&token_url).form(&params).send().await {
                Ok(response) => {
                    let status = response.status();
                    if status.is_success() {
                        // Parse and cache the token
                        #[derive(Deserialize)]
                        struct TokenResponse {
                            access_token: String,
                            expires_in: Option<u64>,
                        }

                        match response.json::<TokenResponse>().await {
                            Ok(token_data) => {
                                self.access_token = Some(token_data.access_token.clone());
                                let expires_in = token_data.expires_in.unwrap_or(300);
                                let now = SystemTime::now()
                                    .duration_since(UNIX_EPOCH)
                                    .unwrap()
                                    .as_secs();
                                self.token_expires_at = Some(now + expires_in);
                                tracing::debug!(
                                    "Token obtained successfully, expires in {}s",
                                    expires_in
                                );
                                return Ok(token_data.access_token);
                            }
                            Err(e) => {
                                return Err(ConnectorError::SerializationError(format!(
                                    "Failed to parse token response: {e}"
                                )));
                            }
                        }
                    }
                    // Non-retryable HTTP error (4xx)
                    if status.is_client_error() {
                        let error_text = response
                            .text()
                            .await
                            .unwrap_or_else(|_| "Unknown error".to_string());
                        tracing::error!("Token request rejected ({status}): {error_text}");

                        // Clear token cache on 401 - credentials may have been revoked
                        if status.as_u16() == 401 {
                            self.clear_token_cache();
                            tracing::warn!("Cleared token cache due to 401 Unauthorized");
                        }

                        return Err(ConnectorError::InvalidConfig(format!(
                            "Token request failed ({status}): {error_text}"
                        )));
                    }
                    // Server error (5xx) - retry
                    let error_text = response
                        .text()
                        .await
                        .unwrap_or_else(|_| "Unknown error".to_string());
                    last_error = Some(ConnectorError::ConnectionError(format!(
                        "Token request failed ({status}): {error_text}"
                    )));
                }
                Err(e) => {
                    // Network error - retry. Walk the source chain so the
                    // underlying TLS/TCP/DNS cause isn't hidden by reqwest's
                    // terse Display.
                    use std::error::Error as _;
                    let mut chain = format!("{e}");
                    let mut src: Option<&(dyn std::error::Error + 'static)> = e.source();
                    while let Some(s) = src {
                        chain.push_str(&format!(" -> {s}"));
                        src = s.source();
                    }
                    tracing::debug!("Token request failed (full chain): {chain}");
                    last_error = Some(ConnectorError::ConnectionError(format!(
                        "Token request network error: {chain}"
                    )));
                }
            }

            // Don't sleep after last attempt
            if attempt < MAX_RETRIES {
                tracing::warn!(
                    "Token request failed (attempt {}/{}), retrying in {}ms...",
                    attempt,
                    MAX_RETRIES,
                    delay_ms
                );
                sleep(Duration::from_millis(delay_ms)).await;
                delay_ms = std::cmp::min(delay_ms * 2, MAX_RETRY_DELAY_MS);
            }
        }

        Err(last_error.unwrap_or_else(|| {
            ConnectorError::ConnectionError("Token request failed after all retries".to_string())
        }))
    }

    fn create_client_assertion(
        &self,
        private_key_pem: &str,
        credentials: &Credentials,
    ) -> Result<String> {
        use jsonwebtoken::{Algorithm, EncodingKey, Header, encode};
        use serde_json::json;

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let claims = json!({
            "iss": credentials.client_id,
            "sub": credentials.client_id,
            "aud": credentials.auth_url,
            "exp": now + 60,
            "iat": now,
            "jti": uuid::Uuid::new_v4().to_string(),
        });

        // Detect key type from PEM header and choose appropriate algorithm
        let pem_bytes = private_key_pem.as_bytes();
        let (algorithm, encoding_key) = if private_key_pem.contains("BEGIN RSA PRIVATE KEY") {
            // PKCS#1 RSA key (legacy)
            let key = EncodingKey::from_rsa_pem(pem_bytes)
                .map_err(|e| ConnectorError::Other(format!("Failed to create RSA key: {e}")))?;
            (Algorithm::RS256, key)
        } else if private_key_pem.contains("BEGIN EC PRIVATE KEY") {
            // SEC1 EC key
            let key = EncodingKey::from_ec_pem(pem_bytes)
                .map_err(|e| ConnectorError::Other(format!("Failed to create EC key: {e}")))?;
            (Algorithm::ES256, key)
        } else {
            // PKCS#8 (could be RSA or EC) — try EC first (new default), fall back to RSA
            match EncodingKey::from_ec_pem(pem_bytes) {
                Ok(key) => (Algorithm::ES256, key),
                Err(_) => {
                    let key = EncodingKey::from_rsa_pem(pem_bytes).map_err(|e| {
                        ConnectorError::Other(format!("Failed to create encoding key: {e}"))
                    })?;
                    (Algorithm::RS256, key)
                }
            }
        };

        let mut header = Header::new(algorithm);
        if let Some(ref kid) = credentials.kid {
            header.kid = Some(kid.clone());
        }

        encode(&header, &claims, &encoding_key)
            .map_err(|e| ConnectorError::Other(format!("Failed to sign JWT: {e}")))
    }

    #[allow(dead_code)]
    pub async fn get_auth_token(&mut self) -> Option<String> {
        self.get_token().await.ok()
    }
}

/// Parsed origin: `(scheme, host, port)`. Falls back to the URL crate's
/// default port for the scheme when none is specified, so
/// `https://example.com` and `https://example.com:443` compare equal.
fn parse_origin(s: &str) -> Option<(String, String, u16)> {
    let url = reqwest::Url::parse(s).ok()?;
    let scheme = url.scheme().to_ascii_lowercase();
    if scheme != "http" && scheme != "https" {
        return None;
    }
    let host = url.host_str()?.to_ascii_lowercase();
    let port = url.port_or_known_default()?;
    Some((scheme, host, port))
}

#[cfg(test)]
mod tests {
    use super::*;

    // =========================================================================
    // Register-URL allowlist (validate_register_origin)
    // =========================================================================

    #[test]
    fn validate_register_origin_same_host_passes() {
        OttProvider::validate_register_origin(
            "https://api.matrix.example.com/connectors/v1/register",
            Some("https://api.matrix.example.com"),
        )
        .expect("same origin must pass");
    }

    #[test]
    fn validate_register_origin_default_port_normalised() {
        // https implies :443; explicit and implicit forms must be treated equal.
        OttProvider::validate_register_origin(
            "https://api.matrix.example.com:443/x",
            Some("https://api.matrix.example.com/"),
        )
        .expect("443 == default https port");
    }

    #[test]
    fn validate_register_origin_cross_host_rejected() {
        let err = OttProvider::validate_register_origin(
            "https://attacker.example.com/connectors/v1/register",
            Some("https://api.matrix.example.com"),
        )
        .expect_err("cross-host must be rejected");
        assert!(matches!(err, ConnectorError::InvalidConfig(_)));
    }

    #[test]
    fn validate_register_origin_scheme_mismatch_rejected() {
        // http→https is a downgrade attack the connector must refuse even
        // when host matches.
        let err = OttProvider::validate_register_origin(
            "http://api.matrix.example.com/x",
            Some("https://api.matrix.example.com"),
        )
        .expect_err("scheme mismatch must be rejected");
        assert!(matches!(err, ConnectorError::InvalidConfig(_)));
    }

    #[test]
    fn validate_register_origin_port_mismatch_rejected() {
        let err = OttProvider::validate_register_origin(
            "https://api.matrix.example.com:8443/x",
            Some("https://api.matrix.example.com"),
        )
        .expect_err("port mismatch must be rejected");
        assert!(matches!(err, ConnectorError::InvalidConfig(_)));
    }

    #[test]
    fn validate_register_origin_no_allowlist_skips() {
        // STRIKE48_API_URL unset → permissive (with a warn!) for dev
        // ergonomics. Production deployments must set the env var.
        OttProvider::validate_register_origin("https://api.example.com/x", None)
            .expect("no allowlist => allow");
        OttProvider::validate_register_origin("https://api.example.com/x", Some("   "))
            .expect("blank allowlist => allow");
    }

    #[test]
    fn validate_register_origin_invalid_target_rejected() {
        let err =
            OttProvider::validate_register_origin("not a url", Some("https://api.example.com"))
                .expect_err("malformed URL must be rejected");
        assert!(matches!(err, ConnectorError::InvalidConfig(_)));
    }

    // =========================================================================
    // Credential file permissions (save_credentials)
    // =========================================================================

    #[cfg(unix)]
    #[test]
    fn save_credentials_writes_file_with_mode_0600() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().expect("tempdir");
        let provider = OttProvider {
            api_url: None,
            keys_dir: tmp.path().join("keys"),
            credentials_dir: tmp.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("perm_test".into()),
            instance_id: Some("inst_a".into()),
            direct_config: None,
            http_client: Client::new(),
        };
        let credentials = Credentials {
            client_id: "ci-1".into(),
            auth_url: "https://auth.example.com".into(),
            tenant_id: "demo".into(),
            kid: None,
        };
        provider
            .save_credentials("perm_test", Some("inst_a"), &credentials)
            .expect("save_credentials");
        let path = tmp.path().join("creds").join("perm_test_inst_a.json");
        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
        // POSIX permission bits live in the low 9; mask off any sticky/setuid.
        assert_eq!(
            mode & 0o777,
            0o600,
            "credential file must be owner-only readable, got mode={mode:o}"
        );
    }

    // =========================================================================
    // OTT parsing (parse_ott)
    // =========================================================================

    #[test]
    fn test_parse_ott_raw_token_string() {
        let result = OttProvider::parse_ott("ott_hXg1Adwu12345");
        assert!(result.is_some());
        let ott = result.unwrap();
        assert_eq!(ott.token, "ott_hXg1Adwu12345");
        assert!(ott.api_url.is_none());
        assert!(ott.auth_url.is_none());
        assert!(ott.expires_at.is_none());
    }

    #[test]
    fn test_parse_ott_json_inline() {
        let json_str = r#"{"token":"ott_abc123","matrix_url":"https://api.example.com","keycloak_url":"https://auth.example.com/realms/matrix"}"#;
        let result = OttProvider::parse_ott(json_str);
        assert!(result.is_some());
        let ott = result.unwrap();
        assert_eq!(ott.token, "ott_abc123");
        assert_eq!(ott.api_url.as_deref(), Some("https://api.example.com"));
        assert_eq!(
            ott.auth_url.as_deref(),
            Some("https://auth.example.com/realms/matrix")
        );
    }

    #[test]
    fn test_parse_ott_json_with_all_fields() {
        let json_str = r#"{
            "token": "ott_full",
            "matrix_url": "https://api.example.com",
            "keycloak_url": "https://auth.example.com",
            "expires_at": "2026-12-31T23:59:59Z",
            "connector_type": "my-connector",
            "tenant_id": "tenant-1"
        }"#;
        let result = OttProvider::parse_ott(json_str);
        assert!(result.is_some());
        let ott = result.unwrap();
        assert_eq!(ott.token, "ott_full");
        assert_eq!(ott.connector_type.as_deref(), Some("my-connector"));
        assert_eq!(ott.tenant_id.as_deref(), Some("tenant-1"));
        assert_eq!(ott.expires_at.as_deref(), Some("2026-12-31T23:59:59Z"));
    }

    #[test]
    fn test_parse_ott_base64_encoded_json() {
        use base64::{Engine as _, engine::general_purpose::STANDARD};
        let json_str = r#"{"token":"ott_b64","matrix_url":"https://api.test.com"}"#;
        let encoded = STANDARD.encode(json_str.as_bytes());
        let result = OttProvider::parse_ott(&encoded);
        assert!(result.is_some());
        let ott = result.unwrap();
        assert_eq!(ott.token, "ott_b64");
        assert_eq!(ott.api_url.as_deref(), Some("https://api.test.com"));
    }

    #[test]
    fn test_parse_ott_empty_string() {
        let result = OttProvider::parse_ott("");
        assert!(result.is_some());
        let ott = result.unwrap();
        assert_eq!(ott.token, "");
    }

    #[test]
    fn test_parse_ott_json_missing_token_fails() {
        let json_str = r#"{"matrix_url":"https://api.example.com"}"#;
        let result = OttProvider::parse_ott(json_str);
        // serde will fail because "token" is required
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_ott_json_minimal() {
        let json_str = r#"{"token":"ott_min"}"#;
        let result = OttProvider::parse_ott(json_str);
        assert!(result.is_some());
        let ott = result.unwrap();
        assert_eq!(ott.token, "ott_min");
        assert!(ott.api_url.is_none());
    }

    // =========================================================================
    // EC key generation and PEM round-tripping
    // =========================================================================

    #[tokio::test]
    async fn test_keypair_generation_and_pem_roundtrip() {
        let temp_dir = tempfile::tempdir().unwrap();
        let keys_dir = temp_dir.path().join("keys");

        let mut provider = OttProvider {
            api_url: None,
            keys_dir,
            credentials_dir: temp_dir.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("test-connector".to_string()),
            instance_id: Some("test-instance".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        // Generate keypair
        let public_key_pem = provider
            .get_or_create_keypair_for_connector("test-connector", Some("test-instance"))
            .await
            .unwrap();

        // Verify the public key PEM is valid SPKI format
        assert!(public_key_pem.contains("BEGIN PUBLIC KEY"));
        assert!(public_key_pem.contains("END PUBLIC KEY"));

        // Verify private key was stored in memory
        assert!(provider.private_key_pem.is_some());

        // Verify private key file was written to disk
        let key_path = provider.get_private_key_path("test-connector", Some("test-instance"));
        assert!(key_path.exists());

        // Verify the file contains PKCS#8 EC PEM
        let key_data = std::fs::read_to_string(&key_path).unwrap();
        assert!(key_data.contains("BEGIN PRIVATE KEY"));

        // Verify round-trip: load key from file and extract same public key
        let loaded_pem =
            OttProvider::load_private_key_from_path(key_path.to_str().unwrap()).unwrap();
        let loaded_pub_pem = OttProvider::extract_ec_public_key_pem(&loaded_pem).unwrap();
        assert_eq!(public_key_pem, loaded_pub_pem);
    }

    #[tokio::test]
    async fn test_keypair_reuse_on_second_call() {
        let temp_dir = tempfile::tempdir().unwrap();
        let keys_dir = temp_dir.path().join("keys");

        let mut provider = OttProvider {
            api_url: None,
            keys_dir,
            credentials_dir: temp_dir.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("test-connector".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        // First call generates
        let pub1 = provider
            .get_or_create_keypair_for_connector("test-connector", Some("inst"))
            .await
            .unwrap();

        // Clear in-memory key to force reload from disk
        provider.private_key_pem = None;

        // Second call loads from disk
        let pub2 = provider
            .get_or_create_keypair_for_connector("test-connector", Some("inst"))
            .await
            .unwrap();

        // Should be the same key
        assert_eq!(pub1, pub2);
    }

    #[test]
    fn test_private_key_path_format() {
        let provider = OttProvider::new(Some("my-type".to_string()), Some("my-inst".to_string()));
        let path = provider.get_private_key_path("my-type", Some("my-inst"));
        let filename = path.file_name().unwrap().to_str().unwrap();
        assert_eq!(filename, "my-type_my-inst.pem");
    }

    #[test]
    fn test_private_key_path_default_instance() {
        let provider = OttProvider::new(Some("my-type".to_string()), None);
        let path = provider.get_private_key_path("my-type", None);
        let filename = path.file_name().unwrap().to_str().unwrap();
        assert_eq!(filename, "my-type_default.pem");
    }

    // =========================================================================
    // Credential save/load persistence
    // =========================================================================

    #[test]
    fn test_save_and_load_credentials() {
        let temp_dir = tempfile::tempdir().unwrap();
        let creds_dir = temp_dir.path().join("credentials");

        let mut provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: creds_dir.clone(),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("cred-test".to_string()),
            instance_id: Some("inst-1".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        let creds = Credentials {
            client_id: "client-abc".to_string(),
            auth_url: "https://auth.example.com/realms/matrix".to_string(),
            tenant_id: "tenant-1".to_string(),
            kid: None,
        };

        // Save
        provider
            .save_credentials("cred-test", Some("inst-1"), &creds)
            .unwrap();

        // Verify file exists
        let filepath = creds_dir.join("cred-test_inst-1.json");
        assert!(filepath.exists());

        // Verify file contents are valid JSON
        let file_content = std::fs::read_to_string(&filepath).unwrap();
        let parsed: Credentials = serde_json::from_str(&file_content).unwrap();
        assert_eq!(parsed.client_id, "client-abc");
        assert_eq!(parsed.auth_url, "https://auth.example.com/realms/matrix");
        assert_eq!(parsed.tenant_id, "tenant-1");

        // Load back via the provider
        let loaded = provider.load_saved_credentials("cred-test", Some("inst-1"));
        assert!(loaded.is_some());
        let loaded = loaded.unwrap();
        assert_eq!(loaded.client_id, "client-abc");
        assert_eq!(loaded.auth_url, "https://auth.example.com/realms/matrix");
        assert_eq!(loaded.tenant_id, "tenant-1");
    }

    #[test]
    fn test_load_credentials_not_found() {
        let temp_dir = tempfile::tempdir().unwrap();
        let mut provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: temp_dir.path().join("credentials"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("missing".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        let loaded = provider.load_saved_credentials("missing", Some("inst"));
        assert!(loaded.is_none());
    }

    #[test]
    fn test_load_credentials_default_instance() {
        let temp_dir = tempfile::tempdir().unwrap();
        let creds_dir = temp_dir.path().join("credentials");

        let mut provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: creds_dir,
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("test".to_string()),
            instance_id: None,
            direct_config: None,
            http_client: Client::new(),
        };

        let creds = Credentials {
            client_id: "default-client".to_string(),
            auth_url: "https://auth.example.com".to_string(),
            tenant_id: "default".to_string(),
            kid: None,
        };

        provider.save_credentials("test", None, &creds).unwrap();
        let loaded = provider.load_saved_credentials("test", None);
        assert!(loaded.is_some());
        assert_eq!(loaded.unwrap().client_id, "default-client");
    }

    #[test]
    fn test_delete_saved_credentials() {
        let temp_dir = tempfile::tempdir().unwrap();
        let creds_dir = temp_dir.path().join("credentials");

        let provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: creds_dir.clone(),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("del-test".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        // Save credentials first
        provider
            .save_credentials(
                "del-test",
                Some("inst"),
                &Credentials {
                    client_id: "to-delete".to_string(),
                    auth_url: "https://auth.example.com".to_string(),
                    tenant_id: "t".to_string(),
                    kid: None,
                },
            )
            .unwrap();

        let filepath = creds_dir.join("del-test_inst.json");
        assert!(filepath.exists());

        // Delete
        provider.delete_saved_credentials();
        assert!(!filepath.exists());
    }

    #[test]
    fn test_delete_saved_credentials_nonexistent_is_noop() {
        let temp_dir = tempfile::tempdir().unwrap();
        let provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: temp_dir.path().join("credentials"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("nope".to_string()),
            instance_id: Some("nope".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        // Should not panic
        provider.delete_saved_credentials();
    }

    // =========================================================================
    // Token cache management
    // =========================================================================

    #[test]
    fn test_clear_token_cache() {
        let mut provider = OttProvider::new(Some("test".to_string()), Some("inst".to_string()));
        provider.access_token = Some("cached-token".to_string());
        provider.token_expires_at = Some(9999999999);

        provider.clear_token_cache();

        assert!(provider.access_token.is_none());
        assert!(provider.token_expires_at.is_none());
    }

    #[test]
    fn test_reset_clears_all_state() {
        let mut provider = OttProvider::new(Some("test".to_string()), Some("inst".to_string()));
        provider.access_token = Some("token".to_string());
        provider.token_expires_at = Some(123);
        provider.credentials = Some(Credentials {
            client_id: "c".to_string(),
            auth_url: "a".to_string(),
            tenant_id: "t".to_string(),
            kid: None,
        });

        provider.reset();

        assert!(provider.access_token.is_none());
        assert!(provider.token_expires_at.is_none());
        assert!(provider.credentials.is_none());
        assert!(provider.private_key_pem.is_none());
    }

    // =========================================================================
    // JWT client assertion creation (the jsonwebtoken API surface)
    // =========================================================================

    #[tokio::test]
    async fn test_create_client_assertion_produces_valid_jwt() {
        let temp_dir = tempfile::tempdir().unwrap();
        let mut provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: temp_dir.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("jwt-test".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        // Generate a keypair
        provider
            .get_or_create_keypair_for_connector("jwt-test", Some("inst"))
            .await
            .unwrap();

        let private_key_pem = provider.private_key_pem.as_ref().unwrap();
        let credentials = Credentials {
            client_id: "test-client-id".to_string(),
            auth_url: "https://auth.example.com/realms/matrix".to_string(),
            tenant_id: "test-tenant".to_string(),
            kid: None,
        };

        let jwt = provider
            .create_client_assertion(private_key_pem, &credentials)
            .unwrap();

        // JWT should have 3 parts (header.payload.signature)
        let parts: Vec<&str> = jwt.split('.').collect();
        assert_eq!(parts.len(), 3, "JWT should have 3 dot-separated parts");

        // Decode header to verify algorithm
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
        let header_bytes = URL_SAFE_NO_PAD.decode(parts[0]).unwrap();
        let header: serde_json::Value = serde_json::from_slice(&header_bytes).unwrap();
        assert_eq!(header["alg"], "ES256");
        assert_eq!(header["typ"], "JWT");

        // Decode payload to verify claims
        let payload_bytes = URL_SAFE_NO_PAD.decode(parts[1]).unwrap();
        let claims: serde_json::Value = serde_json::from_slice(&payload_bytes).unwrap();
        assert_eq!(claims["iss"], "test-client-id");
        assert_eq!(claims["sub"], "test-client-id");
        assert_eq!(claims["aud"], "https://auth.example.com/realms/matrix");
        assert!(claims["exp"].is_number());
        assert!(claims["iat"].is_number());
        assert!(claims["jti"].is_string());

        // Verify exp is ~60s after iat
        let iat = claims["iat"].as_u64().unwrap();
        let exp = claims["exp"].as_u64().unwrap();
        assert_eq!(exp - iat, 60);

        // Verify jti is a valid UUID
        let jti = claims["jti"].as_str().unwrap();
        assert!(uuid::Uuid::parse_str(jti).is_ok());
    }

    #[tokio::test]
    async fn test_create_client_assertion_signature_is_verifiable() {
        let temp_dir = tempfile::tempdir().unwrap();
        let mut provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: temp_dir.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("verify-test".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        let public_key_pem = provider
            .get_or_create_keypair_for_connector("verify-test", Some("inst"))
            .await
            .unwrap();

        let private_key_pem = provider.private_key_pem.as_ref().unwrap();
        let credentials = Credentials {
            client_id: "verify-client".to_string(),
            auth_url: "https://auth.example.com".to_string(),
            tenant_id: "t".to_string(),
            kid: None,
        };

        let jwt = provider
            .create_client_assertion(private_key_pem, &credentials)
            .unwrap();

        // Verify the JWT signature using the EC public key
        use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
        let decoding_key = DecodingKey::from_ec_pem(public_key_pem.as_bytes()).unwrap();
        let mut validation = Validation::new(Algorithm::ES256);
        validation.set_audience(&["https://auth.example.com"]);
        validation.set_issuer(&["verify-client"]);
        validation.sub = Some("verify-client".to_string());

        let decoded = decode::<serde_json::Value>(&jwt, &decoding_key, &validation);
        assert!(
            decoded.is_ok(),
            "JWT signature verification failed: {:?}",
            decoded.err()
        );
    }

    #[tokio::test]
    async fn test_create_two_assertions_have_different_jti() {
        let temp_dir = tempfile::tempdir().unwrap();
        let mut provider = OttProvider {
            api_url: None,
            keys_dir: temp_dir.path().join("keys"),
            credentials_dir: temp_dir.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("jti-test".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        provider
            .get_or_create_keypair_for_connector("jti-test", Some("inst"))
            .await
            .unwrap();

        let private_key_pem = provider.private_key_pem.as_ref().unwrap();
        let credentials = Credentials {
            client_id: "c".to_string(),
            auth_url: "a".to_string(),
            tenant_id: "t".to_string(),
            kid: None,
        };

        let jwt1 = provider
            .create_client_assertion(private_key_pem, &credentials)
            .unwrap();
        let jwt2 = provider
            .create_client_assertion(private_key_pem, &credentials)
            .unwrap();

        // Different JTI means different tokens (replay protection)
        assert_ne!(jwt1, jwt2);
    }

    // =========================================================================
    // Legacy RSA key backward compatibility
    // =========================================================================

    #[tokio::test]
    async fn test_legacy_rsa_key_signs_jwt_with_rs256() {
        // Simulate a legacy RSA PKCS#1 key loaded from disk via direct config
        // Generate a temporary RSA key using jsonwebtoken's test infrastructure
        let rsa_pem = include_str!("../../test_fixtures/legacy_rsa_key.pem");

        let provider = OttProvider::new(Some("test".to_string()), None);
        let credentials = Credentials {
            client_id: "legacy-client".to_string(),
            auth_url: "https://auth.example.com".to_string(),
            tenant_id: "t".to_string(),
            kid: None,
        };

        let jwt = provider
            .create_client_assertion(rsa_pem, &credentials)
            .unwrap();

        // Verify it used RS256
        use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
        let parts: Vec<&str> = jwt.split('.').collect();
        let header_bytes = URL_SAFE_NO_PAD.decode(parts[0]).unwrap();
        let header: serde_json::Value = serde_json::from_slice(&header_bytes).unwrap();
        assert_eq!(header["alg"], "RS256");
    }

    #[tokio::test]
    async fn test_legacy_rsa_key_upgraded_on_re_registration() {
        let temp_dir = tempfile::tempdir().unwrap();
        let keys_dir = temp_dir.path().join("keys");
        fs::create_dir_all(&keys_dir).unwrap();

        // Write a legacy RSA key to disk
        let rsa_pem = include_str!("../../test_fixtures/legacy_rsa_key.pem");
        let key_path = keys_dir.join("upgrade-test_inst.pem");
        fs::write(&key_path, rsa_pem).unwrap();

        let mut provider = OttProvider {
            api_url: None,
            keys_dir,
            credentials_dir: temp_dir.path().join("creds"),
            private_key_pem: None,
            credentials: None,
            access_token: None,
            token_expires_at: None,
            connector_type: Some("upgrade-test".to_string()),
            instance_id: Some("inst".to_string()),
            direct_config: None,
            http_client: Client::new(),
        };

        // Re-registration should generate a new EC key
        let public_key_pem = provider
            .get_or_create_keypair_for_connector("upgrade-test", Some("inst"))
            .await
            .unwrap();

        assert!(public_key_pem.contains("BEGIN PUBLIC KEY"));
        // The private key on disk should now be EC PKCS#8
        let new_key_data = fs::read_to_string(&key_path).unwrap();
        assert!(new_key_data.contains("BEGIN PRIVATE KEY"));
        assert!(!new_key_data.contains("RSA"));
    }

    // =========================================================================
    // Token caching behavior
    // =========================================================================

    #[tokio::test]
    async fn test_get_token_returns_cached_when_valid() {
        let mut provider = OttProvider::new(Some("test".to_string()), Some("inst".to_string()));
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        provider.access_token = Some("cached-jwt".to_string());
        provider.token_expires_at = Some(now + 120); // expires in 2 minutes
        provider.credentials = Some(Credentials {
            client_id: "c".to_string(),
            auth_url: "a".to_string(),
            tenant_id: "t".to_string(),
            kid: None,
        });

        // Should return cached token without hitting Keycloak
        let token = provider.get_token().await.unwrap();
        assert_eq!(token, "cached-jwt");
    }

    #[tokio::test]
    async fn test_get_token_expired_cache_triggers_refresh() {
        let mut provider = OttProvider::new(Some("test".to_string()), Some("inst".to_string()));
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        provider.access_token = Some("expired-jwt".to_string());
        provider.token_expires_at = Some(now + 10); // expires in 10s, but 30s buffer means "expired"
        provider.credentials = Some(Credentials {
            client_id: "c".to_string(),
            auth_url: "https://auth.invalid.test".to_string(),
            tenant_id: "t".to_string(),
            kid: None,
        });

        // Should try to refresh (and fail since no real Keycloak)
        let result = provider.get_token().await;
        assert!(
            result.is_err(),
            "Should fail trying to refresh expired token"
        );
    }

    // =========================================================================
    // Direct config detection
    // =========================================================================

    #[test]
    fn test_has_direct_config_false_by_default() {
        // SAFETY: test-only env cleanup
        unsafe {
            std::env::remove_var("STRIKE48_PRIVATE_KEY_PATH");
            std::env::remove_var("STRIKE48_CLIENT_ID");
            std::env::remove_var("STRIKE48_AUTH_URL");
        }
        let provider = OttProvider::new(Some("test".to_string()), None);
        assert!(!provider.has_direct_config());
    }

    // =========================================================================
    // Credentials serialization format
    // =========================================================================

    #[test]
    fn test_credentials_json_field_names() {
        let creds = Credentials {
            client_id: "cid".to_string(),
            auth_url: "https://auth.example.com".to_string(),
            tenant_id: "tid".to_string(),
            kid: None,
        };
        let json = serde_json::to_value(&creds).unwrap();

        // Verify field names match what Matrix server expects
        assert!(json.get("client_id").is_some());
        assert!(json.get("keycloak_url").is_some()); // Note: serialized as keycloak_url
        assert!(json.get("tenant_id").is_some());
        assert_eq!(json["client_id"], "cid");
        assert_eq!(json["keycloak_url"], "https://auth.example.com");
        assert_eq!(json["tenant_id"], "tid");
    }

    #[test]
    fn test_credentials_deserialization_from_server_format() {
        // Simulate what the /api/connectors/register-with-ott endpoint returns
        let server_json = r#"{
            "client_id": "connector-client-abc",
            "keycloak_url": "https://keycloak.example.com/realms/matrix",
            "tenant_id": "production"
        }"#;
        let creds: Credentials = serde_json::from_str(server_json).unwrap();
        assert_eq!(creds.client_id, "connector-client-abc");
        assert_eq!(creds.auth_url, "https://keycloak.example.com/realms/matrix");
        assert_eq!(creds.tenant_id, "production");
    }

    // =========================================================================
    // OTT data serialization
    // =========================================================================

    #[test]
    fn test_ott_data_json_field_names() {
        let ott = OttData {
            token: "ott_test".to_string(),
            api_url: Some("https://api.example.com".to_string()),
            auth_url: Some("https://auth.example.com".to_string()),
            expires_at: Some("2026-12-31".to_string()),
            connector_type: Some("my-conn".to_string()),
            tenant_id: Some("t1".to_string()),
        };
        let json = serde_json::to_value(&ott).unwrap();

        // Verify field names match what the pre-approve endpoint produces
        assert_eq!(json["token"], "ott_test");
        assert_eq!(json["matrix_url"], "https://api.example.com");
        assert_eq!(json["keycloak_url"], "https://auth.example.com");
        assert_eq!(json["expires_at"], "2026-12-31");
        assert_eq!(json["connector_type"], "my-conn");
        assert_eq!(json["tenant_id"], "t1");
    }

    #[test]
    fn test_ott_data_deserialization_from_server_format() {
        let server_json = r#"{
            "token": "ott_from_server",
            "matrix_url": "https://matrix.prod.example.com",
            "keycloak_url": "https://auth.prod.example.com/realms/matrix"
        }"#;
        let ott: OttData = serde_json::from_str(server_json).unwrap();
        assert_eq!(ott.token, "ott_from_server");
        assert_eq!(
            ott.api_url.as_deref(),
            Some("https://matrix.prod.example.com")
        );
        assert_eq!(
            ott.auth_url.as_deref(),
            Some("https://auth.prod.example.com/realms/matrix")
        );
    }
}