monosecret 0.1.0

Declarative secrets, every environment, any provider
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
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
use std::collections::HashMap;
use std::process::Command;

use secrecy::ExposeSecret;
use secrecy::SecretString;
use serde::Deserialize;
use serde::Serialize;

use crate::MonosecretError;
use crate::Result;
use crate::config::SecretRequest;
use crate::provider::Provider;
use crate::provider::ProviderUrl;

const ONEPASSWORD_BATCH_PARALLELISM: usize = 8;

fn collect_bounded_parallel<T, R, F>(
	jobs: Vec<T>,
	max_parallel: usize,
	panic_message: &'static str,
	run: F,
) -> Vec<Result<R>>
where
	T: Send,
	R: Send,
	F: Fn(T) -> R + Sync,
{
	let max_parallel = max_parallel.max(1);
	let mut results = Vec::with_capacity(jobs.len());

	std::thread::scope(|scope| {
		let mut jobs = jobs.into_iter();
		loop {
			let handles: Vec<_> = jobs
				.by_ref()
				.take(max_parallel)
				.map(|job| {
					let run = &run;
					scope.spawn(move || run(job))
				})
				.collect();

			if handles.is_empty() {
				break;
			}

			results.extend(handles.into_iter().map(|handle| {
				handle
					.join()
					.map_err(|_| MonosecretError::ProviderOperationFailed(panic_message.into()))
			}));
		}
	});

	results
}

/// Represents a `OnePassword` item retrieved from the CLI.
///
/// This struct deserializes the JSON output from the `op item get` command
/// and contains an array of fields that hold the actual secret data.
#[derive(Debug, Deserialize)]
pub(crate) struct OnePasswordItem {
	/// Collection of fields within the `OnePassword` item.
	/// Each field represents a piece of data stored in the item.
	pub(crate) fields: Vec<OnePasswordField>,
}

/// Represents a single field within a `OnePassword` item.
///
/// Fields can contain various types of data such as passwords, strings,
/// or concealed values. The field's label is used to identify specific
/// data within an item.
#[derive(Debug, Deserialize)]
pub(crate) struct OnePasswordField {
	/// Unique identifier for the field within the item.
	id: String,
	/// The type of field (e.g., "STRING", "CONCEALED", "PASSWORD").
	#[serde(rename = "type")]
	field_type: String,
	/// Optional human-readable label for the field.
	/// Used to identify fields like "value", "password", etc.
	pub(crate) label: Option<String>,
	/// Optional section the field belongs to (e.g. "GitHub").
	pub(crate) section: Option<OnePasswordSection>,
	/// The actual value stored in the field.
	/// May be None for certain field types.
	pub(crate) value: Option<String>,
}

/// A section within a `OnePassword` item.
#[derive(Debug, Deserialize)]
pub(crate) struct OnePasswordSection {
	/// Optional label for the section (e.g. "GitHub").
	pub(crate) label: Option<String>,
}

/// Template for creating new `OnePassword` items via the CLI.
///
/// This struct is serialized to JSON and passed to the `op item create` command
/// using the `--template` flag. It defines the structure and metadata for
/// new secure note items that store secrets.
#[derive(Debug, Serialize)]
struct OnePasswordItemTemplate {
	/// The title of the item, formatted as "monosecret/{project}/{profile}/{key}".
	title: String,
	/// The category of the item. Always "`SECURE_NOTE`" for monosecret items.
	category: String,
	/// Collection of fields to include in the item.
	/// Contains project, key, and value fields.
	fields: Vec<OnePasswordFieldTemplate>,
	/// Tags to help organize and identify monosecret items.
	/// Includes "automated" and the project name.
	tags: Vec<String>,
}

/// Template for individual fields when creating `OnePassword` items.
///
/// Each field represents a piece of data to store in the item.
/// Used within `OnePasswordItemTemplate` to define the item's content.
#[derive(Debug, Serialize)]
struct OnePasswordFieldTemplate {
	/// Human-readable label for the field (e.g., "project", "key", "value").
	label: String,
	/// The type of field. Always "STRING" for monosecret fields.
	#[serde(rename = "type")]
	field_type: String,
	/// The actual value to store in the field.
	value: String,
}

/// Configuration for the `OnePassword` provider.
///
/// This struct contains all the necessary configuration options for
/// interacting with `OnePassword` CLI. It supports both interactive authentication
/// and service account tokens for automated workflows.
///
/// # Examples
///
/// ```ignore
/// # use monosecret::provider::onepassword::OnePasswordConfig;
/// // Using default configuration (interactive auth)
/// let config = OnePasswordConfig::default();
///
/// // With a specific vault
/// let config = OnePasswordConfig {
///     default_vault: Some("Development".to_string()),
///     ..Default::default()
/// };
///
/// // With service account token for CI/CD
/// let config = OnePasswordConfig {
///     service_account_token: Some("ops_eyJzaWduSW...".to_string()),
///     ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OnePasswordConfig {
	/// Optional account shorthand (for multiple accounts).
	///
	/// Used with the `--account` flag when you have multiple `OnePassword`
	/// accounts configured. This should match the shorthand shown in
	/// `op account list`.
	pub account: Option<String>,
	/// Default vault to use when profile is "default".
	///
	/// If not set, defaults to "Private" for the default profile.
	/// For non-default profiles, the profile name is used as the vault name.
	pub default_vault: Option<String>,
	/// Service account token (alternative to interactive auth).
	///
	/// When set, this token is passed via the `OP_SERVICE_ACCOUNT_TOKEN`
	/// environment variable to authenticate without user interaction.
	/// Ideal for CI/CD environments.
	pub service_account_token: Option<String>,
	/// Optional folder prefix format string for organizing Monosecret-owned secrets in `OnePassword`.
	///
	/// Supports placeholders: {project}, {profile}, and {key}.
	/// Defaults to "monosecret/{project}/{profile}/{key}" if not specified.
	pub folder_prefix: Option<String>,
	/// Whether this provider uses native 1Password secret references (`op://`).
	#[serde(default)]
	pub native_references: bool,
	/// Base path segments for native 1Password references after the vault name.
	#[serde(default, skip_serializing_if = "Vec::is_empty")]
	pub reference_base_path: Vec<String>,
}

impl TryFrom<&ProviderUrl> for OnePasswordConfig {
	type Error = MonosecretError;

	fn try_from(url: &ProviderUrl) -> std::result::Result<Self, Self::Error> {
		let scheme = url.scheme();

		match scheme {
			"1password" => {
				return Err(MonosecretError::ProviderOperationFailed(
                    "Invalid scheme '1password'. Use 'onepassword' instead (e.g., onepassword://vault/path)".to_string()
                ));
			}
			"onepassword" | "onepassword+token" | "op" | "op+token" => {}
			_ => {
				return Err(MonosecretError::ProviderOperationFailed(format!(
					"Invalid scheme '{scheme}' for OnePassword provider"
				)));
			}
		}

		let mut config = Self {
			native_references: matches!(scheme, "op" | "op+token"),
			..Self::default()
		};

		// Parse URL components for account@vault format, ignoring dummy localhost
		if let Some(host) = url.host()
			&& host != "localhost"
		{
			let username = url.username();

			// Check if we have username (account) information
			if username.is_empty() {
				// No username, so the host is the vault
				config.default_vault = Some(host);
			} else {
				// Handle user:token format for service account tokens
				if scheme == "onepassword+token" || scheme == "op+token" {
					if let Some(password) = url.password() {
						config.service_account_token = Some(password);
					} else {
						config.service_account_token = Some(username);
					}
				} else {
					config.account = Some(username);
				}
				config.default_vault = Some(host);
			}
		}

		let uri_path = url.path();
		let uri_path = uri_path.trim_matches('/');
		if !uri_path.is_empty() {
			if config.native_references {
				config.reference_base_path = uri_path
					.split('/')
					.filter(|segment| !segment.is_empty())
					.map(str::to_string)
					.collect();
			} else {
				let folder_prefix = if uri_path.contains("{key}") {
					uri_path.to_string()
				} else {
					format!("{}/{{key}}", uri_path.trim_end_matches('/'))
				};
				config.folder_prefix = Some(folder_prefix);
			}
		}

		Ok(config)
	}
}

