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
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
//! Infisical provider
//!
//! This provider integrates with [Infisical](https://infisical.com) to store and
//! retrieve secrets over its REST API, against both Infisical Cloud and
//! self-hosted instances.
//!
//! # Authentication
//!
//! A machine identity's `client_id` and `client_secret` are exchanged for a
//! short-lived access token via Universal Auth, cached for the life of the
//! process. A `token` minted elsewhere is used directly instead, which is what
//! CI usually has to hand. Credentials come from the provider alias or from
//! `INFISICAL_CLIENT_ID` / `INFISICAL_CLIENT_SECRET` / `INFISICAL_TOKEN`.
//!
//! Service tokens are not supported: Infisical deprecated them in favour of
//! machine identities.
//!
//! # URI Format
//!
//! `infisical://[host]/{project-id}[?env=slug&path=/prefix&tls=false]`
//!
//! The project is Infisical's own project UUID; its v4 API does not accept a
//! project slug. Query parameters:
//!
//! - `env` -- environment slug. When omitted, the SecretSpec profile names the
//! environment, so a `production` profile reads Infisical's `production`
//! environment. That holds for a `ref` too (0.20+), which names a folder and
//! key but never an environment. Set it to read every profile from one
//! environment, e.g. an instance whose environments do not correspond to
//! profiles.
//! - `path` -- folder prefix holding SecretSpec's secrets (default:
//! `/secretspec`).
//! - `tls` -- enable TLS: `true` (default) or `false`, for self-hosted
//! instances served over plain HTTP.
//!
//! When no host is given, falls back to `INFISICAL_DOMAIN`, then to Infisical's
//! legacy `INFISICAL_API_URL`, then to `app.infisical.com`.
//!
//! # Examples
//!
//! - `infisical://app.infisical.com/7e2f...` -- Infisical Cloud (US)
//! - `infisical://eu.infisical.com/7e2f...` -- Infisical Cloud (EU)
//! - `infisical://vault.example.com/7e2f...?env=prod` -- pin one environment
//! - `infisical://localhost:8080/7e2f...?tls=false` -- self-hosted, plain HTTP
//!
//! # Secret Naming
//!
//! A secret lives at the folder `{path}/{project}/{profile}` in the
//! environment named by the profile, under the key itself:
//!
//! ```text
//! project "myapp", profile "prod", key "DATABASE_URL"
//! -> environment prod
//! secretPath /secretspec/myapp/prod
//! secretKey DATABASE_URL
//! ```
//!
//! The profile names the folder as well as the environment, so that pinning
//! `?env=` moves every profile into one environment without two of them
//! landing on the same secret.
//!
//! Keys are stored verbatim: Infisical imposes no charset of its own, so no
//! rewriting is needed and distinct keys cannot collide. Folder names are
//! narrower, so a project or profile Infisical cannot spell is refused rather
//! than rewritten.
//!
//! A folder that imports another resolves the imported keys too, with
//! Infisical's own precedence: a secret defined directly in the folder wins
//! over an imported one, and a later import wins over an earlier one.
//!
//! Starting in 0.20, an all-missing read probes the environment root once to
//! distinguish an absent environment or project from ordinary absent secrets
//! and folders. The resulting error names the environment and whether the
//! profile or `?env=` selected it.
use super::{
Address, Provider, ProviderCredentials, ProviderUrl, credential_or_env, join_slash_path,
};
use crate::config::NativeAddress;
use crate::{Result, SecretSpecError};
use reqwest::StatusCode;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::{Mutex, OnceLock};
/// Default folder prefix holding SecretSpec's secrets.
const DEFAULT_PATH: &str = "/secretspec";
/// Infisical Cloud's US host, used when neither the URI nor the environment
/// names one.
const DEFAULT_HOST: &str = "app.infisical.com";
const CLIENT_ID: &str = "client_id";
const CLIENT_SECRET: &str = "client_secret";
const TOKEN: &str = "token";
const INFISICAL_CLIENT_ID_ENV: &str = "INFISICAL_CLIENT_ID";
const INFISICAL_CLIENT_SECRET_ENV: &str = "INFISICAL_CLIENT_SECRET";
const INFISICAL_TOKEN_ENV: &str = "INFISICAL_TOKEN";
/// The environment variables naming the instance, in the Infisical CLI's own
/// precedence order: `INFISICAL_DOMAIN` first, then the legacy
/// `INFISICAL_API_URL` it superseded but still honours (`util.GetEnvDomain`).
/// Reading only the current name would silently send an existing EU or
/// self-hosted setup, configured with the legacy one, to US Cloud.
const INFISICAL_DOMAIN_ENVS: [&str; 2] = ["INFISICAL_DOMAIN", "INFISICAL_API_URL"];
/// Configuration for the Infisical provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InfisicalConfig {
/// The Infisical API endpoint (e.g. `https://app.infisical.com`).
pub endpoint: String,
/// The Infisical project UUID.
pub project_id: String,
/// Environment slug. When `None`, the profile names the environment.
pub environment: Option<String>,
/// Folder prefix holding SecretSpec's secrets.
pub path: String,
}
impl Default for InfisicalConfig {
fn default() -> Self {
Self {
endpoint: format!("https://{DEFAULT_HOST}"),
project_id: String::new(),
environment: None,
path: DEFAULT_PATH.to_string(),
}
}
}
impl InfisicalConfig {
/// Reads `INFISICAL_DOMAIN` into an endpoint.
///
/// The URI names a host, so the endpoint is a host too: a domain carrying
/// a path is refused rather than accepted into a config that
/// [`uri`](Provider::uri) could not render back.
///
/// A trailing `/api` is the exception, and is dropped rather than refused.
/// Infisical's own CLI appends `/api` to the domain unless it is already
/// there, so the suffix is common in a working configuration -- one that
/// SecretSpec should read the same way, since it appends `/api` too.
fn endpoint_from_domain(var: &str, domain: &str, http_scheme: &str) -> Result<String> {
let domain = domain.trim_end_matches('/');
let domain = domain.strip_suffix("/api").unwrap_or(domain);
let absolute = if domain.starts_with("http://") || domain.starts_with("https://") {
domain.to_string()
} else {
format!("{http_scheme}://{domain}")
};
let parsed = url::Url::parse(&absolute).map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!("Invalid {var} '{domain}': {e}"))
})?;
if !parsed.path().trim_matches('/').is_empty() {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Invalid {var} '{domain}': it names a path. Infisical's \
API is addressed at the host, e.g. https://vault.example.com."
)));
}
Ok(absolute)
}
/// The instance named by the environment, with the variable that named it
/// so an error can report the one the user actually set.
fn env_domain() -> Option<(&'static str, String)> {
Self::pick_domain(|var| std::env::var(var).ok())
}
/// The first variable in [`INFISICAL_DOMAIN_ENVS`] that names an instance.
///
/// Trimmed and empty-filtered to match the CLI's `GetEnvDomain`, so a blank
/// variable falls through to the next rather than being taken as a domain.
/// Split from [`env_domain`](Self::env_domain) so the precedence is
/// testable without mutating the process environment.
fn pick_domain(lookup: impl Fn(&str) -> Option<String>) -> Option<(&'static str, String)> {
INFISICAL_DOMAIN_ENVS.iter().find_map(|var| {
let value = lookup(var)?;
let value = value.trim().to_string();
(!value.is_empty()).then_some((*var, value))
})
}
}
impl TryFrom<&ProviderUrl> for InfisicalConfig {
type Error = SecretSpecError;
fn try_from(url: &ProviderUrl) -> std::result::Result<Self, Self::Error> {
let scheme = url.scheme();
if scheme != "infisical" {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Invalid scheme '{scheme}' for infisical provider. Expected 'infisical'."
)));
}
// An unreadable `tls` is refused rather than read as one of its two
// meanings: the knob is explicit, so a typo in it should be too.
let use_tls = url
.query_pairs()
.find(|(k, _)| k == "tls")
.map(|(_, v)| match v.as_ref() {
"true" | "1" => Ok(true),
"false" | "0" => Ok(false),
other => Err(SecretSpecError::ProviderOperationFailed(format!(
"Unknown tls value '{other}'. Expected 'true' or 'false'."
))),
})
.transpose()?
.unwrap_or(true);
let http_scheme = if use_tls { "https" } else { "http" };
// Host from the URI, else the environment, else Infisical Cloud.
let endpoint = match url.host().filter(|s| !s.is_empty()) {
Some(host) => match url.port() {
Some(port) => format!("{http_scheme}://{host}:{port}"),
None => format!("{http_scheme}://{host}"),
},
// The domain is a full URL in Infisical's own CLI.
None => match Self::env_domain() {
Some((var, domain)) => Self::endpoint_from_domain(var, &domain, http_scheme)?,
None => format!("{http_scheme}://{DEFAULT_HOST}"),
},
};
// The project UUID is the URI path; Infisical's v4 API has no slug form.
let project_id = url.path().trim_matches('/').to_string();
if project_id.is_empty() {
return Err(SecretSpecError::ProviderOperationFailed(
"No Infisical project given. Name the project UUID in the URI, e.g. \
infisical://app.infisical.com/7e2f1a4c-.... Infisical's API takes the \
project's UUID (Project Settings -> Project ID), not its slug."
.to_string(),
));
}
if project_id.contains('/') {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Invalid Infisical project '{project_id}': expected a single project UUID. \
The folder holding the secrets is set with `?path=` instead."
)));
}
let environment = url.query_value("env").filter(|s| !s.is_empty());
let path = match url.query_value("path").filter(|s| !s.is_empty()) {
Some(p) => {
let trimmed = p.trim_end_matches('/');
if trimmed.starts_with('/') {
trimmed.to_string()
} else {
format!("/{trimmed}")
}
}
None => DEFAULT_PATH.to_string(),
};
Ok(Self {
endpoint,
project_id,
environment,
path,
})
}
}
/// One secret's location in Infisical's own terms. Holds no secret value, so it
/// is safe to render in an error or a test failure.
#[derive(Debug)]
struct Location {
environment: String,
secret_path: String,
key: String,
}
/// The distinction an environment diagnostic needs to retain after a secret
/// read. An HTTP 200 without a usable value is not Infisical's ambiguous 404.
enum SecretRead {
Response(Option<SecretString>),
NotFound,
}
/// Infisical provider.
pub struct InfisicalProvider {
config: InfisicalConfig,
/// Credentials supplied by the provider alias.
credentials: ProviderCredentials,
/// The Universal Auth access token, fetched once per process. Infisical's
/// tokens are short-lived (7200s by default), which outlives any single
/// SecretSpec invocation.
///
/// Async, because the exchange itself must be serialized rather than merely
/// its result: a batch read fetches distinct addresses concurrently, and a
/// cell that only guards the completed token lets every caller log in and
/// then discard all but one. Infisical supports client secrets with a
/// one-use limit, for which the surplus exchanges are not just waste but a
/// hard failure.
token: tokio::sync::OnceCell<SecretString>,
/// One HTTP client for every request, so a run of secrets reuses the
/// connection rather than building a pool per call.
http: OnceLock<reqwest::Client>,
/// The session's profile, set by [`Provider::set_profile`] before any I/O.
///
/// A convention address names the profile itself, so this only answers for a
/// `ref`, whose coordinates name a folder and key but never an environment.
/// It is deliberately not part of [`InfisicalConfig`]: the environment a
/// profile implies must not reach [`uri`](Provider::uri) or
/// [`storage_identity`](Provider::storage_identity), or the same store would
/// take one identity per profile.
profile: Mutex<Option<String>>,
}
crate::register_provider! {
struct: InfisicalProvider,
config: InfisicalConfig,
metadata: &super::catalog::INFISICAL,
}
impl InfisicalProvider {
/// Creates a new InfisicalProvider with the given configuration.
pub fn new(config: InfisicalConfig) -> Self {
Self {
config,
credentials: ProviderCredentials::new(),
token: tokio::sync::OnceCell::new(),
http: OnceLock::new(),
profile: Mutex::new(None),
}
}
/// The shared HTTP client.
fn http(&self) -> &reqwest::Client {
self.http.get_or_init(reqwest::Client::new)
}
/// The profile this session resolves under, if [`Provider::set_profile`] has
/// run.
///
/// A blank profile is treated as absent: an empty environment slug would
/// build a request Infisical answers with a 404 that reads as a missing
/// secret, rather than as the missing configuration it is.
fn session_profile(&self) -> Option<String> {
self.profile
.lock()
.ok()?
.as_deref()
.map(str::trim)
.filter(|profile| !profile.is_empty())
.map(str::to_string)
}
/// Explains which SecretSpec setting selected an environment Infisical
/// could not find.
fn missing_environment_error(&self, environment: &str) -> SecretSpecError {
let source = if self.config.environment.is_some() {
"The provider URI selected it with `?env=`."
} else {
"The active SecretSpec profile selected it because the provider URI does not pin an \
environment with `?env=`."
};
SecretSpecError::ProviderOperationFailed(format!(
"Infisical could not find environment '{}' in project {} (or the project itself is \
unavailable). {source}",
environment, self.config.project_id
))
}
/// Renders the provider URI with the supplied entry-addressing defaults.
///
/// The public URI passes the configured environment and path through. Entry
/// comparison omits both from the underlying project container and resolves
/// them alongside the address instead, so aliases with different defaults
/// can still compare the physical entries they actually reach without
/// changing either alias's cache identity.
fn render_uri(&self, environment: Option<&str>, path: Option<&str>) -> String {
let plain_http = self.config.endpoint.starts_with("http://");
let host = self
.config
.endpoint
.trim_start_matches("https://")
.trim_start_matches("http://");
let mut uri = format!("infisical://{host}/{}", self.config.project_id);
let mut query = Vec::new();
if let Some(env) = environment {
query.push(format!("env={}", ProviderUrl::encode_query(env)));
}
if let Some(path) = path.filter(|path| *path != DEFAULT_PATH) {
query.push(format!("path={}", ProviderUrl::encode_query(path)));
}
if plain_http {
query.push("tls=false".to_string());
}
if !query.is_empty() {
uri.push('?');
uri.push_str(&query.join("&"));
}
uri
}
/// Resolves an address to one secret's Infisical location.
///
/// `item` carries the folder and the key together, so convention and `ref`
/// addresses share one spelling of the layout. The environment comes from
/// `?env=`, else the profile: a convention address names the profile, and a
/// `ref` takes the one the session resolves under, so both spell the same
/// environment for the same run.
fn locate(&self, addr: Address<'_>) -> Result<Location> {
let coords = self.resolve_coords(addr)?;
let environment = match (&self.config.environment, addr) {
(Some(env), _) => env.clone(),
(None, Address::Convention { profile, .. }) => profile.to_string(),
(None, Address::Native(_)) => self.session_profile().ok_or_else(|| {
SecretSpecError::ProviderOperationFailed(
"No Infisical environment for this ref. Name one in the provider URI, \
e.g. infisical://app.infisical.com/{project-id}?env=prod. A provider \
credential is resolved without a profile, so its ref always needs one."
.to_string(),
)
})?,
};
// A leading slash distinguishes the two forms a ref can take: `/DB`
// names the environment's root, while `DB` and `team/DB` alike are read
// under the configured prefix. Trimming the slash first would move a
// root secret under the prefix, where reading it finds nothing; reading
// a relative folder from the root instead would put the prefix out of
// reach of every ref that names a folder.
let (secret_path, key) = match coords.item.rsplit_once('/') {
Some((folder, key)) => {
let folder = folder.trim_end_matches('/');
let secret_path = match folder {
"" => "/".to_string(),
relative if !relative.starts_with('/') => {
join_slash_path(&self.config.path, relative)
}
absolute => absolute.to_string(),
};
(secret_path, key.to_string())
}
// A bare name sits at the folder prefix itself.
None => (self.config.path.clone(), coords.item.clone()),
};
if key.is_empty() {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Invalid Infisical ref '{}': it names a folder, not a secret.",
coords.item
)));
}
Ok(Location {
environment,
secret_path,
key,
})
}
/// Resolves the access token, logging in at most once.
///
/// An already-minted token is used directly; otherwise a machine
/// identity's credentials are exchanged for one. Infisical's tokens are
/// short-lived (7200s by default), which outlives any single SecretSpec
/// invocation, so the token is fetched once and never renewed.
///
/// The login is awaited rather than blocked on: this runs inside the
/// runtime that [`block_on`](super::block_on) already entered for the
/// request, and blocking there would panic.
async fn resolve_token(&self) -> Result<&SecretString> {
// `get_or_try_init` runs one initializer at a time: a concurrent caller
// waits for the in-flight exchange and takes its token rather than
// starting a second one. On failure the cell stays empty, so a later
// call retries instead of caching the error.
self.token
.get_or_try_init(|| async {
// `credential_or_env` never yields an empty value, so a blank
// INFISICAL_TOKEN reads as absent rather than as a broken token.
match credential_or_env(&self.credentials, TOKEN, INFISICAL_TOKEN_ENV) {
Some(token) => Ok(SecretString::new(token.into())),
None => self.login().await,
}
})
.await
}
/// Exchanges the machine identity's credentials for an access token.
async fn login(&self) -> Result<SecretString> {
let client_id = credential_or_env(&self.credentials, CLIENT_ID, INFISICAL_CLIENT_ID_ENV);
let client_secret = credential_or_env(
&self.credentials,
CLIENT_SECRET,
INFISICAL_CLIENT_SECRET_ENV,
);
// A half-specified identity is an error: falling back to an anonymous
// request would fail later with an opaque 401 instead.
let (client_id, client_secret) = match (client_id, client_secret) {
(Some(id), Some(secret)) => (id, secret),
(None, None) => {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"No Infisical credentials found. Configure the {CLIENT_ID} and \
{CLIENT_SECRET} provider credentials (or a ready-made {TOKEN}), or set \
{INFISICAL_CLIENT_ID_ENV} and {INFISICAL_CLIENT_SECRET_ENV} (or \
{INFISICAL_TOKEN_ENV})."
)));
}
(Some(_), None) => {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Infisical {CLIENT_SECRET} is missing. Configure the {CLIENT_SECRET} \
provider credential, or set {INFISICAL_CLIENT_SECRET_ENV}."
)));
}
(None, Some(_)) => {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Infisical {CLIENT_ID} is missing. Configure the {CLIENT_ID} provider \
credential, or set {INFISICAL_CLIENT_ID_ENV}."
)));
}
};
let url = format!("{}/api/v1/auth/universal-auth/login", self.config.endpoint);
let body = serde_json::json!({
"clientId": client_id,
"clientSecret": client_secret,
});
// Keep the authentication connection out of the pool used for secret reads.
let auth_client = reqwest::Client::new();
let response = auth_client
.post(&url)
.json(&body)
.send()
.await
.map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Failed to connect to Infisical at {}: {}",
self.config.endpoint,
crate::error::display_error_chain(&e)
))
})?;
if !response.status().is_success() {
let status = response.status();
let body = Self::response_body(response).await?;
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Infisical login returned HTTP {status}: {}",
Self::error_message(&body)
)));
}
let parsed: serde_json::Value = response.json().await.map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Failed to parse Infisical login response: {}",
crate::error::display_error_chain(&e)
))
})?;
let token = parsed["accessToken"].as_str().ok_or_else(|| {
SecretSpecError::ProviderOperationFailed(
"Infisical login response missing accessToken".to_string(),
)
})?;
Ok(SecretString::new(token.to_string().into()))
}
/// Infisical's error envelope carries a human-readable `message`; the
/// status code, not this text, decides control flow.
fn error_message(body: &str) -> String {
serde_json::from_str::<serde_json::Value>(body)
.ok()
.and_then(|v| v["message"].as_str().map(str::to_string))
.unwrap_or_else(|| body.to_string())
}
/// Reads a response body without hiding transport/decompression failures
/// behind an empty string and a later, misleading JSON parse error.
async fn response_body(response: reqwest::Response) -> Result<String> {
let status = response.status();
response.text().await.map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Failed to read Infisical HTTP {status} response body: {}",
crate::error::display_error_chain(&e)
))
})
}
/// The query shared by every read: which project, environment and folder.
///
/// `expandSecretReferences` follows Infisical's own default and CLI: a
/// `${...}` reference is a feature its users configure deliberately, so the
/// value SecretSpec hands over is the resolved one.
///
/// `viewSecretValue` is set explicitly rather than left to its default,
/// since Infisical can withhold a value from an identity that may only see
/// that a secret exists. Requesting the value does not guarantee it, so
/// every read is checked with [`secret_value`](Self::secret_value).
fn read_query<'q>(
&'q self,
environment: &'q str,
secret_path: &'q str,
) -> Vec<(&'static str, &'q str)> {
vec![
("projectId", self.config.project_id.as_str()),
("environment", environment),
("secretPath", secret_path),
("expandSecretReferences", "true"),
("viewSecretValue", "true"),
]
}
/// A metadata-only root listing used solely to check whether an
/// environment exists.
///
/// Unlike a secret read, this must not retrieve or expand values: every
/// secret at the root is unrelated to the missing entry being diagnosed.
fn environment_probe_query<'q>(&'q self, environment: &'q str) -> Vec<(&'static str, &'q str)> {
vec![
("projectId", self.config.project_id.as_str()),
("environment", environment),
("secretPath", "/"),
("expandSecretReferences", "false"),
("viewSecretValue", "false"),
]
}
/// Reads one secret's value from its JSON, rejecting a value Infisical
/// withheld.
///
/// An identity allowed to see that a secret exists, but not to read it,
/// still gets HTTP 200: the value is replaced with a placeholder and
/// `secretValueHidden` is set. Passing that placeholder on would export a
/// literal `<hidden-by-infisical>` to the process SecretSpec runs, so it is
/// reported as the refusal it is.
fn secret_value(secret: &serde_json::Value, key: &str) -> Result<Option<SecretString>> {
if secret["secretValueHidden"].as_bool() == Some(true) {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Infisical withheld the value of '{key}': this identity may see that the \
secret exists but not read it. Grant it permission to read secret values."
)));
}
Ok(secret["secretValue"]
.as_str()
.map(|v| SecretString::new(v.to_string().into())))
}
/// The URL naming one secret.
///
/// Infisical accepts any non-empty key -- spaces and non-ASCII included --
/// so the key is escaped as a path segment rather than interpolated.
fn secret_url(&self, key: &str) -> Result<String> {
let mut url = url::Url::parse(&self.config.endpoint).map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Invalid Infisical endpoint '{}': {e}",
self.config.endpoint
))
})?;
url.path_segments_mut()
.map_err(|_| {
SecretSpecError::ProviderOperationFailed(format!(
"Invalid Infisical endpoint '{}': not a base URL",
self.config.endpoint
))
})?
.extend(["api", "v4", "secrets", key]);
Ok(url.into())
}
/// Reads one secret, by version when the ref pins one.
async fn get_async(&self, loc: &Location, version: Option<&str>) -> Result<SecretRead> {
let url = self.secret_url(&loc.key)?;
let mut query = self.read_query(&loc.environment, &loc.secret_path);
if let Some(version) = version {
query.push(("version", version));
}
let response = self.send(reqwest::Method::GET, &url, &query, None).await?;
let status = response.status();
let body = Self::response_body(response).await?;
match status {
StatusCode::OK => {
let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Failed to parse Infisical response: {e}"
))
})?;
Self::secret_value(&parsed["secret"], &loc.key).map(SecretRead::Response)
}
// A 404 covers a missing secret, folder, environment and project
// alike. The caller decides when an all-missing operation warrants
// an environment probe, so a batch can share one probe across all
// of its version-pinned reads.
StatusCode::NOT_FOUND => Ok(SecretRead::NotFound),
_ => Err(self.http_error(status, &body, "reading a secret")),
}
}
/// Folds a list response's imported secrets into the keys read directly
/// from the folder.
///
/// A folder can import others, and the list endpoint answers with those in
/// a separate `imports` array rather than merged into `secrets` (it sets
/// `includeImports` by default, so they arrive whether or not they are
/// asked for). Ignoring them would make a batch read disagree with a
/// single read of the same key, which does resolve imports: `check` and
/// `run` would call an imported secret missing while `get` returned it.
///
/// The precedence mirrors the Infisical CLI's `InjectRawImportedSecret`, so
/// a value resolves the same way here as it does through their own tool: a
/// secret defined directly in the folder wins over any import, and among
/// imports a later entry wins over an earlier one (the CLI walks the array
/// in reverse, taking the first value it finds for a key).
fn merge_imports(
parsed: &serde_json::Value,
listed: &mut HashMap<String, SecretString>,
) -> Result<()> {
// Absent rather than empty on an instance that predates imports, or on
// a folder that imports nothing.
let Some(imports) = parsed["imports"].as_array() else {
return Ok(());
};
for import in imports.iter().rev() {
let Some(secrets) = import["secrets"].as_array() else {
continue;
};
for secret in secrets {
let Some(key) = secret["secretKey"].as_str() else {
continue;
};
// A direct secret, or a higher-precedence import, already
// claimed this key.
if listed.contains_key(key) {
continue;
}
// Withheld values are refused here exactly as for a direct
// secret: an imported key the identity may not read must not
// arrive as the literal placeholder.
if let Some(value) = Self::secret_value(secret, key)? {
listed.insert(key.to_string(), value);
}
}
}
Ok(())
}
/// Lists every secret in one folder, indexed by key. Infisical has no
/// fetch-these-N-names endpoint, so a batch read lists the folder once.
async fn list_async(
&self,
environment: &str,
secret_path: &str,
) -> Result<Option<HashMap<String, SecretString>>> {
let url = format!("{}/api/v4/secrets", self.config.endpoint);
let query = self.read_query(environment, secret_path);
let response = self.send(reqwest::Method::GET, &url, &query, None).await?;
let status = response.status();
let body = Self::response_body(response).await?;
match status {
StatusCode::OK => {
let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Failed to parse Infisical response: {e}"
))
})?;
let secrets = parsed["secrets"].as_array().ok_or_else(|| {
SecretSpecError::ProviderOperationFailed(
"Infisical list response missing `secrets`".to_string(),
)
})?;
let mut listed = HashMap::new();
for secret in secrets {
let Some(key) = secret["secretKey"].as_str() else {
continue;
};
// A withheld value is refused here rather than dropped:
// omitting it would read as a secret that is simply unset.
if let Some(value) = Self::secret_value(secret, key)? {
listed.insert(key.to_string(), value);
}
}
Self::merge_imports(&parsed, &mut listed)?;
Ok(Some(listed))
}
// The caller decides whether this is an absent folder or an absent
// environment. Infisical uses the same 404 for both.
StatusCode::NOT_FOUND => Ok(None),
_ => Err(self.http_error(status, &body, "listing secrets")),
}
}
/// Checks the environment's root to distinguish an ordinary missing
/// secret/folder from an environment (or project) Infisical cannot find.
///
/// The root folder always exists in a real environment. Inspecting only the
/// HTTP status avoids parsing or exposing any unrelated root-level secrets.
async fn ensure_environment_exists_async(&self, environment: &str) -> Result<()> {
let url = format!("{}/api/v4/secrets", self.config.endpoint);
let query = self.environment_probe_query(environment);
let response = self.send(reqwest::Method::GET, &url, &query, None).await?;
let status = response.status();
match status {
StatusCode::OK => Ok(()),
StatusCode::NOT_FOUND => Err(self.missing_environment_error(environment)),
_ => {
let body = Self::response_body(response).await?;
Err(self.http_error(status, &body, "checking an environment"))
}
}
}
/// Writes a secret, creating its folder when Infisical requires one.
///
/// Infisical separates creating a secret from updating one, and does not
/// create a folder implicitly: writing into a folder that does not exist
/// fails and stores nothing, not even part of the path. Each request is
/// chosen from the status of the one before it, so updating an existing
/// secret costs a single call, and only a new secret costs more.
async fn set_async(&self, loc: &Location, value: &SecretString) -> Result<()> {
// A secret that is merely absent, and a folder that is absent, both
// answer 404 here.
if self
.write_secret(reqwest::Method::PATCH, loc, value)
.await?
{
return Ok(());
}
if self.write_secret(reqwest::Method::POST, loc, value).await? {
return Ok(());
}
// The folder is what is missing, unless the secret lives at the root,
// which always exists -- then the 404 is the environment's.
if loc.secret_path == "/" {
return Err(self.missing_environment_error(&loc.environment));
}
let refused = self.create_folder(loc).await?;
if self.write_secret(reqwest::Method::POST, loc, value).await? {
return Ok(());
}
Err(SecretSpecError::ProviderOperationFailed(format!(
"Infisical could not find the folder '{}' in environment '{}' even after \
creating it{}",
loc.secret_path,
loc.environment,
match refused {
Some(reason) => format!(", which reported: {reason}"),
None => ".".to_string(),
}
)))
}
/// Creates or updates one secret. `Ok(false)` reports the 404 that means
/// the secret, its folder or its environment is absent; the caller decides
/// which, since Infisical answers all three alike.
async fn write_secret(
&self,
method: reqwest::Method,
loc: &Location,
value: &SecretString,
) -> Result<bool> {
let url = self.secret_url(&loc.key)?;
let body = serde_json::json!({
"projectId": self.config.project_id,
"environment": loc.environment,
"secretPath": loc.secret_path,
"secretValue": value.expose_secret(),
});
let response = self.send(method, &url, &[], Some(body)).await?;
let status = response.status();
if status == StatusCode::NOT_FOUND {
return Ok(false);
}
let body = Self::response_body(response).await?;
if status.is_success() {
Self::written(&body, &loc.key)?;
return Ok(true);
}
Err(self.http_error(status, &body, "writing a secret"))
}
/// Confirms a write that answered 200 actually stored the value.
///
/// A project can carry an approval policy, under which a write is not a
/// write but a change request: Infisical still answers 200, with an
/// `approval` in place of the `secret`, and the value lands only once a
/// human merges it. Reading that as success would have `set` report a
/// secret stored that nobody can read back.
fn written(body: &str, key: &str) -> Result<()> {
let parsed: serde_json::Value = match serde_json::from_str(body) {
Ok(parsed) => parsed,
// A 200 whose body will not parse is left alone: the write is the
// server's word, and the shape is only consulted to catch the
// approval case.
Err(_) => return Ok(()),
};
let Some(approval) = parsed.get("approval") else {
return Ok(());
};
let status = approval["status"].as_str().unwrap_or("open");
Err(SecretSpecError::ProviderOperationFailed(format!(
"Infisical did not store '{key}': this project has an approval policy, so the \
write opened a change request ({status}) instead. The value lands once the \
request is approved in Infisical."
)))
}
/// Creates the folder holding a secret, and any parent it still needs:
/// Infisical creates the intermediate levels of a nested path in the one
/// call.
/// Returns whatever a refused creation said, for the caller to quote if
/// the write that follows still fails.
async fn create_folder(&self, loc: &Location) -> Result<Option<String>> {
let (parent, name) = loc
.secret_path
.rsplit_once('/')
.map(|(parent, name)| {
let parent = if parent.is_empty() { "/" } else { parent };
(parent.to_string(), name.to_string())
})
.ok_or_else(|| {
SecretSpecError::ProviderOperationFailed(format!(
"Invalid Infisical folder '{}': paths are absolute, e.g. /secretspec.",
loc.secret_path
))
})?;
let url = format!("{}/api/v2/folders", self.config.endpoint);
let body = serde_json::json!({
"projectId": self.config.project_id,
"environment": loc.environment,
"path": parent,
"name": name,
});
let response = self
.send(reqwest::Method::POST, &url, &[], Some(body))
.await?;
let status = response.status();
if status.is_success() {
return Ok(None);
}
let body = Self::response_body(response).await?;
// A folder that already exists answers 400, and so does a folder a
// concurrent SecretSpec run created. Telling those apart would mean
// reading the message, so the write that follows decides instead: it
// succeeds if the folder is present, whichever run created it. The
// refusal's message is returned so a write that still fails can name
// the reason rather than discard it.
if status == StatusCode::BAD_REQUEST {
return Ok(Some(Self::error_message(&body)));
}
Err(self.http_error(status, &body, "creating a folder"))
}
/// Sends an authenticated request.
async fn send(
&self,
method: reqwest::Method,
url: &str,
query: &[(&str, &str)],
body: Option<serde_json::Value>,
) -> Result<reqwest::Response> {
let token = self.resolve_token().await?;
let mut request = self
.http()
.request(method, url)
.bearer_auth(token.expose_secret())
.query(query);
if let Some(body) = body {
request = request.json(&body);
}
request.send().await.map_err(|e| {
SecretSpecError::ProviderOperationFailed(format!(
"Failed to connect to Infisical at {}: {}",
self.config.endpoint,
crate::error::display_error_chain(&e)
))
})
}
/// Renders a failed response, naming the likely cause for the statuses a
/// user actually hits.
fn http_error(&self, status: StatusCode, body: &str, action: &str) -> SecretSpecError {
let message = Self::error_message(body);
match status {
StatusCode::UNAUTHORIZED => SecretSpecError::ProviderOperationFailed(format!(
"Infisical authentication failed (401) while {action}: {message}. \
Check the machine identity's {CLIENT_ID}/{CLIENT_SECRET}."
)),
StatusCode::FORBIDDEN => SecretSpecError::ProviderOperationFailed(format!(
"Infisical denied access (403) while {action}: {message}. Check the machine \
identity's permissions on project {}.",
self.config.project_id
)),
StatusCode::TOO_MANY_REQUESTS => SecretSpecError::ProviderOperationFailed(format!(
"Infisical rate limit exceeded (429) while {action}: {message}."
)),
_ => SecretSpecError::ProviderOperationFailed(format!(
"Infisical returned HTTP {status} while {action}: {message}"
)),
}
}
}
impl Provider for InfisicalProvider {
/// Keeps the session's profile as the environment a `ref` reads from when
/// the URI names none. Last write wins, matching the other session hooks.
fn set_profile(&self, profile: &str) {
if let Ok(mut held) = self.profile.lock() {
*held = Some(profile.to_string());
}
}
/// Names the environment as well as the folder and key.
///
/// The environment is half the destination and is not in the coordinates,
/// which the default rendering shows; where the URI does not pin it, it is
/// not in [`uri`](Provider::uri) either, so a preview built from those two
/// would leave the profile-derived environment invisible on the one
/// operation that overwrites a value.
fn describe_write_target(&self, addr: Address<'_>) -> Result<String> {
let loc = self.locate(addr)?;
Ok(format!(
"environment {}, {}/{}",
loc.environment,
loc.secret_path.trim_end_matches('/'),
loc.key
))
}
/// A profile's secrets share one folder under the configured prefix, each
/// under its own key. `item` carries the folder and the key together; the
/// environment is resolved separately in [`locate`](Self::locate), since
/// SecretSpec's `ref` table has no coordinate for it.
fn convention_address(&self, project: &str, profile: &str, key: &str) -> Result<NativeAddress> {
for (label, value) in [("project", project), ("profile", profile), ("key", key)] {
if value.is_empty() {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"{label} cannot be empty"
)));
}
}
// Infisical addresses folders like a filesystem, so a key carrying a
// separator would silently move the secret to another folder. The key
// is otherwise unconstrained -- spaces and non-ASCII included -- so it
// is stored exactly as written, and two distinct keys can never land
// on one name.
if key.contains('/') {
return Err(SecretSpecError::ProviderOperationFailed(format!(
"Invalid key '{key}': Infisical addresses folders by path, so a '/' would \
move the secret to another folder."
)));
}
// The project and profile each name a folder, and Infisical spells
// folder names in a narrower alphabet than keys. Rewriting a name to
// fit would let two projects share a folder, so an unspellable one is
// refused instead.
for (label, value) in [("Project", project), ("Profile", profile)] {
if !value
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
{
return Err(SecretSpecError::ProviderOperationFailed(format!(
"{label} '{value}' cannot name an Infisical folder: only letters, digits, \
dashes and underscores are allowed. Rename it in secretspec.toml, or \
address these secrets by their own coordinates with \
ref = {{ item = \"/folder/KEY\" }}."
)));
}
}
Ok(NativeAddress {
item: format!("{}/{project}/{profile}/{key}", self.config.path),
..Default::default()
})
}
/// Resolves every part of the entry identity that Infisical sends to the
/// API. In particular, the environment may come from session profile
/// context rather than the provider URI or native coordinates.
fn entry_coordinates<'a>(
&self,
addr: Address<'a>,
) -> Result<std::borrow::Cow<'a, NativeAddress>> {
let loc = self.locate(addr)?;
let version = match addr {
Address::Native(native) => native.version.clone(),
Address::Convention { .. } => None,
};
// NativeAddress has no environment coordinate. Encode the resolved
// Infisical tuple into its canonical item identity; query encoding
// keeps the component boundaries unambiguous. This value is used only
// for comparisons and is never sent to Infisical.
let item = format!(
"environment={}&path={}&key={}",
ProviderUrl::encode_query(&loc.environment),
ProviderUrl::encode_query(&loc.secret_path),
ProviderUrl::encode_query(&loc.key),
);
Ok(std::borrow::Cow::Owned(NativeAddress {
item,
version,
..Default::default()
}))
}
fn with_credentials(&mut self, credentials: ProviderCredentials) {
self.credentials = credentials;
}
fn name(&self) -> &'static str {
Self::PROVIDER_NAME
}
/// The inverse of parsing: every knob the config holds is rendered, so the
/// URI naming this store in an audit record or a warning is one that reads
/// back as the same store. `tls` is the one that bites -- a plain-HTTP
/// endpoint rendered without it comes back as HTTPS.
fn uri(&self) -> String {
self.render_uri(
self.config.environment.as_deref(),
Some(self.config.path.as_str()),
)
}
/// The environment and path are part of the resolved entry coordinates,
/// not the Infisical instance and project container. Omitting both here
/// lets an unpinned provider under profile `prod` compare equal to
/// `?env=prod`, and lets an absolute ref override different path defaults;
/// [`storage_identity`](Provider::storage_identity) remains the public URI
/// with its configured defaults and never absorbs session profile context.
fn entry_container_identity(&self) -> String {
self.render_uri(None, None)
}
/// Infisical versions its secrets, so a `ref` may pin one. Its values are
/// single strings with no sub-components, so `field`, `section` and
/// `vault` are rejected.
fn supported_coords(&self) -> &'static [&'static str] {
&["version"]
}
fn get(&self, addr: Address<'_>) -> Result<Option<SecretString>> {
let loc = self.locate(addr)?;
let version = match addr {
Address::Native(native) => native.version.as_deref(),
Address::Convention { .. } => None,
};
super::block_on(async {
let read = self.get_async(&loc, version).await?;
if matches!(&read, SecretRead::NotFound) {
self.ensure_environment_exists_async(&loc.environment)
.await?;
}
Ok(match read {
SecretRead::Response(value) => value,
SecretRead::NotFound => None,
})
})
}
/// Secrets sharing a folder and environment are read with one list call
/// each, rather than one round trip per secret: Infisical's cloud rate
/// limits are per-minute, and a fan-out of single reads burns them.
fn get_many(&self, requests: &[(&str, Address<'_>)]) -> Result<HashMap<String, SecretString>> {
// A pinned version names one historical value, which the folder
// listing (always latest) cannot answer.
let (versioned, listable): (Vec<_>, Vec<_>) = requests.iter().partition(
|(_, addr)| matches!(addr, Address::Native(native) if native.version.is_some()),
);
// Versioned reads still share the generic deduplicated, concurrent
// fetch, but bypass `get`: its per-read diagnostic would issue one root
// probe for every miss. Their environments are checked together below
// only if the whole provider read is missing.
let versioned: Vec<(&str, Address<'_>)> = versioned.into_iter().copied().collect();
let versioned_misses = Mutex::new(HashSet::new());
let mut resolved = if versioned.is_empty() {
HashMap::new()
} else {
super::get_each_with(&versioned, |addr| {
let loc = self.locate(addr)?;
let version = match addr {
Address::Native(native) => native.version.as_deref(),
Address::Convention { .. } => None,
};
match super::block_on(self.get_async(&loc, version))? {
SecretRead::Response(value) => Ok(value),
SecretRead::NotFound => {
versioned_misses
.lock()
.map_err(|_| {
SecretSpecError::ProviderOperationFailed(
"Infisical batch diagnostic state was poisoned".to_string(),
)
})?
.insert(loc.environment);
Ok(None)
}
}
})?
};
let versioned_environments = versioned_misses.into_inner().map_err(|_| {
SecretSpecError::ProviderOperationFailed(
"Infisical batch diagnostic state was poisoned".to_string(),
)
})?;
super::block_on(async {
// One list call per distinct folder and environment.
let mut folders: HashMap<(String, String), Vec<(&str, String)>> = HashMap::new();
for (name, addr) in &listable {
let loc = self.locate(*addr)?;
folders
.entry((loc.environment, loc.secret_path))
.or_default()
.push((name, loc.key));
}
// A successful listing proves the environment exists. A 404 on a
// non-root folder is ambiguous, so defer its root probe until we
// know the entire provider read missed; successful reads should not
// pay for diagnostics on an unrelated optional secret.
let mut known_environments = HashSet::new();
let mut uncertain_environments = versioned_environments;
for ((environment, secret_path), wanted) in folders {
match self.list_async(&environment, &secret_path).await? {
Some(listed) => {
known_environments.insert(environment);
for (name, key) in wanted {
if let Some(value) = listed.get(&key) {
resolved.insert(name.to_string(), value.clone());
}
}
}
None if secret_path == "/" => {
// Listing the root itself removes the folder/secret
// ambiguity without another request.
return Err(self.missing_environment_error(&environment));
}
None => {
uncertain_environments.insert(environment);
}
}
}
if resolved.is_empty() {
let to_probe: Vec<String> = uncertain_environments
.difference(&known_environments)
.cloned()
.collect();
for environment in to_probe {
self.ensure_environment_exists_async(&environment).await?;
}
}
Ok(resolved)
})
}
fn set(&self, addr: Address<'_>, value: &SecretString) -> Result<()> {
self.check_writable(addr)?;
let loc = self.locate(addr)?;
super::block_on(self.set_async(&loc, value))
}
/// A pinned version names a value that already exists; writing one would
/// mean rewriting history, which Infisical does not offer.
fn check_writable(&self, addr: Address<'_>) -> Result<()> {
match addr {
Address::Native(native) if native.version.is_some() => {
Err(SecretSpecError::ProviderOperationFailed(
"infisical refs pinning a `version` are read-only: a past version cannot \
be rewritten. Drop `version` to write the secret's latest value."
.to_string(),
))
}
_ => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
mpsc,
};
use std::thread;
use std::time::{Duration, Instant};
use url::Url;
const PROJECT: &str = "7e2f1a4c-0000-0000-0000-000000000000";
fn config(s: &str) -> InfisicalConfig {
InfisicalConfig::try_from(&ProviderUrl::new(Url::parse(s).unwrap())).unwrap()
}
fn provider(s: &str) -> InfisicalProvider {
InfisicalProvider::new(config(s))
}
fn read_request(reader: &mut BufReader<TcpStream>) -> Option<String> {
let mut request_line = String::new();
if reader.read_line(&mut request_line).ok()? == 0 {
return None;
}
let mut content_length = 0;
loop {
let mut line = String::new();
reader.read_line(&mut line).ok()?;
if line == "\r\n" || line.is_empty() {
break;
}
if let Some((name, value)) = line.split_once(':') {
if name.eq_ignore_ascii_case("content-length") {
content_length = value.trim().parse().ok()?;
}
}
}
if content_length > 0 {
let mut body = vec![0; content_length];
reader.read_exact(&mut body).ok()?;
}
Some(request_line.trim_end().to_string())
}
/// Keeps responses alive and records the accepted connection for each request.
fn connection_recording_server() -> (SocketAddr, thread::JoinHandle<Vec<(usize, String)>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let endpoint = listener.local_addr().unwrap();
let (sender, receiver) = mpsc::channel();
let request_count = Arc::new(AtomicUsize::new(0));
let server = thread::spawn(move || {
let deadline = Instant::now() + Duration::from_secs(5);
let mut workers = Vec::new();
let mut next_connection_id = 0;
while request_count.load(Ordering::Acquire) < 2 && Instant::now() < deadline {
match listener.accept() {
Ok((stream, _)) => {
let connection_id = next_connection_id;
next_connection_id += 1;
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let sender = sender.clone();
let request_count = Arc::clone(&request_count);
workers.push(thread::spawn(move || {
let mut reader = BufReader::new(stream.try_clone().unwrap());
let mut writer = stream;
loop {
let Some(request) = read_request(&mut reader) else {
break;
};
let seen = request_count.fetch_add(1, Ordering::AcqRel) + 1;
sender.send((connection_id, request.clone())).unwrap();
let body = if request
.starts_with("POST /api/v1/auth/universal-auth/login ")
{
r#"{"accessToken":"test-token"}"#
} else if request
.starts_with("GET /api/v4/secrets/DATABASE_HOST?")
{
r#"{"secret":{"secretKey":"DATABASE_HOST","secretValue":"db.internal","secretValueHidden":false}}"#
} else {
r#"{"message":"unexpected request"}"#
};
write!(
writer,
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n{body}",
body.len()
)
.unwrap();
writer.flush().unwrap();
if seen >= 2 {
break;
}
}
}));
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(5));
}
Err(error) => panic!("accept failed: {error}"),
}
}
for worker in workers {
worker.join().unwrap();
}
drop(sender);
receiver.into_iter().collect()
});
(endpoint, server)
}
#[test]
fn universal_auth_and_secret_read_use_distinct_tcp_connections() {
let (endpoint, server) = connection_recording_server();
let mut provider = provider(&format!(
"infisical://{endpoint}/{PROJECT}?tls=false&env=development"
));
provider.with_credentials(ProviderCredentials::from([
(
CLIENT_ID.to_string(),
SecretString::new("test-client-id".to_string().into()),
),
(
CLIENT_SECRET.to_string(),
SecretString::new("test-client-secret".to_string().into()),
),
]));
let address = NativeAddress {
item: "/DATABASE_HOST".into(),
..Default::default()
};
let value = provider
.get(Address::Native(&address))
.expect("the secret read must succeed")
.expect("the fixture must return DATABASE_HOST");
assert_eq!(value.expose_secret(), "db.internal");
let requests = server.join().unwrap();
assert_eq!(requests.len(), 2, "{requests:#?}");
assert!(
requests[0]
.1
.starts_with("POST /api/v1/auth/universal-auth/login ")
);
assert!(
requests[1]
.1
.starts_with("GET /api/v4/secrets/DATABASE_HOST?")
);
assert_ne!(
requests[0].0, requests[1].0,
"Universal Auth and secret reads must use different TCP connections"
);
}
fn provider_with_token(endpoint: SocketAddr, environment: Option<&str>) -> InfisicalProvider {
let environment =
environment.map_or_else(String::new, |environment| format!("&env={environment}"));
let mut provider = provider(&format!(
"infisical://{endpoint}/{PROJECT}?tls=false{environment}"
));
provider.with_credentials(ProviderCredentials::from([(
TOKEN.to_string(),
SecretString::new("test-token".to_string().into()),
)]));
provider
}
/// Serves a fixed sequence of Infisical-shaped responses and records the
/// request lines. Closing every response keeps the tiny fixture independent
/// of reqwest's connection-pool behavior.
fn response_server(
responses: Vec<(&'static str, &'static str)>,
) -> (SocketAddr, std::thread::JoinHandle<Vec<String>>) {
response_server_with_lengths(
responses
.into_iter()
.map(|(status, body)| (status, body, body.len()))
.collect(),
)
}
/// As [`response_server`], with an independently declared content length.
/// A deliberately truncated body proves code only inspected the response
/// status instead of buffering data it did not need.
fn response_server_with_lengths(
responses: Vec<(&'static str, &'static str, usize)>,
) -> (SocketAddr, std::thread::JoinHandle<Vec<String>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let endpoint = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let mut requests = Vec::new();
for (status, body, content_length) in responses {
let (mut stream, _) = listener.accept().unwrap();
let mut reader = BufReader::new(&mut stream);
let mut request_line = String::new();
reader.read_line(&mut request_line).unwrap();
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if line == "\r\n" || line.is_empty() {
break;
}
}
requests.push(request_line.trim_end().to_string());
write!(
stream,
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: \
{}\r\nConnection: close\r\n\r\n{body}",
content_length
)
.unwrap();
}
requests
});
(endpoint, server)
}
fn one_convention_request() -> [(&'static str, Address<'static>); 1] {
[(
"API_KEY",
Address::convention("myapp", "development", "API_KEY"),
)]
}
#[test]
fn uri_defaults_to_infisical_cloud() {
let c = config(&format!("infisical:///{PROJECT}"));
assert_eq!(c.endpoint, "https://app.infisical.com");
assert_eq!(c.project_id, PROJECT);
assert_eq!(c.path, DEFAULT_PATH);
assert_eq!(c.environment, None);
}
/// When the requested folder and the environment root both return 404,
/// the provider names the missing environment instead of reducing the
/// whole profile to a list of unset secrets.
#[test]
fn an_all_missing_batch_diagnoses_a_missing_profile_environment() {
let (endpoint, server) = response_server(vec![
("404 Not Found", r#"{"message":"not found"}"#),
("404 Not Found", r#"{"message":"not found"}"#),
]);
let provider = provider_with_token(endpoint, None);
let error = provider
.get_many(&one_convention_request())
.expect_err("the absent environment must be reported")
.to_string();
assert!(error.contains("environment 'development'"), "{error}");
assert!(error.contains(PROJECT), "{error}");
assert!(error.contains("active SecretSpec profile"), "{error}");
let requests = server.join().unwrap();
assert_eq!(requests.len(), 2);
assert!(requests[0].contains("environment=development"));
assert!(requests[1].contains("secretPath=%2F"));
}
/// A missing non-root folder remains an ordinary miss when the root probe
/// proves the environment exists, preserving provider fallback behavior.
#[test]
fn a_missing_folder_in_an_existing_environment_stays_unset() {
let (endpoint, server) = response_server(vec![
("404 Not Found", r#"{"message":"not found"}"#),
("200 OK", r#"{"secrets":[]}"#),
]);
let provider = provider_with_token(endpoint, None);
assert!(
provider
.get_many(&one_convention_request())
.expect("the environment exists")
.is_empty()
);
assert_eq!(server.join().unwrap().len(), 2);
}
/// Distinct historical reads share one status-only, metadata-only root
/// probe when the whole batch is missing.
#[test]
fn versioned_batch_misses_probe_the_environment_once_without_values() {
let first_body = r#"{"message":"first version not found"}"#;
let second_body = r#"{"message":"second version not found"}"#;
let root_body = r#"{"secrets":[{"secretValue":"unrelated plaintext"}]}"#;
let (endpoint, server) = response_server_with_lengths(vec![
("404 Not Found", first_body, first_body.len()),
("404 Not Found", second_body, second_body.len()),
// Closing before the declared length makes consuming this body
// fail. A status-only probe succeeds without touching it.
("200 OK", root_body, root_body.len() + 1024),
]);
let provider = provider_with_token(endpoint, Some("development"));
let first = NativeAddress {
item: "/infra/FIRST".into(),
version: Some("1".into()),
..Default::default()
};
let second = NativeAddress {
item: "/infra/SECOND".into(),
version: Some("2".into()),
..Default::default()
};
assert!(
provider
.get_many(&[
("FIRST", Address::Native(&first)),
("SECOND", Address::Native(&second)),
])
.expect("the environment exists")
.is_empty()
);
let requests = server.join().unwrap();
assert_eq!(requests.len(), 3);
let probes: Vec<_> = requests
.iter()
.filter(|request| request.starts_with("GET /api/v4/secrets?"))
.collect();
assert_eq!(probes.len(), 1, "{requests:#?}");
assert!(probes[0].contains("secretPath=%2F"), "{}", probes[0]);
assert!(
probes[0].contains("expandSecretReferences=false"),
"{}",
probes[0]
);
assert!(probes[0].contains("viewSecretValue=false"), "{}", probes[0]);
assert!(!probes[0].contains("viewSecretValue=true"), "{}", probes[0]);
}
/// The diagnostic tells users whether to rename a profile or change the
/// provider's explicit environment pin.
#[test]
fn a_missing_environment_names_how_it_was_selected() {
let implicit = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
let implicit_error = implicit
.missing_environment_error("development")
.to_string();
assert!(implicit_error.contains("active SecretSpec profile"));
let pinned = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=shared"
));
let pinned_error = pinned.missing_environment_error("shared").to_string();
assert!(pinned_error.contains("provider URI selected it with `?env=`"));
}
#[test]
fn uri_carries_host_environment_and_path() {
let c = config(&format!(
"infisical://localhost:8080/{PROJECT}?env=prod&path=/team&tls=false"
));
assert_eq!(c.endpoint, "http://localhost:8080");
assert_eq!(c.environment.as_deref(), Some("prod"));
assert_eq!(c.path, "/team");
}
/// A project is required, and its absence names the UUID that v4 wants:
/// the slug the Infisical UI shows is not addressable.
#[test]
fn uri_without_a_project_is_rejected() {
let err = InfisicalConfig::try_from(&ProviderUrl::new(
Url::parse("infisical://app.infisical.com").unwrap(),
))
.unwrap_err();
assert!(err.to_string().contains("UUID"), "{err}");
}
/// The profile names the folder as well as the environment, so pinning
/// `?env=` cannot make two profiles share one secret.
#[test]
fn every_profile_gets_its_own_folder() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let dev = p.convention_address("myapp", "dev", "API_KEY").unwrap();
let prod = p.convention_address("myapp", "prod", "API_KEY").unwrap();
assert_eq!(dev.item, "/secretspec/myapp/dev/API_KEY");
assert_ne!(dev.item, prod.item);
}
/// The profile names the environment when the URI pins none.
#[test]
fn profile_names_the_environment() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
let loc = p
.locate(Address::convention("myapp", "prod", "API_KEY"))
.unwrap();
assert_eq!(loc.environment, "prod");
assert_eq!(loc.secret_path, "/secretspec/myapp/prod");
assert_eq!(loc.key, "API_KEY");
let pinned = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let loc = pinned
.locate(Address::convention("myapp", "prod", "API_KEY"))
.unwrap();
assert_eq!(loc.environment, "dev");
// The folder still keeps the profile apart.
assert_eq!(loc.secret_path, "/secretspec/myapp/prod");
}
/// Keys are stored exactly as written: Infisical constrains them no
/// further than being non-empty, so nothing needs rewriting.
#[test]
fn keys_are_stored_verbatim() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
for key in ["lower_case", "SECTION__KEY", "with.dot", "with-dash"] {
let addr = p.convention_address("myapp", "dev", key).unwrap();
assert_eq!(addr.item, format!("/secretspec/myapp/dev/{key}"));
}
}
/// A folder name Infisical cannot spell is refused, not rewritten: a
/// rewrite could land two projects on one folder.
#[test]
fn unspellable_folder_names_are_refused() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
let err = p.convention_address("my.app", "dev", "KEY").unwrap_err();
assert!(
err.to_string().contains("cannot name an Infisical folder"),
"{err}"
);
let err = p
.convention_address("myapp", "my.profile", "KEY")
.unwrap_err();
assert!(
err.to_string().contains("cannot name an Infisical folder"),
"{err}"
);
}
/// A ref names a folder and key; Infisical values have no components, so
/// `field` has no meaning and is rejected rather than ignored.
#[test]
fn native_address_rejects_field() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let addr = NativeAddress {
item: "/infra/DB_PASSWORD".into(),
field: Some("password".into()),
..Default::default()
};
let err = p.get(Address::Native(&addr)).unwrap_err();
assert!(err.to_string().contains("`field`"), "{err}");
}
/// A ref names no environment, so one must come from `?env=` or the profile.
/// With neither — a library caller that never set one — the error says so.
#[test]
fn native_address_needs_an_environment() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
let addr = NativeAddress {
item: "/infra/DB_PASSWORD".into(),
..Default::default()
};
let err = p.get(Address::Native(&addr)).unwrap_err();
assert!(err.to_string().contains("?env="), "{err}");
}
/// A ref splits into the folder holding it and the key itself.
#[test]
fn native_address_splits_folder_from_key() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let addr = NativeAddress {
item: "/infra/shared/DB_PASSWORD".into(),
..Default::default()
};
let loc = p.locate(Address::Native(&addr)).unwrap();
assert_eq!(loc.secret_path, "/infra/shared");
assert_eq!(loc.key, "DB_PASSWORD");
}
/// A past version cannot be rewritten, so those refs refuse writes with
/// the same reason the pre-check gives.
#[test]
fn versioned_refs_are_read_only() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let addr = NativeAddress {
item: "/infra/DB_PASSWORD".into(),
version: Some("3".into()),
..Default::default()
};
let refusal = p.check_writable(Address::Native(&addr)).unwrap_err();
assert!(refusal.to_string().contains("read-only"), "{refusal}");
let err = p
.set(Address::Native(&addr), &SecretString::new("v".into()))
.unwrap_err();
assert_eq!(err.to_string(), refusal.to_string());
}
/// A value Infisical withheld is refused, not handed on.
///
/// An identity that may see a secret exists but not read it still gets
/// HTTP 200, with a placeholder where the value should be. Passing that on
/// would export a literal `<hidden-by-infisical>` to the process
/// SecretSpec runs, and reporting it as absent would read as an unset
/// secret; both are worse than saying what happened.
#[test]
fn a_withheld_value_is_refused() {
let hidden = serde_json::json!({
"secretKey": "API_KEY",
"secretValue": "<hidden-by-infisical>",
"secretValueHidden": true,
});
let err = InfisicalProvider::secret_value(&hidden, "API_KEY").unwrap_err();
assert!(err.to_string().contains("withheld"), "{err}");
assert!(err.to_string().contains("API_KEY"), "{err}");
}
/// A readable value is returned unchanged.
#[test]
fn a_readable_value_is_returned() {
let visible = serde_json::json!({
"secretKey": "API_KEY",
"secretValue": "s3cret",
"secretValueHidden": false,
});
let value = InfisicalProvider::secret_value(&visible, "API_KEY")
.unwrap()
.expect("a readable value");
assert_eq!(value.expose_secret(), "s3cret");
}
/// Builds a list-response import entry holding one key.
fn import(path: &str, key: &str, value: &str) -> serde_json::Value {
serde_json::json!({
"secretPath": path,
"environment": "prod",
"secrets": [{
"secretKey": key,
"secretValue": value,
"secretValueHidden": false,
}],
})
}
fn merged(parsed: &serde_json::Value, direct: &[(&str, &str)]) -> HashMap<String, String> {
let mut listed: HashMap<String, SecretString> = direct
.iter()
.map(|(k, v)| (k.to_string(), SecretString::new((*v).into())))
.collect();
InfisicalProvider::merge_imports(parsed, &mut listed).expect("merge");
listed
.into_iter()
.map(|(k, v)| (k, v.expose_secret().to_string()))
.collect()
}
/// An imported secret is readable in a batch read.
///
/// Infisical answers a folder's imports separately from its own secrets. A
/// batch read that ignored them would call an imported secret missing while
/// a single read of the same key returned it.
#[test]
fn imported_secrets_are_merged_into_a_listing() {
let parsed = serde_json::json!({
"secrets": [],
"imports": [import("/shared", "DB_HOST", "db.internal")],
});
let merged = merged(&parsed, &[]);
assert_eq!(
merged.get("DB_HOST").map(String::as_str),
Some("db.internal")
);
}
/// A folder's own secret wins over an imported one, as in Infisical's CLI.
#[test]
fn a_direct_secret_beats_an_import() {
let parsed = serde_json::json!({
"secrets": [],
"imports": [import("/shared", "DB_HOST", "imported")],
});
let merged = merged(&parsed, &[("DB_HOST", "direct")]);
assert_eq!(merged.get("DB_HOST").map(String::as_str), Some("direct"));
}
/// Among imports the later entry wins: the CLI walks `imports` in reverse
/// and keeps the first value it finds for a key.
#[test]
fn a_later_import_beats_an_earlier_one() {
let parsed = serde_json::json!({
"secrets": [],
"imports": [
import("/base", "DB_HOST", "from-base"),
import("/override", "DB_HOST", "from-override"),
],
});
let merged = merged(&parsed, &[]);
assert_eq!(
merged.get("DB_HOST").map(String::as_str),
Some("from-override"),
);
}
/// A withheld imported value is refused, exactly as a direct one is.
#[test]
fn a_withheld_imported_value_is_refused() {
let parsed = serde_json::json!({
"secrets": [],
"imports": [serde_json::json!({
"secretPath": "/shared",
"environment": "prod",
"secrets": [{
"secretKey": "DB_HOST",
"secretValue": "<hidden-by-infisical>",
"secretValueHidden": true,
}],
})],
});
let mut listed = HashMap::new();
let err = InfisicalProvider::merge_imports(&parsed, &mut listed)
.expect_err("a withheld import must not pass through");
assert!(err.to_string().contains("DB_HOST"), "{err}");
}
/// A response without `imports` is not an error: an instance predating
/// imports, or a folder importing nothing, simply has none.
#[test]
fn a_listing_without_imports_is_unchanged() {
let parsed = serde_json::json!({ "secrets": [] });
let merged = merged(&parsed, &[("API_KEY", "kept")]);
assert_eq!(merged.len(), 1);
assert_eq!(merged.get("API_KEY").map(String::as_str), Some("kept"));
}
/// A write held for approval does not report success.
///
/// A project under an approval policy answers a write with 200 and an
/// `approval` where the `secret` would be, storing nothing until a human
/// merges it. Reporting that as success would claim a secret was stored
/// that cannot be read back.
#[test]
fn a_write_held_for_approval_is_not_a_write() {
let held = serde_json::json!({
"approval": { "id": "8f2c", "status": "open", "hasMerged": false },
});
let err = InfisicalProvider::written(&held.to_string(), "API_KEY").unwrap_err();
assert!(err.to_string().contains("approval policy"), "{err}");
assert!(err.to_string().contains("API_KEY"), "{err}");
}
/// An ordinary write answers with the secret it stored, and reports success.
#[test]
fn an_ordinary_write_reports_success() {
let stored = serde_json::json!({
"secret": { "id": "1a2b", "secretKey": "API_KEY", "version": 1 },
});
InfisicalProvider::written(&stored.to_string(), "API_KEY")
.expect("a stored secret is not an approval");
// A body that will not parse is the server's word, taken as given.
InfisicalProvider::written("", "API_KEY").expect("an unparseable 200 stays a success");
}
/// The rendered URI round-trips through parsing.
///
/// `uri()` names this store in audit records and warnings, so it has to
/// read back as the same store -- including a self-hosted instance on
/// plain HTTP, which without `tls` would come back as HTTPS.
#[test]
fn uri_round_trips() {
for spec in [
format!("infisical://app.infisical.com/{PROJECT}"),
format!("infisical://app.infisical.com/{PROJECT}?env=prod"),
format!("infisical://app.infisical.com/{PROJECT}?env=prod&path=/team"),
format!("infisical://localhost:8080/{PROJECT}?tls=false"),
format!("infisical://localhost:8080/{PROJECT}?env=dev&tls=false"),
] {
let rendered = provider(&spec).uri();
assert_eq!(rendered, spec, "uri() must render what parsing read");
// ... and the rendering must parse back to the same endpoint.
assert_eq!(
config(&rendered).endpoint,
config(&spec).endpoint,
"re-reading uri() must reach the same instance"
);
}
}
/// An unreadable `tls` is refused rather than silently meaning one of its
/// two values.
#[test]
fn unreadable_tls_is_rejected() {
let err = InfisicalConfig::try_from(&ProviderUrl::new(
Url::parse(&format!("infisical://host/{PROJECT}?tls=banana")).unwrap(),
))
.unwrap_err();
assert!(err.to_string().contains("tls value 'banana'"), "{err}");
}
/// Without `?env=`, a ref reads the environment the session's profile names
/// — the same one a convention address would reach in that run.
#[test]
fn a_ref_without_env_reads_the_profile_environment() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
p.set_profile("prod");
let addr = NativeAddress {
item: "/DB_PASSWORD".into(),
..Default::default()
};
let loc = p.locate(Address::Native(&addr)).unwrap();
assert_eq!(loc.environment, "prod");
assert_eq!(loc.secret_path, "/");
assert_eq!(loc.key, "DB_PASSWORD");
// A convention address in the same run names the same environment.
let conv = p
.locate(Address::convention("myapp", "prod", "DB_PASSWORD"))
.unwrap();
assert_eq!(conv.environment, loc.environment);
}
/// `?env=` is an explicit pin, so it outranks the profile for refs exactly as
/// it already does for convention addresses.
#[test]
fn an_explicit_env_outranks_the_profile() {
let p = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=shared"
));
p.set_profile("prod");
let addr = NativeAddress {
item: "/DB_PASSWORD".into(),
..Default::default()
};
assert_eq!(
p.locate(Address::Native(&addr)).unwrap().environment,
"shared"
);
assert_eq!(
p.locate(Address::convention("myapp", "prod", "DB_PASSWORD"))
.unwrap()
.environment,
"shared"
);
}
/// With neither `?env=` nor a profile, a ref still fails with the error that
/// names the fix, rather than requesting an empty environment slug.
#[test]
fn a_ref_without_env_or_profile_still_explains_itself() {
let addr = NativeAddress {
item: "/DB_PASSWORD".into(),
..Default::default()
};
for profile in [None, Some(""), Some(" ")] {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
if let Some(profile) = profile {
p.set_profile(profile);
}
let err = p.locate(Address::Native(&addr)).unwrap_err().to_string();
assert!(
err.contains("No Infisical environment for this ref"),
"{err}"
);
}
}
/// The profile is session context, not naming: an instance's URI must not
/// change with it, or one store would take a different cache identity under
/// every profile.
#[test]
fn the_profile_does_not_change_the_uri() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
let before = p.uri();
p.set_profile("prod");
assert_eq!(p.uri(), before);
assert_eq!(p.storage_identity(), before);
}
/// Entry collision checks must see the environment that operations resolve,
/// even when one alias derives it from the profile and another pins it in
/// the URI. The profile remains absent from the cache storage identity.
#[test]
fn entry_identity_resolves_the_profile_environment() {
let implicit = provider(&format!("infisical://app.infisical.com/{PROJECT}"));
implicit.set_profile("prod");
let pinned_prod = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=prod"));
let pinned_dev = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let addr = NativeAddress {
item: "/DB_PASSWORD".into(),
..Default::default()
};
assert_ne!(implicit.storage_identity(), pinned_prod.storage_identity());
assert!(
implicit
.same_entries(Address::Native(&addr), &pinned_prod, Address::Native(&addr),)
.unwrap(),
"profile prod and ?env=prod reach the same Infisical secret"
);
assert!(
!implicit
.same_entries(Address::Native(&addr), &pinned_dev, Address::Native(&addr),)
.unwrap(),
"different Infisical environments must remain distinct"
);
}
/// An absolute ref supplies the complete Infisical folder, so configured
/// path defaults do not distinguish two aliases that reach that same folder.
#[test]
fn entry_identity_uses_the_resolved_absolute_path() {
let left = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=prod&path=/left"
));
let right = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=prod&path=/right"
));
let addr = NativeAddress {
item: "/shared/DB_PASSWORD".into(),
..Default::default()
};
assert!(
left.same_entries(Address::Native(&addr), &right, Address::Native(&addr),)
.unwrap(),
"absolute refs that resolve to the same API path are one entry"
);
}
/// A relative ref is resolved under the configured path, so different path
/// defaults still keep the resulting Infisical entries distinct.
#[test]
fn entry_identity_resolves_relative_refs_under_the_configured_path() {
let left = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=prod&path=/left"
));
let right = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=prod&path=/right"
));
let addr = NativeAddress {
item: "shared/DB_PASSWORD".into(),
..Default::default()
};
assert!(
!left
.same_entries(Address::Native(&addr), &right, Address::Native(&addr),)
.unwrap(),
"relative refs under different configured paths are distinct entries"
);
}
/// `set_profile` is shared by every provider, and a preflight-enabled one is
/// wrapped as `Box<Arc<P>>`, which a `&mut self` hook cannot reach through.
/// Infisical registers no preflight today, so this guards the trait's
/// contract rather than its own wrapping: it must stay a `&self` hook.
#[test]
fn set_profile_reaches_the_provider_through_arc() {
let p = std::sync::Arc::new(provider(&format!(
"infisical://app.infisical.com/{PROJECT}"
)));
Provider::set_profile(&p, "prod");
let addr = NativeAddress {
item: "/DB_PASSWORD".into(),
..Default::default()
};
assert_eq!(
p.locate(Address::Native(&addr)).unwrap().environment,
"prod"
);
}
/// A ref names the environment's root with a leading slash, and the
/// configured prefix without one. Trimming the slash away would move a
/// root secret under the prefix, where it reads as unset.
#[test]
fn a_root_ref_stays_at_the_root() {
let p = provider(&format!("infisical://app.infisical.com/{PROJECT}?env=dev"));
let root = NativeAddress {
item: "/DB_PASSWORD".into(),
..Default::default()
};
let loc = p.locate(Address::Native(&root)).unwrap();
assert_eq!(loc.secret_path, "/");
assert_eq!(loc.key, "DB_PASSWORD");
// A bare name still means "in the configured prefix".
let bare = NativeAddress {
item: "DB_PASSWORD".into(),
..Default::default()
};
let loc = p.locate(Address::Native(&bare)).unwrap();
assert_eq!(loc.secret_path, DEFAULT_PATH);
assert_eq!(loc.key, "DB_PASSWORD");
}
/// A ref that names a folder without a leading slash is read under the
/// prefix, exactly as a bare name is. Reading it from the root instead
/// would put the prefix out of reach of every ref naming a folder, and
/// make `team/DB` mean what `/team/DB` already means.
#[test]
fn a_relative_ref_is_read_under_the_prefix() {
let p = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=dev&path=/myapp"
));
let relative = NativeAddress {
item: "team/DB_PASSWORD".into(),
..Default::default()
};
let loc = p.locate(Address::Native(&relative)).unwrap();
assert_eq!(loc.secret_path, "/myapp/team");
// ... while the absolute form still names the root, unprefixed.
let absolute = NativeAddress {
item: "/team/DB_PASSWORD".into(),
..Default::default()
};
let loc = p.locate(Address::Native(&absolute)).unwrap();
assert_eq!(loc.secret_path, "/team");
// A prefix of `/` joins without doubling the separator.
let rooted = provider(&format!(
"infisical://app.infisical.com/{PROJECT}?env=dev&path=/"
));
let loc = rooted.locate(Address::Native(&relative)).unwrap();
assert_eq!(loc.secret_path, "/team");
}
/// Infisical's own CLI appends `/api` to the domain unless it is already
/// there, so a domain carrying it is a working configuration, not a
/// mistake. A domain naming any other path still is one.
#[test]
fn a_domain_may_carry_the_api_suffix() {
let var = INFISICAL_DOMAIN_ENVS[0];
assert_eq!(
InfisicalConfig::endpoint_from_domain(var, "https://vault.example.com/api", "https")
.unwrap(),
"https://vault.example.com"
);
assert_eq!(
InfisicalConfig::endpoint_from_domain(var, "vault.example.com:8080", "https").unwrap(),
"https://vault.example.com:8080"
);
let err =
InfisicalConfig::endpoint_from_domain(var, "https://example.com/infisical", "https")
.unwrap_err();
assert!(err.to_string().contains("names a path"), "{err}");
}
/// An invalid domain is reported against the variable that actually set it,
/// not against whichever name the provider happens to prefer.
#[test]
fn an_invalid_domain_names_the_variable_that_set_it() {
let err =
InfisicalConfig::endpoint_from_domain("INFISICAL_API_URL", "https://e.com/x", "https")
.unwrap_err();
assert!(err.to_string().contains("INFISICAL_API_URL"), "{err}");
}
/// The legacy variable still names an instance.
///
/// Infisical superseded `INFISICAL_API_URL` with `INFISICAL_DOMAIN` but
/// still honours it, so an existing EU or self-hosted setup configured with
/// the old name must not be silently redirected to US Cloud.
#[test]
fn the_legacy_domain_variable_is_honoured() {
let picked = InfisicalConfig::pick_domain(|var| {
(var == "INFISICAL_API_URL").then(|| "https://eu.infisical.com".to_string())
});
assert_eq!(
picked,
Some(("INFISICAL_API_URL", "https://eu.infisical.com".to_string()))
);
}
/// `INFISICAL_DOMAIN` wins when both are set, matching the CLI's
/// `GetEnvDomain` precedence.
#[test]
fn the_current_domain_variable_supersedes_the_legacy_one() {
let picked = InfisicalConfig::pick_domain(|var| {
Some(
match var {
"INFISICAL_DOMAIN" => "https://current.example.com",
_ => "https://legacy.example.com",
}
.to_string(),
)
});
assert_eq!(
picked,
Some((
"INFISICAL_DOMAIN",
"https://current.example.com".to_string()
))
);
}
/// A blank variable falls through rather than being taken as a domain, so
/// `INFISICAL_DOMAIN=""` still lets the legacy name apply.
#[test]
fn a_blank_domain_variable_falls_through() {
let picked = InfisicalConfig::pick_domain(|var| {
Some(
match var {
"INFISICAL_DOMAIN" => " ",
_ => "https://legacy.example.com",
}
.to_string(),
)
});
assert_eq!(
picked,
Some((
"INFISICAL_API_URL",
"https://legacy.example.com".to_string()
))
);
}
/// Neither set means Infisical Cloud, not an error.
#[test]
fn no_domain_variable_is_not_an_error() {
assert_eq!(InfisicalConfig::pick_domain(|_| None), None);
}
}