secretspec-ipc 0.21.1

Independent Rust implementation of the SecretSpec IPC protocols
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
use crate::error::{Error, Result};
use crate::{ABSOLUTE_MAX_FRAME_BYTES, MAX_IN_FLIGHT, MIN_FRAME_BYTES};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

pub const RESOLVER_PROTOCOL: &str = "secretspec.resolver";
pub const PROVIDER_PROTOCOL: &str = "secretspec.provider";
pub const PROTOCOL_VERSION: u32 = 1;

/// Stands in for a secret in `Debug` output, so logging a protocol message
/// never prints the value it carries.
pub(crate) struct Redacted;

impl std::fmt::Debug for Redacted {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("<redacted>")
    }
}

pub mod rpc {
    /// Return this endpoint's OpenRPC description without initializing
    /// application state (0.21+).
    pub const DISCOVER: &str = "rpc.discover";
    pub const INITIALIZE: &str = "rpc.initialize";
    pub const CANCEL: &str = "rpc.cancel";
    pub const SHUTDOWN: &str = "rpc.shutdown";

    pub const ALL: &[&str] = &[DISCOVER, INITIALIZE, CANCEL, SHUTDOWN];
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Product {
    pub name: String,
    pub version: String,
}

impl Product {
    pub fn validate(&self) -> Result<()> {
        validate_nonempty_bytes("product name", &self.name, 256)?;
        validate_nonempty_bytes("product version", &self.version, 256)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Limits {
    pub max_frame_bytes: usize,
    pub max_in_flight: usize,
}

impl Limits {
    pub const PRE_NEGOTIATION: Self = Self {
        max_frame_bytes: ABSOLUTE_MAX_FRAME_BYTES,
        max_in_flight: 1,
    };

    pub fn validate(self) -> Result<()> {
        if !(MIN_FRAME_BYTES..=ABSOLUTE_MAX_FRAME_BYTES).contains(&self.max_frame_bytes) {
            return Err(Error::Protocol(
                "max_frame_bytes is outside the version 1 range",
            ));
        }
        if !(1..=MAX_IN_FLIGHT).contains(&self.max_in_flight) {
            return Err(Error::Protocol(
                "max_in_flight is outside the version 1 range",
            ));
        }
        Ok(())
    }

    pub fn select(self, peer: Self) -> Result<Self> {
        self.validate()?;
        peer.validate()?;
        Ok(Self {
            max_frame_bytes: self.max_frame_bytes.min(peer.max_frame_bytes),
            max_in_flight: self.max_in_flight.min(peer.max_in_flight),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InitializeParams<A> {
    pub protocol: String,
    pub versions: Vec<u32>,
    pub client: Product,
    pub limits: Limits,
    /// Methods this client can answer when the server calls back on the same
    /// session (0.21+). Empty, and omitted on the wire, for a client that
    /// answers none, which is every client before this field existed.
    ///
    /// The server's `methods` say what a client may ask for. These say
    /// what the server may ask of the client, and a server MUST NOT send a
    /// method that is not listed here. A consumer with no way to reach a person
    /// therefore advertises nothing and is told so immediately, rather than
    /// waiting out a deadline on an interaction that was never going to arrive.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub client_methods: Vec<String>,
    pub application: A,
}

impl<A> InitializeParams<A> {
    pub fn validate_common(&self, expected_protocol: &str) -> Result<()> {
        if self.protocol != expected_protocol {
            return Err(Error::Protocol(
                "initialization selected the wrong protocol",
            ));
        }
        if self.versions.is_empty()
            || self.versions.contains(&0)
            || self.versions.iter().collect::<BTreeSet<_>>().len() != self.versions.len()
        {
            return Err(Error::Protocol(
                "versions must be distinct positive integers",
            ));
        }
        self.client.validate()?;
        self.limits.validate()?;
        validate_capabilities(&self.client_methods)?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InitializeResult<A> {
    pub protocol: String,
    pub version: u32,
    pub server: Product,
    pub methods: Vec<String>,
    #[serde(default)]
    pub capabilities: BTreeMap<String, bool>,
    pub limits: Limits,
    pub application: A,
}

impl<A> InitializeResult<A> {
    pub fn validate_common(
        &self,
        expected_protocol: &str,
        offered_versions: &[u32],
        offered_limits: Limits,
    ) -> Result<()> {
        if self.protocol != expected_protocol || !offered_versions.contains(&self.version) {
            return Err(Error::Protocol(
                "server selected an unsupported protocol version",
            ));
        }
        self.server.validate()?;
        validate_capabilities(&self.methods)?;
        validate_feature_capabilities(&self.capabilities)?;
        self.limits.validate()?;
        if self.limits.max_frame_bytes > offered_limits.max_frame_bytes
            || self.limits.max_in_flight > offered_limits.max_in_flight
        {
            return Err(Error::Protocol("server selected an unoffered limit"));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CancelParams {
    pub id: crate::RequestId,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EmptyParams {}

/// Methods a server calls back on the client over the same session (0.21+).
///
/// This is the only direction reversal in version 1, and it exists because the
/// endpoint that knows a value is missing is never the process that can ask a
/// person for it. A stdio resolver has no terminal at all: its stdin and stdout
/// are the protocol. Prior art solves this the same way, from D-Bus Secret
/// Service returning a prompt object the client must drive, to the editor
/// protocols whose servers request input rather than drawing it.
///
/// A server MUST NOT send one of these unless the client advertised it in
/// [`InitializeParams::client_methods`].
pub mod callback {
    pub mod method {
        /// Ask the client to obtain one secret value from a person (0.21+).
        pub const PROMPT: &str = "client.prompt";
        /// Ask the client for one provider authentication credential (0.21+).
        pub const CREDENTIAL: &str = "client.credential";

        pub const RESOLVER: &[&str] = &[PROMPT];
        pub const PROVIDER: &[&str] = &[CREDENTIAL];
        pub const ALL: &[&str] = &[PROMPT, CREDENTIAL];
    }

    use super::*;

    /// Everything the person answering needs, and nothing else.
    ///
    /// There is no free-form message: the text a client shows is built by the
    /// client from these fields, so a server cannot use the prompt to put
    /// arbitrary attacker-influenced text in front of a person. The declared
    /// name and the credential-free provider URI are already known to the
    /// session that asked.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct PromptParams {
        /// The declared name whose value is being asked for.
        pub name: String,
        /// The active profile, so a person answering can tell which one they
        /// are provisioning.
        pub profile: String,
        /// Credential-free display URI of the provider that will store the
        /// answer, or absent when the answer is not persisted.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub target_provider: Option<String>,
    }

    impl PromptParams {
        pub fn validate(&self) -> Result<()> {
            validate_nonempty_bytes("secret name has an invalid byte length", &self.name, 4096)?;
            validate_nonempty_bytes("profile has an invalid byte length", &self.profile, 4096)?;
            validate_optional_bytes(
                "target provider has an invalid byte length",
                self.target_provider.as_deref(),
                32768,
            )
        }
    }

    /// The answer carries a secret and is treated exactly like a resolved
    /// value: never logged, and dropped as soon as it is copied.
    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct PromptResult {
        pub value: String,
    }

    impl std::fmt::Debug for PromptResult {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter
                .debug_struct("PromptResult")
                .field("value", &super::Redacted)
                .finish()
        }
    }

    impl PromptResult {
        pub fn validate(&self) -> Result<()> {
            // An empty answer is refused for the same reason `resolver.set`
            // refuses an empty value: stores disagree about whether one means
            // absent or present-and-empty. A person who wants to decline
            // cancels instead.
            validate_nonempty_bytes(
                "prompt answer has an invalid byte length",
                &self.value,
                ABSOLUTE_MAX_FRAME_BYTES,
            )
        }
    }

    /// One semantic provider credential requested while an endpoint is
    /// initializing or refreshing its authentication (0.21+).
    ///
    /// `scope` is a stable, credential-free account or store identity chosen
    /// by the provider from its configured URI. The client binds it to the
    /// already selected provider principal before consulting its credential
    /// broker, so it cannot address another provider's credentials.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct CredentialParams {
        pub name: String,
        pub scope: String,
        pub required: bool,
    }

    impl CredentialParams {
        pub fn validate(&self) -> Result<()> {
            validate_semantic_name(&self.name)?;
            validate_nonempty_bytes(
                "provider credential scope has an invalid byte length",
                &self.scope,
                4096,
            )
        }
    }

    /// A broker lookup is either a secret value or an ordinary miss. Missing
    /// is not a transport failure: the endpoint may try another authentication
    /// mechanism or return its own actionable authentication error.
    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
    pub enum CredentialResult {
        Found { value: String },
        Missing,
    }

    impl std::fmt::Debug for CredentialResult {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Found { .. } => formatter
                    .debug_struct("Found")
                    .field("value", &super::Redacted)
                    .finish(),
                Self::Missing => formatter.write_str("Missing"),
            }
        }
    }

    impl CredentialResult {
        pub fn validate(&self) -> Result<()> {
            match self {
                Self::Found { value } => validate_nonempty_bytes(
                    "provider credential has an invalid byte length",
                    value,
                    ABSOLUTE_MAX_FRAME_BYTES,
                ),
                Self::Missing => Ok(()),
            }
        }
    }
}

fn validate_semantic_name(name: &str) -> Result<()> {
    let mut chars = name.chars();
    if !matches!(chars.next(), Some('a'..='z'))
        || chars.any(|character| !matches!(character, 'a'..='z' | '0'..='9' | '_'))
        || name.len() > 256
    {
        return Err(Error::Protocol("invalid credential semantic name"));
    }
    Ok(())
}

pub(crate) fn validate_capabilities(capabilities: &[String]) -> Result<()> {
    if capabilities.iter().collect::<BTreeSet<_>>().len() != capabilities.len() {
        return Err(Error::Protocol("capabilities must be distinct"));
    }
    for capability in capabilities {
        validate_nonempty_bytes("capability", capability, 256)?;
    }
    Ok(())
}

pub(crate) fn validate_feature_capabilities(capabilities: &BTreeMap<String, bool>) -> Result<()> {
    for capability in capabilities.keys() {
        validate_nonempty_bytes("capability", capability, 256)?;
    }
    Ok(())
}

pub(crate) fn validate_nonempty_bytes(label: &'static str, value: &str, max: usize) -> Result<()> {
    if value.is_empty() || value.len() > max {
        Err(Error::Protocol(label))
    } else {
        Ok(())
    }
}

pub(crate) fn validate_optional_bytes(
    label: &'static str,
    value: Option<&str>,
    max: usize,
) -> Result<()> {
    if value.is_some_and(|value| value.len() > max) {
        Err(Error::Protocol(label))
    } else {
        Ok(())
    }
}

pub(crate) fn deserialize_required_nullable<'de, D, T>(
    deserializer: D,
) -> std::result::Result<Option<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    Option::<T>::deserialize(deserializer)
}

pub mod resolver {
    use super::*;

    pub mod method {
        pub const GET: &str = "resolver.get";
        pub const RELEASE: &str = "resolver.release";
        /// Store one declared name (0.21+).
        pub const SET: &str = "resolver.set";
        /// Remove one declared name's stored value (0.21+).
        pub const DELETE: &str = "resolver.delete";

        /// Every method version 1 defines. What an endpoint advertises is a
        /// subset of this: see [`super::CAPABILITIES`] and
        /// [`super::MUTATION_CAPABILITIES`].
        pub const ALL: &[&str] = &[GET, RELEASE, SET, DELETE];
    }

    /// Methods every version 1 endpoint answers. A client that negotiates a
    /// session without all of them is talking to something that is not a
    /// resolver, so it refuses the endpoint rather than degrading.
    ///
    pub const CAPABILITIES: &[&str] = &[method::GET, method::RELEASE];

    /// Methods that write to the store (0.21+).
    ///
    /// These are optional and separately advertised: resolution is the reason
    /// the protocol exists, while storage is authority a consumer usually does
    /// not need. An endpoint serving a read-only consumer, or one an operator
    /// started read-only, advertises none of them, and the client will not send
    /// a method that was not advertised.
    pub const MUTATION_CAPABILITIES: &[&str] = &[method::SET, method::DELETE];

    /// Rejects a capability list that no version 1 endpoint could honor.
    ///
    /// Only the base methods are required. Nothing here constrains the
    /// mutation methods against each other: an endpoint that can store but not
    /// remove is a store that only appends, which is a real backend and not a
    /// malformed advertisement.
    pub fn validate_capabilities(capabilities: &[String]) -> Result<()> {
        if !CAPABILITIES
            .iter()
            .all(|method| capabilities.iter().any(|item| item == method))
        {
            return Err(Error::Protocol(
                "resolver capability set omits a required method",
            ));
        }
        Ok(())
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
    pub enum Manifest {
        Path { path: String },
        Inline { toml: String, base_dir: String },
    }

    impl Manifest {
        pub fn validate(&self) -> Result<()> {
            match self {
                Self::Path { path } => validate_absolute_path(path),
                Self::Inline { toml, base_dir } => {
                    if toml.len() > ABSOLUTE_MAX_FRAME_BYTES {
                        return Err(Error::Protocol("inline manifest is too large"));
                    }
                    validate_absolute_path(base_dir)
                }
            }
        }

        pub const fn kind(&self) -> &'static str {
            match self {
                Self::Path { .. } => "path",
                Self::Inline { .. } => "inline",
            }
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct InitializeApplication {
        pub manifest: Manifest,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub provider: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub profile: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub scope: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub reason: Option<String>,
        /// App-requested authorization lifetime in milliseconds. The provider
        /// may shorten, extend, or reject this request after user approval.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub requested_authorization_duration_ms: Option<u64>,
    }

    impl InitializeApplication {
        pub fn validate(&self) -> Result<()> {
            self.manifest.validate()?;
            self.validate_options()
        }

        /// Validate client inputs without interpreting paths on the client's OS
        /// (0.21+). The resolver still performs its native path validation.
        #[cfg(any(feature = "tokio", feature = "blocking"))]
        pub(crate) fn validate_for_connection(&self) -> Result<()> {
            let path = match &self.manifest {
                Manifest::Path { path } => path,
                Manifest::Inline { toml, base_dir } => {
                    if toml.len() > ABSOLUTE_MAX_FRAME_BYTES {
                        return Err(Error::Protocol("inline manifest is too large"));
                    }
                    base_dir
                }
            };
            validate_nonempty_bytes("path has an invalid byte length", path, 32768)?;
            let bytes = path.as_bytes();
            let windows_drive = bytes.len() >= 3
                && bytes[0].is_ascii_alphabetic()
                && bytes[1] == b':'
                && matches!(bytes[2], b'/' | b'\\');
            let windows_unc = path.starts_with("\\\\");
            let absolute = path.starts_with('/') || windows_drive || windows_unc;
            let normalized = if windows_drive || windows_unc {
                !path
                    .split(['/', '\\'])
                    .any(|part| matches!(part, "." | ".."))
            } else {
                !path.split('/').any(|part| matches!(part, "." | ".."))
            };
            if !absolute || !normalized || path.contains('\0') {
                return Err(Error::Protocol(
                    "manifest path must be absolute and lexically normalized on the resolver machine",
                ));
            }
            self.validate_options()
        }

        fn validate_options(&self) -> Result<()> {
            validate_optional_bytes(
                "provider override is too long",
                self.provider.as_deref(),
                32768,
            )?;
            validate_optional_bytes("profile is too long", self.profile.as_deref(), 4096)?;
            validate_optional_bytes("scope is too long", self.scope.as_deref(), 4096)?;
            validate_optional_bytes("reason is too long", self.reason.as_deref(), 4096)?;
            if self.requested_authorization_duration_ms == Some(0) {
                return Err(Error::Protocol(
                    "requested authorization duration must be positive",
                ));
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct InitializedApplication {
        pub manifest_kind: String,
        pub supports_inline_manifest: bool,
    }

    impl InitializedApplication {
        pub fn validate(&self) -> Result<()> {
            if matches!(self.manifest_kind.as_str(), "path" | "inline") {
                Ok(())
            } else {
                Err(Error::Protocol("invalid initialized manifest kind"))
            }
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    /// Which shape of value the caller can accept.
    ///
    /// Both spellings describe what the returned string contains: the secret
    /// itself, or a location to read it from. The file the resolver writes for
    /// the `Path` form is how that location is produced, not something the
    /// caller selects, which is why it does not appear here.
    pub enum Representation {
        Auto,
        Value,
        Path,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct Purpose {
        pub consumer: String,
        pub operation: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub host: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub path: Option<String>,
    }

    impl Purpose {
        pub fn validate(&self) -> Result<()> {
            validate_nonempty_bytes(
                "purpose consumer has an invalid byte length",
                &self.consumer,
                256,
            )?;
            validate_nonempty_bytes(
                "purpose operation has an invalid byte length",
                &self.operation,
                256,
            )?;
            validate_optional_bytes("purpose host is too long", self.host.as_deref(), 4096)?;
            validate_optional_bytes("purpose path is too long", self.path.as_deref(), 4096)
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct GetParams {
        pub name: String,
        pub representation: Representation,
        pub purpose: Purpose,
    }

    impl GetParams {
        pub fn validate(&self) -> Result<()> {
            validate_nonempty_bytes("secret name has an invalid byte length", &self.name, 4096)?;
            self.purpose.validate()
        }
    }

    /// Where a resolved value came from.
    ///
    /// Provenance, not an authorization input. The set is closed for the
    /// resolver and open for the client, under the same rule as
    /// [`crate::error::ErrorKind`]: a later revision naming a new origin, such
    /// as a dynamically issued credential, must not kill a session with an
    /// older client. A client that treats provenance as security-relevant reads
    /// [`Source::Unrecognized`] as "not one of the origins I can vouch for" and
    /// decides accordingly, which it could not do if the frame failed to parse.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub enum Source {
        Provider,
        Generated,
        Default,
        Composed,
        /// An origin this revision does not define. A resolver never sends it.
        Unrecognized,
    }

    impl Source {
        pub const fn as_str(self) -> &'static str {
            match self {
                Self::Provider => "provider",
                Self::Generated => "generated",
                Self::Default => "default",
                Self::Composed => "composed",
                Self::Unrecognized => "unrecognized",
            }
        }

        pub const DEFINED: &'static [Self] = &[
            Self::Provider,
            Self::Generated,
            Self::Default,
            Self::Composed,
        ];

        pub fn from_wire(source: &str) -> Self {
            Self::DEFINED
                .iter()
                .copied()
                .find(|defined| defined.as_str() == source)
                .unwrap_or(Self::Unrecognized)
        }
    }

    impl Serialize for Source {
        fn serialize<S: serde::Serializer>(
            &self,
            serializer: S,
        ) -> std::result::Result<S::Ok, S::Error> {
            serializer.serialize_str(self.as_str())
        }
    }

    impl<'de> Deserialize<'de> for Source {
        fn deserialize<D: serde::Deserializer<'de>>(
            deserializer: D,
        ) -> std::result::Result<Self, D::Error> {
            Ok(Self::from_wire(&String::deserialize(deserializer)?))
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct UndeclaredResult {
        pub status: UndeclaredStatus,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum UndeclaredStatus {
        Undeclared,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct MissingResult {
        pub status: MissingStatus,
        pub required: bool,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum MissingStatus {
        Missing,
    }

    impl std::fmt::Debug for ResolvedValueResult {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter
                .debug_struct("ResolvedValueResult")
                .field("status", &self.status)
                .field("representation", &self.representation)
                .field("value", &super::Redacted)
                .field("source", &self.source)
                .field("source_provider", &self.source_provider)
                .field("expires_at_unix_ms", &self.expires_at_unix_ms)
                .field("revision", &self.revision)
                .field("refresh_at_unix_ms", &self.refresh_at_unix_ms)
                .finish()
        }
    }

    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ResolvedValueResult {
        pub status: ResolvedStatus,
        pub representation: ValueRepresentation,
        pub value: String,
        pub source: Source,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub source_provider: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub expires_at_unix_ms: Option<u64>,
        /// Opaque revision of the returned logical value (0.21+).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub revision: Option<crate::Revision>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub refresh_at_unix_ms: Option<u64>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ResolvedPathResult {
        pub status: ResolvedStatus,
        pub representation: PathRepresentation,
        pub path: String,
        /// Releases the resolver-owned file behind [`Self::path`]. Named apart
        /// from a provider credential lease, which is an unrelated concept
        /// with its own issuance and revocation.
        pub path_lease_id: String,
        pub source: Source,
        #[serde(skip_serializing_if = "Option::is_none")]
        pub source_provider: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub expires_at_unix_ms: Option<u64>,
        /// Opaque revision of the returned logical value (0.21+).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub revision: Option<crate::Revision>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub refresh_at_unix_ms: Option<u64>,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum ResolvedStatus {
        Resolved,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum ValueRepresentation {
        Value,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum PathRepresentation {
        Path,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(untagged)]
    pub enum GetResult {
        Undeclared(UndeclaredResult),
        Missing(MissingResult),
        Value(ResolvedValueResult),
        Path(ResolvedPathResult),
    }

    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct SetParams {
        pub name: String,
        pub value: String,
        pub purpose: Purpose,
    }

    impl std::fmt::Debug for SetParams {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter
                .debug_struct("SetParams")
                .field("name", &self.name)
                .field("value", &super::Redacted)
                .field("purpose", &self.purpose)
                .finish()
        }
    }

    impl SetParams {
        pub fn validate(&self) -> Result<()> {
            validate_nonempty_bytes("secret name has an invalid byte length", &self.name, 4096)?;
            // An empty value means "no value" to some stores and "a value that
            // happens to be empty" to others, and the difference decides
            // whether a later read finds the secret. It never travels as a
            // write; a caller that wants the value gone sends `resolver.delete`.
            validate_nonempty_bytes(
                "secret value has an invalid byte length",
                &self.value,
                ABSOLUTE_MAX_FRAME_BYTES,
            )?;
            self.purpose.validate()
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum StoredStatus {
        Stored,
    }

    /// A write is either accepted or refused, so there is one shape here where
    /// a read has four. A name the manifest does not declare has no address to
    /// write to, and unlike an absent value it is not something the caller can
    /// route around, so it is an error rather than a status.
    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct SetResult {
        pub status: StoredStatus,
        /// Credential-free URI of the provider that took the write, for a
        /// consumer that reports the destination back to a human. Absent when
        /// the endpoint does not name it.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub target_provider: Option<String>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct DeleteParams {
        pub name: String,
        pub purpose: Purpose,
    }

    impl DeleteParams {
        pub fn validate(&self) -> Result<()> {
            validate_nonempty_bytes("secret name has an invalid byte length", &self.name, 4096)?;
            self.purpose.validate()
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum DeletedStatus {
        Deleted,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct DeleteResult {
        pub status: DeletedStatus,
        /// `false` when the store held nothing for this name. Removal is
        /// idempotent, so that is a success and not an error.
        pub deleted: bool,
        /// Credential-free URI of the provider the removal was addressed to.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub target_provider: Option<String>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct ReleaseParams {
        pub path_lease_ids: Vec<String>,
    }

    impl ReleaseParams {
        pub fn validate(&self) -> Result<()> {
            if self.path_lease_ids.len() > 256 {
                return Err(Error::Protocol("release contains more than 256 lease IDs"));
            }
            for lease in &self.path_lease_ids {
                validate_nonempty_bytes("lease ID has an invalid byte length", lease, 256)?;
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ReleaseResult {
        pub released: usize,
    }

    fn validate_absolute_path(path: &str) -> Result<()> {
        validate_nonempty_bytes("path has an invalid byte length", path, 32768)?;
        let path = std::path::Path::new(path);
        if !path.is_absolute()
            || path.components().any(|component| {
                matches!(
                    component,
                    std::path::Component::CurDir | std::path::Component::ParentDir
                )
            })
        {
            return Err(Error::Protocol(
                "manifest path must be absolute and lexically normalized",
            ));
        }
        Ok(())
    }
}

pub mod provider {
    use super::*;

    pub mod method {
        use super::*;
        use serde::de::DeserializeOwned;

        /// Associates one provider method with its wire parameter and result
        /// types so callers cannot accidentally deserialize a method into the
        /// wrong response shape.
        pub trait Method {
            const NAME: &'static str;
            type Params: Serialize;
            type Result: DeserializeOwned;
        }

        macro_rules! methods {
            ($(($type:ident, $constant:ident, $name:literal, $params:ty, $result:ty)),+ $(,)?) => {
                $(
                    pub const $constant: &str = $name;

                    #[derive(Debug, Clone, Copy)]
                    pub struct $type;

                    impl Method for $type {
                        const NAME: &'static str = $constant;
                        type Params = $params;
                        type Result = $result;
                    }
                )+

                pub const ALL: &[&str] = &[$($constant),+];
            };
        }

        methods!(
            (
                ResolveAddress,
                RESOLVE_ADDRESS,
                "provider.resolve_address",
                AddressParams,
                ResolveAddressResult
            ),
            (Get, GET, "provider.get", AddressParams, GetResult),
            (
                GetMany,
                GET_MANY,
                "provider.get_many",
                GetManyParams,
                GetManyResult
            ),
            (
                Exists,
                EXISTS,
                "provider.exists",
                AddressParams,
                ExistsResult
            ),
            (Set, SET, "provider.set", SetParams, StoredResult),
            (
                SetExpiring,
                SET_EXPIRING,
                "provider.set_expiring",
                SetExpiringParams,
                StoredResult
            ),
            (
                Delete,
                DELETE,
                "provider.delete",
                AddressParams,
                DeletedResult
            ),
            (Clear, CLEAR, "provider.clear", ClearParams, ClearResult),
            (
                CheckWritable,
                CHECK_WRITABLE,
                "provider.check_writable",
                AddressParams,
                EmptyResult
            ),
            (
                CheckDeletable,
                CHECK_DELETABLE,
                "provider.check_deletable",
                AddressParams,
                EmptyResult
            ),
            (
                DescribeWriteTarget,
                DESCRIBE_WRITE_TARGET,
                "provider.describe_write_target",
                AddressParams,
                DescribeWriteTargetResult
            ),
            (
                Reflect,
                REFLECT,
                "provider.reflect",
                ReflectParams,
                ReflectResult
            ),
        );
    }

    pub const CAPABILITIES: &[&str] = method::ALL;

    pub fn validate_capabilities(capabilities: &[String]) -> Result<()> {
        let has = |method: &str| capabilities.iter().any(|item| item == method);
        if !has(method::RESOLVE_ADDRESS)
            || ![method::GET, method::EXISTS, method::SET]
                .iter()
                .any(|method| has(method))
            || (has(method::GET_MANY) && !has(method::GET))
            || (has(method::SET_EXPIRING) && !has(method::SET))
        {
            return Err(Error::Protocol(
                "provider capability set violates version 1 dependencies",
            ));
        }
        Ok(())
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    /// Resolver-declared provider session context. Available starting with
    /// SecretSpec 0.21.
    pub struct ApplicationContext {
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub project: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub profile: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub base_dir: Option<String>,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub reason: Option<String>,
        /// App-requested authorization lifetime in milliseconds. This is an
        /// untrusted default for an approval surface, not an authorization.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub requested_authorization_duration_ms: Option<u64>,
    }

    impl ApplicationContext {
        pub fn validate(&self) -> Result<()> {
            for (label, value) in [
                ("provider project", self.project.as_deref()),
                ("provider profile", self.profile.as_deref()),
            ] {
                if let Some(value) = value {
                    validate_nonempty_bytes(label, value, 4096)?;
                }
            }
            validate_optional_bytes(
                "provider base directory is too long",
                self.base_dir.as_deref(),
                32768,
            )?;
            validate_optional_bytes("provider reason is too long", self.reason.as_deref(), 4096)?;
            if self.requested_authorization_duration_ms == Some(0) {
                return Err(Error::Protocol(
                    "requested authorization duration must be positive",
                ));
            }
            if let Some(base_dir) = &self.base_dir
                && !std::path::Path::new(base_dir).is_absolute()
            {
                return Err(Error::Protocol("provider base directory must be absolute"));
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct InitializeApplication {
        pub scheme: String,
        pub uri: String,
        pub context: ApplicationContext,
    }

    impl InitializeApplication {
        pub fn validate(&self) -> Result<()> {
            validate_scheme(&self.scheme)?;
            validate_nonempty_bytes("provider URI has an invalid byte length", &self.uri, 32768)?;
            self.context.validate()?;
            let uri_scheme = self.uri.split_once(':').map(|(scheme, _)| scheme);
            if uri_scheme != Some(self.scheme.as_str()) {
                return Err(Error::Protocol(
                    "provider URI scheme does not match initialization scheme",
                ));
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum CoordinateName {
        Field,
        Vault,
        Section,
        Version,
    }

    impl CoordinateName {
        pub const fn as_str(self) -> &'static str {
            match self {
                Self::Field => "field",
                Self::Vault => "vault",
                Self::Section => "section",
                Self::Version => "version",
            }
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    pub enum Persistence {
        Persist,
        Ephemeral,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct Metadata {
        pub name: String,
        pub display_uri: String,
        pub supported_coordinates: Vec<CoordinateName>,
        pub generated_value_persistence: Persistence,
        pub prompted_value_persistence: Persistence,
        pub storage_identity: String,
        pub entry_container_identity: String,
        #[serde(deserialize_with = "deserialize_required_nullable")]
        pub physical_store_path: Option<String>,
    }

    impl Metadata {
        pub fn validate(&self) -> Result<()> {
            validate_scheme(&self.name)?;
            for value in [
                &self.display_uri,
                &self.storage_identity,
                &self.entry_container_identity,
            ] {
                if value.len() > 32768 {
                    return Err(Error::Protocol("provider metadata is too long"));
                }
            }
            if self
                .supported_coordinates
                .iter()
                .collect::<BTreeSet<_>>()
                .len()
                != self.supported_coordinates.len()
            {
                return Err(Error::Protocol("supported coordinates must be distinct"));
            }
            if let Some(path) = &self.physical_store_path
                && !std::path::Path::new(path).is_absolute()
            {
                return Err(Error::Protocol("physical_store_path must be absolute"));
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct InitializedApplication {
        pub provider: Metadata,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct Coordinates {
        pub item: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub field: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub vault: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub section: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        pub version: Option<String>,
    }

    impl Coordinates {
        pub fn validate(&self) -> Result<()> {
            validate_nonempty_bytes("item has an invalid byte length", &self.item, 4096)?;
            for value in [&self.field, &self.vault, &self.section, &self.version] {
                validate_optional_bytes("coordinate is too long", value.as_deref(), 4096)?;
            }
            Ok(())
        }

        pub fn unsupported(&self, supported: &[CoordinateName]) -> Option<CoordinateName> {
            [
                (CoordinateName::Field, self.field.is_some()),
                (CoordinateName::Vault, self.vault.is_some()),
                (CoordinateName::Section, self.section.is_some()),
                (CoordinateName::Version, self.version.is_some()),
            ]
            .into_iter()
            .find_map(|(name, present)| (present && !supported.contains(&name)).then_some(name))
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
    #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
    pub enum Address {
        Convention {
            project: String,
            profile: String,
            key: String,
        },
        Native {
            coordinates: Coordinates,
        },
    }

    impl Address {
        pub fn validate(&self) -> Result<()> {
            match self {
                Self::Convention {
                    project,
                    profile,
                    key,
                } => {
                    for value in [project, profile, key] {
                        if value.len() > 4096 {
                            return Err(Error::Protocol(
                                "convention address component is too long",
                            ));
                        }
                    }
                    Ok(())
                }
                Self::Native { coordinates } => coordinates.validate(),
            }
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct AddressParams {
        pub address: Address,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ResolveAddressResult {
        pub coordinates: Coordinates,
    }

    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(tag = "status", rename_all = "snake_case")]
    pub enum GetResult {
        Found {
            value: String,
            #[serde(deserialize_with = "deserialize_required_nullable")]
            expires_at_unix_ms: Option<u64>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            revision: Option<crate::Revision>,
        },
        Missing,
    }

    impl std::fmt::Debug for GetResult {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::Found {
                    value: _,
                    expires_at_unix_ms,
                    revision,
                } => formatter
                    .debug_struct("Found")
                    .field("value", &super::Redacted)
                    .field("expires_at_unix_ms", expires_at_unix_ms)
                    .field("revision", revision)
                    .finish(),
                Self::Missing => formatter.write_str("Missing"),
            }
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct NamedRequest {
        pub name: String,
        pub address: Address,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct GetManyParams {
        pub requests: Vec<NamedRequest>,
    }

    impl GetManyParams {
        pub fn validate(&self) -> Result<()> {
            if self.requests.len() > 1024 {
                return Err(Error::Protocol("get_many contains more than 1024 requests"));
            }
            let mut names = BTreeSet::new();
            for request in &self.requests {
                validate_nonempty_bytes(
                    "batch name has an invalid byte length",
                    &request.name,
                    4096,
                )?;
                if !names.insert(&request.name) {
                    return Err(Error::Protocol("batch names must be unique"));
                }
                request.address.validate()?;
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
    pub struct NamedGetResult {
        pub name: String,
        #[serde(flatten)]
        pub outcome: GetResult,
    }

    impl<'de> Deserialize<'de> for NamedGetResult {
        fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            #[derive(Deserialize)]
            struct Found {
                name: String,
                status: FoundStatus,
                value: String,
                #[serde(deserialize_with = "deserialize_required_nullable")]
                expires_at_unix_ms: Option<u64>,
                #[serde(default, skip_serializing_if = "Option::is_none")]
                revision: Option<crate::Revision>,
            }

            #[derive(Deserialize)]
            struct Missing {
                name: String,
                status: MissingStatus,
            }

            #[derive(Deserialize)]
            #[serde(rename_all = "snake_case")]
            enum FoundStatus {
                Found,
            }

            #[derive(Deserialize)]
            #[serde(rename_all = "snake_case")]
            enum MissingStatus {
                Missing,
            }

            #[derive(Deserialize)]
            #[serde(untagged)]
            enum Repr {
                Found(Found),
                Missing(Missing),
            }

            match Repr::deserialize(deserializer)? {
                Repr::Found(Found {
                    name,
                    status: FoundStatus::Found,
                    value,
                    expires_at_unix_ms,
                    revision,
                }) => Ok(Self {
                    name,
                    outcome: GetResult::Found {
                        value,
                        expires_at_unix_ms,
                        revision,
                    },
                }),
                Repr::Missing(Missing {
                    name,
                    status: MissingStatus::Missing,
                }) => Ok(Self {
                    name,
                    outcome: GetResult::Missing,
                }),
            }
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct GetManyResult {
        pub results: Vec<NamedGetResult>,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ExistsResult {
        pub exists: bool,
    }

    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct SetParams {
        pub address: Address,
        pub value: String,
    }

    impl std::fmt::Debug for SetParams {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter
                .debug_struct("SetParams")
                .field("address", &self.address)
                .field("value", &super::Redacted)
                .finish()
        }
    }

    impl SetParams {
        pub fn validate(&self) -> Result<()> {
            self.address.validate()
        }
    }

    #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct SetExpiringParams {
        pub address: Address,
        pub value: String,
        pub ttl_ms: u64,
    }

    impl std::fmt::Debug for SetExpiringParams {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter
                .debug_struct("SetExpiringParams")
                .field("address", &self.address)
                .field("value", &super::Redacted)
                .field("ttl_ms", &self.ttl_ms)
                .finish()
        }
    }

    impl SetExpiringParams {
        pub fn validate(&self) -> Result<()> {
            self.address.validate()?;
            if self.ttl_ms == 0 {
                return Err(Error::Protocol("provider expiry must be positive"));
            }
            Ok(())
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct StoredResult {
        pub stored: bool,
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct DeletedResult {
        pub deleted: bool,
    }

    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
    pub struct EmptyResult {}

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
    pub enum ClearScope {
        All,
        Convention { project: String, profile: String },
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct ClearParams {
        pub scope: ClearScope,
    }

    impl ClearParams {
        pub fn validate(&self) -> Result<()> {
            match &self.scope {
                ClearScope::All => Ok(()),
                ClearScope::Convention { project, profile } => {
                    validate_optional_bytes("clear project is too long", Some(project), 4096)?;
                    validate_optional_bytes("clear profile is too long", Some(profile), 4096)
                }
            }
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ClearResult {
        pub cleared: usize,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct DescribeWriteTargetResult {
        pub description: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct ReflectParams {
        pub project: String,
        pub profile: String,
    }

    impl ReflectParams {
        pub fn validate(&self) -> Result<()> {
            validate_optional_bytes("reflection project is too long", Some(&self.project), 4096)?;
            validate_optional_bytes("reflection profile is too long", Some(&self.profile), 4096)
        }
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    #[serde(deny_unknown_fields)]
    pub struct ReflectedDeclaration {
        pub description: String,
        pub required: bool,
        #[serde(rename = "ref")]
        pub reference: Coordinates,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ReflectResult {
        pub schema_version: u32,
        pub declarations: BTreeMap<String, ReflectedDeclaration>,
    }

    impl ReflectResult {
        pub fn validate(&self) -> Result<()> {
            if self.schema_version != 1 {
                return Err(Error::Protocol("unsupported reflection schema version"));
            }
            for (name, declaration) in &self.declarations {
                validate_optional_bytes("reflected name is too long", Some(name), 4096)?;
                validate_optional_bytes(
                    "reflected description is too long",
                    Some(&declaration.description),
                    4096,
                )?;
                declaration.reference.validate()?;
            }
            Ok(())
        }
    }

    fn validate_scheme(scheme: &str) -> Result<()> {
        let mut chars = scheme.chars();
        let first = chars.next();
        if !matches!(first, Some('a'..='z'))
            || chars.any(|character| !matches!(character, 'a'..='z' | '0'..='9' | '-'))
        {
            return Err(Error::Protocol("invalid provider scheme"));
        }
        Ok(())
    }
}

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

    #[test]
    fn debug_never_prints_secret_values() {
        const SECRET: &str = "hunter2";
        let address = provider::Address::Convention {
            project: "app".into(),
            profile: "default".into(),
            key: "TOKEN".into(),
        };
        let value = resolver::ResolvedValueResult {
            status: resolver::ResolvedStatus::Resolved,
            representation: resolver::ValueRepresentation::Value,
            value: SECRET.into(),
            source: resolver::Source::Provider,
            source_provider: None,
            expires_at_unix_ms: None,
            revision: None,
            refresh_at_unix_ms: None,
        };
        let rendered = [
            format!(
                "{:?}",
                callback::PromptResult {
                    value: SECRET.into()
                }
            ),
            format!(
                "{:?}",
                callback::CredentialResult::Found {
                    value: SECRET.into()
                }
            ),
            format!("{:?}", resolver::GetResult::Value(value)),
            format!(
                "{:?}",
                resolver::SetParams {
                    name: "TOKEN".into(),
                    value: SECRET.into(),
                    purpose: resolver::Purpose {
                        consumer: "test".into(),
                        operation: "store".into(),
                        host: None,
                        path: None,
                    },
                }
            ),
            format!(
                "{:?}",
                provider::GetResult::Found {
                    value: SECRET.into(),
                    expires_at_unix_ms: None,
                    revision: None,
                }
            ),
            format!(
                "{:?}",
                provider::SetParams {
                    address: address.clone(),
                    value: SECRET.into(),
                }
            ),
            format!(
                "{:?}",
                provider::SetExpiringParams {
                    address,
                    value: SECRET.into(),
                    ttl_ms: 1,
                }
            ),
            format!("{:?}", crate::provider::SecretValue::new(SECRET.into())),
        ];
        for debug in rendered {
            assert!(!debug.contains(SECRET), "{debug}");
            assert!(debug.contains("<redacted>"), "{debug}");
        }
    }

    #[test]
    fn limit_selection_never_increases_an_offer() {
        let selected = Limits {
            max_frame_bytes: 32_768,
            max_in_flight: 16,
        }
        .select(Limits {
            max_frame_bytes: 8_192,
            max_in_flight: 4,
        })
        .unwrap();
        assert_eq!(selected.max_frame_bytes, 8_192);
        assert_eq!(selected.max_in_flight, 4);
    }

    #[test]
    fn provider_uri_scheme_must_match() {
        let application = provider::InitializeApplication {
            scheme: "factorseal".into(),
            uri: "other://default".into(),
            context: provider::ApplicationContext {
                project: Some("demo".into()),
                profile: Some("default".into()),
                base_dir: None,
                reason: None,
                requested_authorization_duration_ms: None,
            },
        };
        assert!(application.validate().is_err());
    }

    #[test]
    fn provider_credential_requests_use_bounded_semantic_names_and_scopes() {
        let valid = callback::CredentialParams {
            name: "client_secret_2".into(),
            scope: "https://service.example/account/team-a".into(),
            required: true,
        };
        assert!(valid.validate().is_ok());
        for name in ["", "ClientSecret", "2fa", "client-secret"] {
            assert!(
                callback::CredentialParams {
                    name: name.into(),
                    ..valid.clone()
                }
                .validate()
                .is_err()
            );
        }
        assert!(
            callback::CredentialParams {
                scope: String::new(),
                ..valid.clone()
            }
            .validate()
            .is_err()
        );
        assert!(
            callback::CredentialParams {
                scope: "x".repeat(4097),
                ..valid
            }
            .validate()
            .is_err()
        );
    }

    #[test]
    fn provider_credential_results_distinguish_a_miss_from_an_empty_secret() {
        assert!(callback::CredentialResult::Missing.validate().is_ok());
        assert!(
            callback::CredentialResult::Found {
                value: "token".into()
            }
            .validate()
            .is_ok()
        );
        assert!(
            callback::CredentialResult::Found {
                value: String::new()
            }
            .validate()
            .is_err()
        );
    }

    #[test]
    fn named_provider_batch_results_are_flattened_and_closed() {
        let found = serde_json::from_value::<provider::NamedGetResult>(serde_json::json!({
            "name": "token",
            "status": "found",
            "value": "secret",
            "expires_at_unix_ms": null
        }))
        .unwrap();
        assert_eq!(
            found,
            provider::NamedGetResult {
                name: "token".into(),
                outcome: provider::GetResult::Found {
                    value: "secret".into(),
                    expires_at_unix_ms: None,
                    revision: None,
                }
            }
        );
        assert!(
            serde_json::from_value::<provider::NamedGetResult>(serde_json::json!({
                "name": "token",
                "status": "missing",
                "extra": true
            }))
            .is_ok()
        );
    }

    #[test]
    fn provider_empty_results_ignore_future_members() {
        assert!(serde_json::from_value::<provider::EmptyResult>(serde_json::json!({})).is_ok());
        assert!(
            serde_json::from_value::<provider::EmptyResult>(serde_json::json!({"stored": true}))
                .is_ok()
        );
    }

    #[test]
    fn schema_required_nullable_members_cannot_be_omitted() {
        assert!(
            serde_json::from_value::<resolver::InitializeApplication>(serde_json::json!({
                "manifest": {"kind": "path", "path": "/tmp/secretspec.toml"},
                "provider": null,
                "profile": null,
                "scope": null
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<provider::InitializeApplication>(serde_json::json!({
                "scheme": "factorseal",
                "uri": "factorseal://default",
                "context": {
                    "project": "demo",
                    "profile": "default",
                    "base_dir": null
                }
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<provider::GetResult>(serde_json::json!({
                "status": "found",
                "value": "secret"
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<resolver::ResolvedValueResult>(serde_json::json!({
                "status": "resolved",
                "representation": "value",
                "value": "secret",
                "source": "provider",
                "source_provider": null,
                "expires_at_unix_ms": null
            }))
            .is_err()
        );
    }

    #[test]
    fn requested_authorization_duration_is_optional_but_must_be_positive() {
        let without_request =
            serde_json::from_value::<resolver::InitializeApplication>(serde_json::json!({
                "manifest": {"kind": "path", "path": "/tmp/secretspec.toml"},
                "provider": null,
                "profile": null,
                "scope": null,
                "reason": null
            }))
            .unwrap();
        assert_eq!(without_request.requested_authorization_duration_ms, None);

        let zero = resolver::InitializeApplication {
            requested_authorization_duration_ms: Some(0),
            ..without_request
        };
        assert!(zero.validate().is_err());
    }
}