/// Detects if running on Windows Subsystem for Linux 2.
///
/// Checks if the system is running on WSL2 by reading `/proc/sys/kernel/osrelease`
/// and looking for the `-microsoft-standard-WSL2` suffix.
///
/// # Returns
///
/// * `true` - Running on WSL2
/// * `false` - Not running on WSL2 or unable to determine
#[cfg(target_os = "linux")]
fn is_wsl2() -> bool {
	std::fs::read_to_string("/proc/sys/kernel/osrelease")
		.ok()
		.map(|content| content.trim().ends_with("-microsoft-standard-WSL2"))
		.unwrap_or(false)
}

#[cfg(not(target_os = "linux"))]
fn is_wsl2() -> bool {
	false
}

/// Removes any `OP_SESSION_*` env vars from a spawned `op` invocation.
///
/// `op` treats `OP_SESSION_<account>` as the authoritative session and will not
/// fall back to the desktop app's biometric flow when those tokens expire,
/// returning `"account is not signed in"` instead. Stripping them lets the
/// desktop integration (Settings → Developer → Integrate with 1Password CLI)
/// handle unlock automatically. See
/// <https://github.com/ifiokjr/monosecret/issues/80>.
const OP_NOT_INSTALLED_HELP: &str = "OnePassword CLI (op) is not installed.\n\n\
    To install it:\n  \
    - macOS: brew install 1password-cli\n  \
    - Linux: Download from https://1password.com/downloads/command-line/\n  \
    - Windows: Download from https://1password.com/downloads/command-line/\n  \
    - NixOS: nix-env -iA nixpkgs.onepassword\n\n\
    Then enable desktop integration in the 1Password app under\n  \
    Settings → Developer → \"Integrate with 1Password CLI\".";

const AUTH_REQUIRED_HELP: &str = "OnePassword authentication required.\n\n\
    Recommended: enable desktop integration in the 1Password app under\n  \
    Settings → Developer → \"Integrate with 1Password CLI\", then unlock the app.\n\n\
    Alternatives:\n  \
    - Service account (CI): set OP_SERVICE_ACCOUNT_TOKEN or use the onepassword+token:// or op+token:// scheme\n  \
    - Manual signin: run 'eval $(op signin)' (session expires after 30 minutes of inactivity)";

fn is_auth_error(error_msg: &str) -> bool {
	error_msg.contains("not currently signed in")
		|| error_msg.contains("no active session")
		|| error_msg.contains("could not find session token")
		|| error_msg.contains("account is not signed in")
}

pub(crate) fn strip_op_session_env(cmd: &mut Command) {
	for (key, _) in std::env::vars_os() {
		if key.to_string_lossy().starts_with("OP_SESSION_") {
			cmd.env_remove(&key);
		}
	}
}

/// Provider implementation for `OnePassword` password manager.
///
/// This provider integrates with `OnePassword` CLI (`op`) to store and retrieve
/// secrets. It organizes secrets in a hierarchical structure within `OnePassword`
/// items using a configurable format string that defaults to: `monosecret/{project}/{profile}/{key}`.
///
/// # Authentication
///
/// The provider supports three authentication methods, in order of preference:
///
/// 1. **Desktop app integration** (recommended for local dev): enable
///    Settings → Developer → "Integrate with 1Password CLI" in the desktop app.
///    `op` calls are unlocked via biometrics with no shell session needed.
/// 2. **Service Account Tokens**: For CI/CD, configure a token in the config
///    or set `OP_SERVICE_ACCOUNT_TOKEN`.
/// 3. **Manual signin** (legacy): run `eval $(op signin)`. The provider strips
///    `OP_SESSION_*` env vars before spawning `op` so that expired session
///    tokens fall back to desktop integration instead of erroring.
///
/// # Storage Structure
///
/// Secrets are stored as Secure Note items in `OnePassword` with:
/// - Title: formatted according to `folder_prefix` configuration
/// - Category: `SECURE_NOTE`
/// - Fields: project, key, value
/// - Tags: "automated", {project}
///
/// # Example Usage
///
/// ```ignore
/// # Desktop integration (recommended): enable in 1Password app, then:
/// monosecret set MY_SECRET --provider onepassword://Development
///
/// # Service account token
/// export OP_SERVICE_ACCOUNT_TOKEN="ops_eyJzaWduSW..."
/// monosecret get MY_SECRET --provider onepassword+token://Development
/// ```
pub struct OnePasswordProvider {
	/// Configuration for the provider including auth settings and default vault.
	config: OnePasswordConfig,
	/// The `OnePassword` CLI command to use (either "op" or a custom path).
	op_command: String,
	/// Provider-local dependency secrets that are passed to the `op` child process.
	dependency_env: HashMap<String, SecretString>,
}

crate::register_provider! {
	struct: OnePasswordProvider,
	config: OnePasswordConfig,
	name: "onepassword",
	description: "OnePassword password manager",
	schemes: ["onepassword", "onepassword+token", "op", "op+token"],
	examples: [
		"onepassword://vault",
		"onepassword://work@Production",
		"onepassword+token://vault",
		"op://vault/item/section",
		"op+token://vault/item",
	],
	preflight: check_auth,
}

impl OnePasswordProvider {
	/// Creates a new `OnePasswordProvider` with the given configuration.
	///
	/// # Arguments
	///
	/// * `config` - The configuration for the provider
	pub fn new(config: OnePasswordConfig) -> Self {
		let op_command = std::env::var("MONOSECRET_OPCLI_PATH")
			.or_else(|_| std::env::var("SECRETSPEC_OPCLI_PATH"))
			.unwrap_or_else(|_| {
				if is_wsl2() {
					"op.exe".to_string()
				} else {
					"op".to_string()
				}
			});
		Self {
			config,
			op_command,
			dependency_env: HashMap::new(),
		}
	}

	/// Executes a `OnePassword` CLI command with proper error handling.
	///
	/// This method handles:
	/// - Setting up authentication (account, service token)
	/// - Executing the command
	/// - Parsing error messages for common issues
	/// - Providing helpful error messages for missing CLI
	///
	/// # Arguments
	///
	/// * `args` - The command arguments to pass to `op`
	/// * `stdin_data` - Optional data to write to stdin
	///
	/// # Returns
	///
	/// * `Result<String>` - The command output or an error
	///
	/// # Errors
	///
	/// Returns specific errors for:
	/// - Missing `OnePassword` CLI installation
	/// - Authentication required
	/// - Command execution failures
	/// - Stdin write failures
	fn execute_op_command(&self, args: &[&str], stdin_data: Option<&str>) -> Result<String> {
		use std::io::Write;
		use std::process::Stdio;

		tracing::debug!(
			command = %self.op_command,
			args = ?args,
			has_stdin = stdin_data.is_some(),
			has_service_token = self.config.service_account_token.is_some()
				|| self.dependency_env.contains_key("OP_SERVICE_ACCOUNT_TOKEN"),
			account = ?self.config.account,
			vault = ?self.config.default_vault,
			"executing 1Password CLI command"
		);

		let mut cmd = Command::new(&self.op_command);
		strip_op_session_env(&mut cmd);

		// Set service account token directly on the child command. Prefer an
		// explicit token from the provider URI, then fall back to a resolved
		// provider dependency. This avoids mutating the process-global
		// environment while still giving `op` the credentials it needs.
		if let Some(token) = &self.config.service_account_token {
			cmd.env("OP_SERVICE_ACCOUNT_TOKEN", token);
		} else if let Some(token) = self.dependency_env.get("OP_SERVICE_ACCOUNT_TOKEN") {
			cmd.env("OP_SERVICE_ACCOUNT_TOKEN", token.expose_secret());
		}

		// Add account if specified
		if let Some(account) = &self.config.account {
			cmd.arg("--account").arg(account);
		}

		cmd.args(args);

		// Configure stdio based on whether we have stdin data
		if stdin_data.is_some() {
			cmd.stdin(Stdio::piped());
			cmd.stdout(Stdio::piped());
			cmd.stderr(Stdio::piped());
		}

		let output = if let Some(data) = stdin_data {
			// Spawn process and write to stdin
			let mut child = match cmd.spawn() {
				Ok(child) => child,
				Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
					return Err(MonosecretError::ProviderOperationFailed(
						OP_NOT_INSTALLED_HELP.to_string(),
					));
				}
				Err(e) => return Err(e.into()),
			};

			// Write to stdin
			if let Some(mut stdin) = child.stdin.take() {
				stdin.write_all(data.as_bytes())?;
				drop(stdin); // Close stdin
			}

			child.wait_with_output()?
		} else {
			// No stdin data, use output() directly
			match cmd.output() {
				Ok(output) => output,
				Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
					return Err(MonosecretError::ProviderOperationFailed(
						OP_NOT_INSTALLED_HELP.to_string(),
					));
				}
				Err(e) => return Err(e.into()),
			}
		};

		if !output.status.success() {
			let error_msg = String::from_utf8_lossy(&output.stderr);
			if is_auth_error(&error_msg) {
				tracing::error!(
					status = ?output.status.code(),
					stderr = %error_msg,
					args = ?args,
					"1Password CLI command failed due to authentication"
				);
				return Err(MonosecretError::ProviderOperationFailed(
					AUTH_REQUIRED_HELP.to_string(),
				));
			}
			tracing::warn!(
				status = ?output.status.code(),
				stderr = %error_msg,
				args = ?args,
				"1Password CLI command failed"
			);
			return Err(MonosecretError::ProviderOperationFailed(
				error_msg.to_string(),
			));
		}

		String::from_utf8(output.stdout)
			.map_err(|e| MonosecretError::ProviderOperationFailed(e.to_string()))
	}

	/// Checks if the user is authenticated with `OnePassword` (uncached).
	///
	/// Uses `op vault list` rather than `op whoami` because the latter only
	/// reports the state of an explicit `op signin` session and reports
	/// `account is not signed in` under desktop-app delegated sessions even
	/// when secret reads via `op item ...` work fine. `op vault list` actually
	/// exercises the access path used for real operations.
	///
	/// # Returns
	///
	/// * `Ok(true)` - User is authenticated
	/// * `Ok(false)` - User is not authenticated
	/// * `Err(_)` - Command execution failed
	fn is_authenticated(&self) -> Result<bool> {
		match self.execute_op_command(&["vault", "list", "--format", "json"], None) {
			Ok(_) => Ok(true),
			Err(MonosecretError::ProviderOperationFailed(msg))
				if msg.contains("authentication required") || msg.contains("no account found") =>
			{
				Ok(false)
			}
			Err(e) => Err(e),
		}
	}

	/// Determines the vault name to use.
	///
	/// # Arguments
	///
	/// * `profile` - The profile name (currently unused, but kept for potential future use)
	///
	/// # Returns
	///
	/// The vault name to use - always returns the configured `default_vault` or "Private"
	fn get_vault_name(&self, _profile: &str) -> String {
		self.config
			.default_vault
			.clone()
			.unwrap_or_else(|| "Private".to_string())
	}

	/// Finds an item by title in the vault and returns its ID.
	///
	/// Uses `op item list` to search for items, which is more reliable than
	/// `op item get` for existence checking because it doesn't fail when
	/// an item exists but has no extractable value.
	///
	/// # Arguments
	///
	/// * `item_name` - The item title to search for
	/// * `vault` - The vault to search in
	///
	/// # Returns
	///
	/// * `Ok(Some(id))` - Item found, returns its ID
	/// * `Ok(None)` - Item not found
	/// * `Err(_)` - Search failed
	fn find_item_id(&self, item_name: &str, vault: &str) -> Result<Option<String>> {
		let args = vec!["item", "list", "--vault", vault, "--format", "json"];

		let output = self.execute_op_command(&args, None)?;

		#[derive(Deserialize)]
		struct ListItem {
			id: String,
			title: String,
		}

		let items: Vec<ListItem> = serde_json::from_str(&output).unwrap_or_default();

		Ok(items
			.into_iter()
			.find(|item| item.title == item_name)
			.map(|item| item.id))
	}

	/// Formats the item name for storage in `OnePassword`.
	///
	/// Creates a hierarchical name using the `folder_prefix` format string.
	/// Supports placeholders: {project}, {profile}, and {key}.
	/// Defaults to "monosecret/{project}/{profile}/{key}" if not configured.
	///
	/// # Arguments
	///
	/// * `project` - The project name
	/// * `key` - The secret key
	/// * `profile` - The profile name
	///
	/// # Returns
	///
	/// A formatted string based on the configured pattern
	fn format_item_name(&self, project: &str, key: &str, profile: &str) -> String {
		let format_string = self
			.config
			.folder_prefix
			.as_deref()
			.unwrap_or("monosecret/{project}/{profile}/{key}");

		format_string
			.replace("{project}", project)
			.replace("{profile}", profile)
			.replace("{key}", key)
	}

	/// Creates a template for a new `OnePassword` item.
	///
	/// This template is serialized to JSON and used with `op item create`.
	/// The item is created as a Secure Note with structured fields.
	///
	/// # Arguments
	///
	/// * `project` - The project name
	/// * `key` - The secret key
	/// * `value` - The secret value
	/// * `profile` - The profile name
	///
	/// # Returns
	///
	/// A `OnePasswordItemTemplate` ready for serialization
	fn create_item_template(
		&self,
		project: &str,
		key: &str,
		value: &SecretString,
		profile: &str,
	) -> OnePasswordItemTemplate {
		OnePasswordItemTemplate {
			title: self.format_item_name(project, key, profile),
			category: "SECURE_NOTE".to_string(),
			fields: vec![
				OnePasswordFieldTemplate {
					label: "project".to_string(),
					field_type: "STRING".to_string(),
					value: project.to_string(),
				},
				OnePasswordFieldTemplate {
					label: "key".to_string(),
					field_type: "STRING".to_string(),
					value: key.to_string(),
				},
				OnePasswordFieldTemplate {
					label: "value".to_string(),
					field_type: "STRING".to_string(),
					value: value.expose_secret().to_string(),
				},
			],
			tags: vec!["automated".to_string(), project.to_string()],
		}
	}

	/// Extracts the secret value from a `OnePassword` item JSON.
	///
	/// Looks for a field labeled "value" first, then falls back to
	/// password or concealed fields.
	fn extract_value_from_item(output: &str) -> Result<Option<SecretString>> {
		let item: OnePasswordItem = serde_json::from_str(output)?;

		// Look for the "value" field
		for field in &item.fields {
			if field.label.as_deref() == Some("value") {
				return Ok(field
					.value
					.as_ref()
					.map(|v| SecretString::new(v.clone().into())));
			}
		}

		// Fallback: look for password field or first concealed field
		for field in &item.fields {
			if field.field_type == "CONCEALED" || field.id == "password" {
				return Ok(field
					.value
					.as_ref()
					.map(|v| SecretString::new(v.clone().into())));
			}
		}

		Ok(None)
	}
}

impl OnePasswordProvider {
	/// Checks that the user is authenticated with `OnePassword`.
	/// Called by the preflight guard before any provider operations.
	pub(crate) fn check_auth(&self) -> Result<()> {
		if self.is_authenticated()? {
			Ok(())
		} else {
			Err(MonosecretError::ProviderOperationFailed(
				AUTH_REQUIRED_HELP.to_string(),
			))
		}
	}

	fn native_reference_parts(&self, key: &str, request: Option<&SecretRequest>) -> Vec<String> {
		let mut parts = self.config.reference_base_path.clone();
		if let Some(request) = request {
			if let Some(path) = &request.path {
				parts.extend(path.iter().cloned());
			}
			parts.push(request.key.as_deref().unwrap_or(key).to_string());
		} else {
			parts.push(key.to_string());
		}
		parts
	}

	fn native_reference(&self, profile: &str, parts: &[String]) -> String {
		let mut reference = format!(
			"op://{}",
			ProviderUrl::encode(&self.get_vault_name(profile))
		);
		for part in parts {
			reference.push('/');
			reference.push_str(&ProviderUrl::encode(part));
		}
		reference
	}

	fn native_item_and_assignment(
		&self,
		key: &str,
		value: &SecretString,
		request: Option<&SecretRequest>,
	) -> Result<(String, String)> {
		let parts = self.native_reference_parts(key, request);
		if parts.len() < 2 {
			return Err(MonosecretError::ProviderOperationFailed(
				"Native 1Password provider requires an item path before the field name".into(),
			));
		}

		let item = parts[0].clone();
		let field = parts.last().expect("parts length checked");
		let assignment_name = if parts.len() > 2 {
			format!("{}.{}", parts[1..parts.len() - 1].join("."), field)
		} else {
			field.clone()
		};
		Ok((
			item,
			format!("{}[concealed]={}", assignment_name, value.expose_secret()),
		))
	}

	fn native_missing_message(message: &str) -> bool {
		message.contains("isn't an item")
			|| message.contains("isn't a field")
			|| message.contains("couldn't find")
			|| message.contains("not found")
	}

	fn read_native_reference(
		&self,
		key: &str,
		profile: &str,
		request: Option<&SecretRequest>,
	) -> Result<Option<SecretString>> {
		let parts = self.native_reference_parts(key, request);
		if parts.len() < 2 {
			return Ok(None);
		}
		let reference = self.native_reference(profile, &parts);
		let args = vec!["read", reference.as_str()];
		match self.execute_op_command(&args, None) {
			Ok(output) => {
				Ok(Some(SecretString::new(
					output.trim_end_matches(['\r', '\n']).to_string().into(),
				)))
			}
			Err(MonosecretError::ProviderOperationFailed(msg))
				if Self::native_missing_message(&msg) =>
			{
				Ok(None)
			}
			Err(e) => Err(e),
		}
	}

	fn set_native_reference(
		&self,
		key: &str,
		value: &SecretString,
		profile: &str,
		request: Option<&SecretRequest>,
	) -> Result<()> {
		let vault = self.get_vault_name(profile);
		if self.read_native_reference(key, profile, request)?.is_none() {
			return Err(MonosecretError::ProviderOperationFailed(
				"Cannot set native 1Password reference because it does not exist".into(),
			));
		}
		let (item, assignment) = self.native_item_and_assignment(key, value, request)?;
		let edit_args = vec![
			"item",
			"edit",
			item.as_str(),
			"--vault",
			vault.as_str(),
			assignment.as_str(),
		];
		self.execute_op_command(&edit_args, None).map(|_| ())
	}
}

impl Provider for OnePasswordProvider {
	fn configure_dependency_secrets(
		&mut self,
		dependencies: &[(String, SecretString)],
	) -> Result<()> {
		for (name, value) in dependencies {
			if name == "OP_SERVICE_ACCOUNT_TOKEN" {
				self.dependency_env.insert(name.clone(), value.clone());
			}
		}
		Ok(())
	}

	fn name(&self) -> &'static str {
		Self::PROVIDER_NAME
	}

	fn uri(&self) -> String {
		// Reconstruct the URI from the config
		// Format: onepassword://[account@]vault, onepassword+token://[token@]vault,
		// op://vault[/item], or op+token://[token@]vault[/item]

		let scheme = match (
			self.config.native_references,
			self.config.service_account_token.is_some(),
		) {
			(true, true) => "op+token",
			(true, false) => "op",
			(false, true) => "onepassword+token",
			(false, false) => "onepassword",
		};

		let mut uri = format!("{scheme}://");

		// For service account token, the token itself might be in the URI
		// but we don't want to expose the actual token value, just indicate it's configured
		if self.config.service_account_token.is_some() {
			// Just indicate token auth is being used without exposing the token
			if let Some(ref vault) = self.config.default_vault {
				uri.push_str(&ProviderUrl::encode(vault));
			}
		} else {
			// Regular auth: account@vault format
			if let Some(ref account) = self.config.account {
				uri.push_str(&ProviderUrl::encode(account));
				uri.push('@');
			}

			if let Some(ref vault) = self.config.default_vault {
				uri.push_str(&ProviderUrl::encode(vault));
			}
		}

		if self.config.native_references {
			for segment in &self.config.reference_base_path {
				uri.push('/');
				uri.push_str(&ProviderUrl::encode(segment));
			}
		}

		uri
	}

	/// Retrieves a secret from `OnePassword`.
	///
	/// Searches for an item with the title formatted according to the `folder_prefix`
	/// configuration in the appropriate vault. The method looks for a field labeled "value"
	/// first, then falls back to password or concealed fields.
	///
	/// If multiple items exist with the same title, falls back to ID-based lookup
	/// to retrieve the first matching item.
	///
	/// # Arguments
	///
	/// * `project` - The project name
	/// * `key` - The secret key to retrieve
	/// * `profile` - The profile to use for vault selection
	///
	/// # Returns
	///
	/// * `Ok(Some(value))` - The secret value if found
	/// * `Ok(None)` - No secret found with the given key
	/// * `Err(_)` - Authentication or retrieval error
	fn get(&self, project: &str, key: &str, profile: &str) -> Result<Option<SecretString>> {
		if self.config.native_references {
			return self.read_native_reference(key, profile, None);
		}

		let vault = self.get_vault_name(profile);
		let item_name = self.format_item_name(project, key, profile);

		// Try to get the item by title
		let args = vec![
			"item", "get", &item_name, "--vault", &vault, "--format", "json",
		];

		match self.execute_op_command(&args, None) {
			Ok(output) => Self::extract_value_from_item(&output),
			Err(MonosecretError::ProviderOperationFailed(msg)) if msg.contains("isn't an item") => {
				Ok(None)
			}
			Err(MonosecretError::ProviderOperationFailed(msg))
				if msg.contains("More than one item") =>
			{
				// Multiple items with same title - fall back to ID-based lookup
				if let Some(item_id) = self.find_item_id(&item_name, &vault)? {
					let args = vec![
						"item", "get", &item_id, "--vault", &vault, "--format", "json",
					];
					match self.execute_op_command(&args, None) {
						Ok(output) => Self::extract_value_from_item(&output),
						Err(e) => Err(e),
					}
				} else {
					Ok(None)
				}
			}
			Err(e) => Err(e),
		}
	}

	fn get_with_request(
		&self,
		project: &str,
		key: &str,
		profile: &str,
		request: &SecretRequest,
	) -> Result<Option<SecretString>> {
		if self.config.native_references {
			return self.read_native_reference(key, profile, Some(request));
		}

		// If no path, delegate to base `get` (one item per secret), honoring
		// an alternate storage key when the provider ref supplied one.
		let storage_key = request.key.as_deref().unwrap_or(key);
		let Some(path_segments) = &request.path else {
			return self.get(project, storage_key, profile);
		};
		if path_segments.is_empty() {
			return self.get(project, storage_key, profile);
		}

		// Provider-relative lookup for a shared OnePassword item. The first
		// path segment is the item title, and the optional second segment is
		// the section label inside that item:
		// `{ provider = "op", path = ["dotfiles", "forges"] }`.
		let vault = self.get_vault_name(profile);
		let item_name = path_segments[0].as_str();

		// The key to look for: request.key if set, otherwise the secret name.
		let field_key = request.key.as_deref().unwrap_or(key);
		let section_name = path_segments.get(1).map(String::as_str);

		tracing::debug!(
			item = %item_name,
			vault = %vault,
			section = ?section_name,
			field = %field_key,
			"reading 1Password field via provider-relative request"
		);

		let args = vec![
			"item", "get", item_name, "--vault", &vault, "--format", "json",
		];

		let output = match self.execute_op_command(&args, None) {
			Ok(output) => output,
			Err(MonosecretError::ProviderOperationFailed(msg)) if msg.contains("isn't an item") => {
				return Ok(None);
			}
			Err(e) => return Err(e),
		};

		// Parse the item.
		let item: OnePasswordItem = match serde_json::from_str(&output) {
			Ok(item) => item,
			Err(e) => {
				return Err(MonosecretError::ProviderOperationFailed(format!(
					"Failed to parse OnePassword item JSON: {e}"
				)));
			}
		};

		// Find field matching section name and field key.
		for field in &item.fields {
			let section_match = section_name.is_none_or(|section_name| {
				field.section.as_ref().and_then(|s| s.label.as_deref()) == Some(section_name)
			});
			let label_match = field.label.as_deref() == Some(field_key);
			if section_match
				&& label_match
				&& let Some(ref value) = field.value
			{
				return Ok(Some(SecretString::new(value.clone().into())));
			}
		}

		tracing::warn!(
			item = %item_name,
			vault = %vault,
			section = ?section_name,
			field = %field_key,
			"1Password item did not contain requested section/field"
		);
		Ok(None)
	}

	/// Stores or updates a secret in `OnePassword`.
	///
	/// If an item with the same title exists, it updates the "value" field.
	/// Otherwise, it creates a new Secure Note item with the secret data.
	///
	/// # Arguments
	///
	/// * `project` - The project name
	/// * `key` - The secret key
	/// * `value` - The secret value to store
	/// * `profile` - The profile to use for vault selection
	///
	/// # Returns
	///
	/// * `Ok(())` - Secret stored successfully
	/// * `Err(_)` - Storage or authentication error
	///
	/// # Errors
	///
	/// - Authentication required if not signed in
	/// - Item creation/update failures
	/// - Temporary file creation errors
	fn set(&self, project: &str, key: &str, value: &SecretString, profile: &str) -> Result<()> {
		if self.config.native_references {
			return self.set_native_reference(key, value, profile, None);
		}

		let vault = self.get_vault_name(profile);
		let item_name = self.format_item_name(project, key, profile);

		// Check if item exists by listing items (more reliable than get which requires
		// a readable value). This prevents creating duplicates when an item exists
		// but has no extractable value field.
		if let Some(item_id) = self.find_item_id(&item_name, &vault)? {
			// Item exists, update it by ID to avoid "more than one item" ambiguity
			let field_assignment = format!("value={}", value.expose_secret());
			let args = vec![
				"item",
				"edit",
				&item_id,
				"--vault",
				&vault,
				&field_assignment,
			];

			self.execute_op_command(&args, None)?;
		} else {
			// Item doesn't exist, create it
			let template = self.create_item_template(project, key, value, profile);
			let template_json = serde_json::to_string(&template)?;

			let args = vec!["item", "create", "--vault", &vault, "-"];

			self.execute_op_command(&args, Some(&template_json))?;
		}

		Ok(())
	}

	fn set_with_request(
		&self,
		project: &str,
		key: &str,
		value: &SecretString,
		profile: &str,
		request: &SecretRequest,
	) -> Result<()> {
		if self.config.native_references {
			return self.set_native_reference(key, value, profile, Some(request));
		}

		let storage_key = request.key.as_deref().unwrap_or(key);
		self.set(project, storage_key, value, profile)
	}

	/// Retrieves multiple secrets from `OnePassword` in a single batch operation.
	///
	/// This optimized implementation:
	/// 1. Authenticates once (cached)
	/// 2. Lists all items in the vault once to identify which secrets exist
	/// 3. Fetches only the items that exist, using parallel threads
	///
	/// This significantly improves performance compared to fetching secrets one-by-one,
	/// especially when checking many secrets.
	fn get_batch(
		&self,
		project: &str,
		keys: &[&str],
		profile: &str,
	) -> Result<HashMap<String, SecretString>> {
		if keys.is_empty() {
			return Ok(HashMap::new());
		}
		if self.config.native_references {
			let jobs: Vec<&str> = keys.to_vec();
			let mut results = HashMap::new();
			for outcome in collect_bounded_parallel(
				jobs,
				ONEPASSWORD_BATCH_PARALLELISM,
				"Native 1Password batch read worker panicked",
				|key| {
					self.read_native_reference(key, profile, None)
						.map(|value| value.map(|value| (key.to_string(), value)))
				},
			) {
				match outcome {
					Ok(Ok(Some((key, value)))) => {
						results.insert(key, value);
					}
					Ok(Ok(None)) => {}
					Ok(Err(e)) | Err(e) => return Err(e),
				}
			}
			return Ok(results);
		}

		let vault = self.get_vault_name(profile);

		// List all items in the vault once
		let args = vec!["item", "list", "--vault", &vault, "--format", "json"];
		let output = self.execute_op_command(&args, None)?;

		#[derive(Deserialize)]
		struct ListItem {
			id: String,
			title: String,
		}

		let items: Vec<ListItem> = serde_json::from_str(&output).unwrap_or_default();

		// Build a map of item titles to IDs for quick lookup
		let item_map: HashMap<String, String> = items
			.into_iter()
			.map(|item| (item.title, item.id))
			.collect();

		// Find which keys exist and need to be fetched
		let keys_to_fetch: Vec<(&str, String)> = keys
			.iter()
			.filter_map(|key| {
				let item_name = self.format_item_name(project, key, profile);
				item_map.get(&item_name).map(|id| (*key, id.clone()))
			})
			.collect();

		// Fetch items in bounded parallel chunks.
		let outcomes = collect_bounded_parallel(
			keys_to_fetch,
			ONEPASSWORD_BATCH_PARALLELISM,
			"1Password batch read worker panicked",
			|(key, item_id)| {
				let args = vec![
					"item", "get", &item_id, "--vault", &vault, "--format", "json",
				];

				match self.execute_op_command(&args, None) {
					Ok(output) => {
						Self::extract_value_from_item(&output)
							.ok()
							.flatten()
							.map(|value| (key.to_string(), value))
					}
					Err(_) => None,
				}
			},
		);

		let mut results = HashMap::new();
		for outcome in outcomes {
			if let Ok(Some((key, value))) = outcome {
				results.insert(key, value);
			}
		}

		Ok(results)
	}
}

impl Default for OnePasswordProvider {
	/// Creates a `OnePasswordProvider` with default configuration.
	///
	/// Uses interactive authentication and the "Private" vault by default.
	fn default() -> Self {
		Self::new(OnePasswordConfig::default())
	}
}

#[cfg(test)]
mod tests {
	use url::Url;

	use super::*;

	fn config(s: &str) -> OnePasswordConfig {
		OnePasswordConfig::try_from(&ProviderUrl::new(Url::parse(s).unwrap())).unwrap()
	}

	#[test]
	fn try_from_parses_account_and_vault() {
		let c = config("onepassword://work@Production");
		assert_eq!(c.account.as_deref(), Some("work"));
		assert_eq!(c.default_vault.as_deref(), Some("Production"));
		assert_eq!(c.service_account_token, None);
	}

	#[test]
	fn try_from_parses_vault_only() {
		let c = config("onepassword://Production");
		assert_eq!(c.account, None);
		assert_eq!(c.default_vault.as_deref(), Some("Production"));
	}

	#[test]
	fn try_from_token_scheme_captures_token_from_username() {
		let c = config("onepassword+token://ops_tok@Private");
		assert_eq!(c.service_account_token.as_deref(), Some("ops_tok"));
		assert_eq!(c.default_vault.as_deref(), Some("Private"));
		assert_eq!(c.account, None);
	}

	#[test]
	fn try_from_token_scheme_captures_token_from_password() {
		let c = config("onepassword+token://acct:ops_tok@Private");
		assert_eq!(c.service_account_token.as_deref(), Some("ops_tok"));
	}

	#[test]
	fn try_from_ignores_localhost_host() {
		let c = config("onepassword://localhost");
		assert_eq!(c.default_vault, None);
		assert_eq!(c.account, None);
	}

	// Note: the `"1password"` guard arm in `try_from` is effectively unreachable
	// via ProviderUrl, because `Url::parse` rejects schemes that start with a
	// digit (RFC 3986). It therefore cannot be exercised through a real URL.

	#[test]
	fn try_from_rejects_unknown_scheme() {
		let err =
			OnePasswordConfig::try_from(&ProviderUrl::new(Url::parse("keyring://vault").unwrap()))
				.unwrap_err();
		assert!(err.to_string().contains("Invalid scheme"));
	}

	#[test]
	fn get_vault_name_defaults_to_private() {
		let default = OnePasswordProvider::new(OnePasswordConfig::default());
		assert_eq!(default.get_vault_name("any"), "Private");

		let configured = OnePasswordProvider::new(config("onepassword://Production"));
		assert_eq!(configured.get_vault_name("any"), "Production");
	}

	#[test]
	fn format_item_name_default_and_custom() {
		let default = OnePasswordProvider::new(OnePasswordConfig::default());
		assert_eq!(
			default.format_item_name("proj", "KEY", "prod"),
			"monosecret/proj/prod/KEY"
		);

		let custom = OnePasswordProvider::new(OnePasswordConfig {
			folder_prefix: Some("{project}-{key}".to_string()),
			..Default::default()
		});
		assert_eq!(custom.format_item_name("proj", "KEY", "prod"), "proj-KEY");
	}

	#[test]
	fn uri_for_account_round_trips() {
		let provider = OnePasswordProvider::new(config("onepassword://work@Production"));
		assert_eq!(provider.uri(), "onepassword://work@Production");
	}

	#[test]
	fn uri_for_token_does_not_leak_secret() {
		let provider =
			OnePasswordProvider::new(config("onepassword+token://ops_secret_tok@Private"));
		let uri = provider.uri();
		assert_eq!(uri, "onepassword+token://Private");
		assert!(!uri.contains("ops_secret_tok"));
	}
}

#[cfg(all(test, unix))]
mod dependency_env_tests {
	use std::fs;
	use std::os::unix::fs::PermissionsExt;

	use secrecy::ExposeSecret;

	use super::*;

	fn write_op_stub(script: &std::path::Path, log: &std::path::Path) {
		let script_body = format!(
			r#"#!/bin/sh
printf '%s\n' "$OP_SERVICE_ACCOUNT_TOKEN" >> '{}'
printf '{{"fields":[{{"id":"value","type":"CONCEALED","label":"value","value":"%s"}}]}}\n' "$OP_SERVICE_ACCOUNT_TOKEN"
"#,
			log.display()
		);
		fs::write(script, script_body).unwrap();
		let mut permissions = fs::metadata(script).unwrap().permissions();
		permissions.set_mode(0o755);
		fs::set_permissions(script, permissions).unwrap();
	}

	#[test]
	fn dependency_token_is_command_scoped_for_every_op_invocation() {
		let temp = tempfile::TempDir::new().unwrap();
		let script = temp.path().join("op-stub");
		let log = temp.path().join("calls.log");
		write_op_stub(&script, &log);

		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			service_account_token: None,
			default_vault: Some("Development".into()),
			..OnePasswordConfig::default()
		});
		provider.op_command = script.display().to_string();
		provider
			.configure_dependency_secrets(&[
				("IGNORED".into(), SecretString::new("ignored".into())),
				(
					"OP_SERVICE_ACCOUNT_TOKEN".into(),
					SecretString::new("dependency-token".into()),
				),
			])
			.unwrap();

		let first = provider
			.get("project", "API_KEY", "default")
			.unwrap()
			.unwrap();
		let second = provider
			.get("project", "API_KEY", "default")
			.unwrap()
			.unwrap();

		assert_eq!(first.expose_secret(), "dependency-token");
		assert_eq!(second.expose_secret(), "dependency-token");
		assert_eq!(
			fs::read_to_string(log).unwrap(),
			"dependency-token\ndependency-token\n"
		);
	}

	#[test]
	fn explicit_uri_token_takes_precedence_over_dependency_token() {
		let temp = tempfile::TempDir::new().unwrap();
		let script = temp.path().join("op-stub");
		let log = temp.path().join("calls.log");
		write_op_stub(&script, &log);

		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			service_account_token: Some("uri-token".into()),
			default_vault: Some("Development".into()),
			..OnePasswordConfig::default()
		});
		provider.op_command = script.display().to_string();
		provider
			.configure_dependency_secrets(&[(
				"OP_SERVICE_ACCOUNT_TOKEN".into(),
				SecretString::new("dependency-token".into()),
			)])
			.unwrap();

		let value = provider
			.get("project", "API_KEY", "default")
			.unwrap()
			.unwrap();

		assert_eq!(value.expose_secret(), "uri-token");
		assert_eq!(fs::read_to_string(log).unwrap(), "uri-token\n");
	}
}

#[cfg(test)]
mod native_and_batch_tests {
	use std::fs;

	use secrecy::ExposeSecret;

	use super::*;

	#[cfg(unix)]
	fn write_fake_op(temp_dir: &tempfile::TempDir, log: &std::path::Path) -> std::path::PathBuf {
		use std::os::unix::fs::PermissionsExt;

		let script = temp_dir.path().join("op");
		fs::write(
            &script,
            format!(
                r#"#!/usr/bin/env sh
printf '%s\n' "$*" >> '{0}'
case "$1 $2" in
  read*)
    case "$2" in
      op://Development/dotfiles/forges/GITHUB_TOKEN)
        printf '%s\n' 'native-github-token'
        ;;
      op://Development/dotfiles/GITHUB_TOKEN)
        printf '%s\n' 'native-root-github-token'
        ;;
      op://Development/dotfiles/error/GITHUB_TOKEN)
        printf '%s\n' 'permission denied' >&2
        exit 1
        ;;
      *)
        printf '%s\n' 'not found' >&2
        exit 1
        ;;
    esac
    ;;
  "item edit")
    printf '%s\n' 'edited'
    ;;
  "item create")
    cat >> '{0}'
    printf '%s\n' 'created'
    ;;
  "item list")
    printf '%s\n' '[{{"id":"id-stored-item","title":"monosecret/proj/default/STORED_ITEM"}},{{"id":"id-broken","title":"monosecret/proj/default/BROKEN"}},{{"id":"id-duplicate","title":"monosecret/proj/default/DUPLICATE_ITEM"}}]'
    ;;
  "item get")
    case "$3" in
      id-stored-item)
        printf '%s\n' '{{"fields":[{{"id":"value","type":"STRING","label":"value","value":"from-batch-item"}}]}}'
        ;;
      *STORED_ITEM*)
        printf '%s\n' '{{"fields":[{{"id":"value","type":"STRING","label":"value","value":"from-stored-item"}}]}}'
        ;;
      *DUPLICATE_ITEM*)
        printf '%s\n' 'More than one item matching this title was found' >&2
        exit 1
        ;;
      id-duplicate)
        printf '%s\n' '{{"fields":[{{"id":"value","type":"STRING","label":"value","value":"from-duplicate-id"}}]}}'
        ;;
      dotfiles)
        printf '%s\n' '{{"fields":[{{"id":"github","type":"CONCEALED","label":"GITHUB_TOKEN","section":{{"label":"forges"}},"value":"from-dotfiles-item"}}]}}'
        ;;
      *)
        printf '%s\n' "isn't an item" >&2
        exit 1
        ;;
    esac
    ;;
  *)
    printf '%s\n' '[]'
    ;;
esac
"#,
                log.display()
            ),
        )
        .expect("write fake op script");
		let mut permissions = fs::metadata(&script)
			.expect("stat fake op script")
			.permissions();
		permissions.set_mode(0o755);
		fs::set_permissions(&script, permissions).expect("make fake op executable");
		script
	}

	fn init_test_tracing() {}

	fn call_log_with_sorted_tail(path: &std::path::Path, prefix_len: usize) -> String {
		let contents = fs::read_to_string(path).expect("read fake op call log");
		let mut lines: Vec<_> = contents.lines().map(str::to_string).collect();
		let split_at = prefix_len.min(lines.len());
		let mut tail = lines.split_off(split_at);
		tail.sort();
		lines.extend(tail);
		let mut normalized = lines.join("\n");
		normalized.push('\n');
		normalized
	}

	#[test]
	fn collect_bounded_parallel_maps_worker_panics_to_provider_errors() {
		let panic_hook = std::panic::take_hook();
		std::panic::set_hook(Box::new(|_| {}));
		let outcomes = collect_bounded_parallel(vec![1, 2], 1, "worker failed", |job| {
			assert!(job != 2, "boom");
			job
		});
		std::panic::set_hook(panic_hook);

		assert_eq!(outcomes[0].as_ref().copied().unwrap(), 1);
		let err = outcomes[1].as_ref().expect_err("panic maps to error");
		assert!(err.to_string().contains("worker failed"));
	}

	#[test]
	#[cfg(unix)]
	fn onepassword_get_batch_fetches_legacy_items_with_bounded_workers() {
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let batch = provider
			.get_batch("proj", &["STORED_ITEM", "BROKEN", "MISSING"], "default")
			.expect("batch legacy reads");

		assert_eq!(batch["STORED_ITEM"].expose_secret(), "from-batch-item");
		assert!(!batch.contains_key("BROKEN"));
		assert!(!batch.contains_key("MISSING"));

		let calls = call_log_with_sorted_tail(&log, 1);
		insta::assert_snapshot!(calls);
	}

	#[test]
	#[cfg(unix)]
	fn onepassword_get_falls_back_to_id_lookup_when_title_is_ambiguous() {
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let value = provider
			.get("proj", "DUPLICATE_ITEM", "default")
			.expect("fallback to ID lookup should succeed")
			.expect("value should be found via id-duplicate");
		assert_eq!(value.expose_secret(), "from-duplicate-id");

		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!(calls);
	}

	#[test]
	#[cfg(unix)]
	fn op_get_batch_propagates_native_reference_errors() {
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string(), "error".to_string()],
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let err = provider
			.get_batch("dotfiles", &["GITHUB_TOKEN"], "default")
			.expect_err("native batch read should propagate non-missing errors");

		insta::assert_snapshot!(err.to_string());
	}

	#[test]
	#[cfg(unix)]
	fn onepassword_get_with_request_uses_key_hint_when_path_is_absent_or_empty() {
		init_test_tracing();
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig::default());
		provider.op_command = op.display().to_string();

		let no_path_request = SecretRequest {
			path: None,
			key: Some("STORED_ITEM".to_string()),
		};
		let empty_path_request = SecretRequest {
			path: Some(Vec::new()),
			key: Some("STORED_ITEM".to_string()),
		};

		let no_path_value = provider
			.get_with_request("proj", "SECRET_NAME", "default", &no_path_request)
			.expect("read with key hint and no path")
			.expect("value from fake op");
		let empty_path_value = provider
			.get_with_request("proj", "SECRET_NAME", "default", &empty_path_request)
			.expect("read with key hint and empty path")
			.expect("value from fake op");

		assert_eq!(no_path_value.expose_secret(), "from-stored-item");
		assert_eq!(empty_path_value.expose_secret(), "from-stored-item");

		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!(calls);

		let missing_value = provider
			.get("proj", "MISSING_ITEM", "default")
			.expect("missing item should not be a hard error");
		assert!(missing_value.is_none());
	}

	#[test]
	fn onepassword_uri_path_becomes_provider_relative_item_root() {
		let provider_url =
			ProviderUrl::new(url::Url::parse("onepassword+token://Development/dotfiles").unwrap());
		let config = OnePasswordConfig::try_from(&provider_url).unwrap();

		assert_eq!(config.default_vault.as_deref(), Some("Development"));
		assert_eq!(config.folder_prefix.as_deref(), Some("dotfiles/{key}"));
		assert_eq!(config.service_account_token, None);

		let provider_url = ProviderUrl::new(
			url::Url::parse("onepassword://Development/monosecret/{project}/{profile}/{key}")
				.unwrap(),
		);
		let config = OnePasswordConfig::try_from(&provider_url).unwrap();
		assert_eq!(
			config.folder_prefix.as_deref(),
			Some("monosecret/{project}/{profile}/{key}")
		);
	}

	#[test]
	fn op_uri_path_becomes_native_reference_base_path() {
		let provider_url =
			ProviderUrl::new(url::Url::parse("op+token://Development/dotfiles").unwrap());
		let config = OnePasswordConfig::try_from(&provider_url).unwrap();
		let provider = OnePasswordProvider::new(config.clone());

		assert!(config.native_references);
		assert_eq!(config.default_vault.as_deref(), Some("Development"));
		assert_eq!(config.reference_base_path, vec!["dotfiles"]);
		assert_eq!(config.folder_prefix, None);
		assert_eq!(provider.uri(), "op://Development/dotfiles");

		let op_token_provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			service_account_token: Some("token".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string()],
			..OnePasswordConfig::default()
		});
		assert_eq!(op_token_provider.uri(), "op+token://Development/dotfiles");

		let legacy_token_provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			service_account_token: Some("token".to_string()),
			..OnePasswordConfig::default()
		});
		assert_eq!(
			legacy_token_provider.uri(),
			"onepassword+token://Development"
		);

		let legacy_url =
			ProviderUrl::new(url::Url::parse("onepassword://Development/dotfiles").unwrap());
		let legacy_config = OnePasswordConfig::try_from(&legacy_url).unwrap();
		assert!(!legacy_config.native_references);
		assert_eq!(
			legacy_config.folder_prefix.as_deref(),
			Some("dotfiles/{key}")
		);
		assert!(legacy_config.reference_base_path.is_empty());
	}

	#[test]
	#[cfg(unix)]
	fn op_command_auth_failure_returns_helpful_error() {
		use std::os::unix::fs::PermissionsExt;

		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let op = temp_dir.path().join("op-auth-fails");
		fs::write(
			&op,
			"#!/usr/bin/env sh\nprintf '%s\\n' 'not currently signed in' >&2\nexit 1\n",
		)
		.expect("write fake op");
		let mut permissions = fs::metadata(&op).expect("metadata").permissions();
		permissions.set_mode(0o755);
		fs::set_permissions(&op, permissions).expect("chmod fake op");

		let mut provider = OnePasswordProvider::new(OnePasswordConfig::default());
		provider.op_command = op.display().to_string();

		let err = provider
			.execute_op_command(&["item", "list"], None)
			.expect_err("auth failures should be rewritten");
		insta::assert_snapshot!(err.to_string());
	}

	#[test]
	#[cfg(unix)]
	fn op_get_without_request_reads_native_reference_from_uri_base() {
		init_test_tracing();
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string()],
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let value = provider
			.get("dotfiles", "GITHUB_TOKEN", "default")
			.expect("read native reference")
			.expect("value from fake op");
		assert_eq!(value.expose_secret(), "native-root-github-token");

		provider
			.set(
				"dotfiles",
				"GITHUB_TOKEN",
				&SecretString::new("new-token".into()),
				"default",
			)
			.expect("edit native reference without request");

		let batch = provider
			.get_batch("dotfiles", &["GITHUB_TOKEN", "MISSING"], "default")
			.expect("batch native reads");
		assert_eq!(
			batch["GITHUB_TOKEN"].expose_secret(),
			"native-root-github-token"
		);
		assert!(!batch.contains_key("MISSING"));

		let calls = call_log_with_sorted_tail(&log, 3);
		insta::assert_snapshot!(calls);
	}

	#[test]
	#[cfg(unix)]
	fn op_get_without_item_path_returns_none_and_set_errors() {
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			..OnePasswordConfig::default()
		});
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		provider.op_command = op.display().to_string();

		let value = provider
			.get("dotfiles", "GITHUB_TOKEN", "default")
			.expect("short native reference should not hard fail");
		assert!(value.is_none());

		let err = provider
			.native_item_and_assignment(
				"GITHUB_TOKEN",
				&SecretString::new("new-token".into()),
				None,
			)
			.expect_err("native set needs an item path");
		insta::assert_snapshot!(err.to_string());
	}

	#[test]
	#[cfg(unix)]
	fn op_get_with_request_propagates_non_missing_errors() {
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string()],
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: Some(vec!["error".to_string()]),
			key: None,
		};
		let err = provider
			.get_with_request("dotfiles", "GITHUB_TOKEN", "default", &request)
			.expect_err("permission errors should propagate");
		insta::assert_snapshot!(err.to_string());
	}

	#[test]
	#[cfg(unix)]
	fn onepassword_set_with_request_uses_key_hint_for_legacy_storage() {
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: None,
			key: Some("STORED_ITEM".to_string()),
		};
		provider
			.set_with_request(
				"dotfiles",
				"SECRET_NAME",
				&SecretString::new("new-token".into()),
				"default",
				&request,
			)
			.expect("legacy set with key hint");

		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!(calls);

		let batch = provider
			.get_batch("dotfiles", &["STORED_ITEM"], "default")
			.expect("legacy get_batch should still run through item listing");
		assert!(batch.is_empty());
	}

	#[test]
	#[cfg(unix)]
	fn op_set_with_request_uses_field_without_section_when_path_is_item_only() {
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: Some(vec!["dotfiles".to_string()]),
			key: None,
		};
		provider
			.set_with_request(
				"dotfiles",
				"GITHUB_TOKEN",
				&SecretString::new("new-token".into()),
				"default",
				&request,
			)
			.expect("edit native field without section");

		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!(calls);
	}

	#[test]
	#[cfg(unix)]
	fn op_get_with_request_reads_native_reference() {
		init_test_tracing();
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string()],
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: Some(vec!["forges".to_string()]),
			key: None,
		};
		let value = provider
			.get_with_request("dotfiles", "GITHUB_TOKEN", "default", &request)
			.expect("read native reference")
			.expect("value from fake op");

		assert_eq!(value.expose_secret(), "native-github-token");
		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!(calls);
	}

	#[test]
	#[cfg(unix)]
	fn op_set_with_request_edits_existing_native_reference() {
		init_test_tracing();
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string()],
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: Some(vec!["forges".to_string()]),
			key: None,
		};
		provider
			.set_with_request(
				"dotfiles",
				"GITHUB_TOKEN",
				&SecretString::new("new-token".into()),
				"default",
				&request,
			)
			.expect("edit existing native reference");

		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!(calls);
	}

	#[test]
	#[cfg(unix)]
	fn op_set_with_request_rejects_missing_native_reference() {
		init_test_tracing();
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			native_references: true,
			reference_base_path: vec!["dotfiles".to_string()],
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: Some(vec!["missing".to_string()]),
			key: None,
		};
		let err = provider
			.set_with_request(
				"dotfiles",
				"GITHUB_TOKEN",
				&SecretString::new("new-token".into()),
				"default",
				&request,
			)
			.expect_err("missing native reference should not be created");

		insta::assert_snapshot!(
			"op_set_with_request_missing_native_reference_error",
			err.to_string()
		);
		let calls = fs::read_to_string(log).expect("read fake op call log");
		insta::assert_snapshot!("op_set_with_request_missing_native_reference_calls", calls);
	}

	#[test]
	#[cfg(unix)]
	fn onepassword_get_with_request_uses_path_item_and_section() {
		init_test_tracing();
		let temp_dir = tempfile::TempDir::new().expect("create temp dir");
		let log = temp_dir.path().join("calls.log");
		let op = write_fake_op(&temp_dir, &log);
		let mut provider = OnePasswordProvider::new(OnePasswordConfig {
			default_vault: Some("Development".to_string()),
			..OnePasswordConfig::default()
		});
		provider.op_command = op.display().to_string();

		let request = SecretRequest {
			path: Some(vec!["dotfiles".to_string(), "forges".to_string()]),
			key: None,
		};
		let value = provider
			.get_with_request("dotfiles", "GITHUB_TOKEN", "default", &request)
			.expect("read provider-relative field")
			.expect("value from fake op");

		assert_eq!(value.expose_secret(), "from-dotfiles-item");
		let calls = fs::read_to_string(&log).expect("read fake op call log");
		insta::assert_snapshot!("onepassword_get_with_request_initial_calls", calls);

		let missing_request = SecretRequest {
			path: Some(vec!["dotfiles".to_string(), "packages".to_string()]),
			key: Some("CARGO_REGISTRY_TOKEN".to_string()),
		};
		let missing_value = provider
			.get_with_request(
				"dotfiles",
				"CARGO_REGISTRY_TOKEN",
				"default",
				&missing_request,
			)
			.expect("missing section/field should not be a hard error");
		assert!(missing_value.is_none());

		let missing_item_request = SecretRequest {
			path: Some(vec!["missing-item".to_string(), "forges".to_string()]),
			key: Some("GITHUB_TOKEN".to_string()),
		};
		let missing_item_value = provider
			.get_with_request("dotfiles", "GITHUB_TOKEN", "default", &missing_item_request)
			.expect("missing item should not be a hard error");
		assert!(missing_item_value.is_none());
		insta::assert_snapshot!(
			"onepassword_get_with_request_all_calls",
			fs::read_to_string(&log).unwrap()
		);
	}
}