Skip to main content

kmip_protocol/types/
request.rs

1//! Rust types for sserializing KMIP requests.
2use std::fmt;
3use std::{ops::Deref, str::FromStr};
4
5use enum_ordinalize::Ordinalize;
6
7use crate::ttlv::fast_scan::{FastScanError, FastScanner};
8use crate::ttlv::format::{FormatResult, Formatter, TruncationError};
9use crate::ttlv::types::Tag;
10
11use super::common::{
12    ApplicationData, ApplicationNamespace, AttributeIndex, AttributeName, AttributeValue, CompromiseOccurrenceDate,
13    CryptographicAlgorithm, CryptographicLength, CryptographicParameters, CryptographicUsageMask, Data, DataLength,
14    KeyCompressionType, KeyFormatType, KeyMaterial, LinkType, LinkedObjectIdentifier, NameType, NameValue, ObjectType,
15    Operation, RevocationMessage, RevocationReasonCode, UniqueBatchItemID, UniqueIdentifier,
16};
17
18use super::impl_ttlv_serde;
19
20pub fn from_slice(buffer: &[u8]) -> std::result::Result<RequestMessage, FastScanError> {
21    let (res, rest) = crate::ttlv::from_slice(buffer, RequestMessage::fast_scan)?;
22    if !rest.is_empty() {
23        Err(FastScanError::assert())
24    } else {
25        Ok(res)
26    }
27}
28
29pub fn to_vec(payload: RequestPayload, credential: Option<CredentialValue>) -> Result<Vec<u8>, TruncationError> {
30    let operation = payload.operation();
31
32    let request = RequestMessage(
33        RequestHeader(
34            payload.protocol_version(),
35            Option::<MaximumResponseSize>::None,
36            credential.map(Authentication::build),
37            None,
38            None,
39            BatchCount(1),
40        ),
41        vec![BatchItem(operation, Option::<UniqueBatchItemID>::None, payload)],
42    );
43
44    crate::ttlv::to_vec(|f| request.format(f))
45}
46
47/// See KMIP 1.0 section 2.1.1 [Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581155).
48#[derive(Clone, Debug, PartialEq, Eq)]
49pub struct Attribute(pub AttributeName, pub Option<AttributeIndex>, pub AttributeValue);
50
51impl Attribute {
52    pub fn name(&self) -> &AttributeName {
53        &self.0
54    }
55
56    pub fn index(&self) -> Option<&AttributeIndex> {
57        self.1.as_ref()
58    }
59
60    pub fn value(&self) -> &AttributeValue {
61        &self.2
62    }
63}
64
65/// Helper functions to simplifying including KMIP TemplateAttributes in requests.
66///
67/// The set of possible attributes and their textual names are specified by the KMIP 1.0 spec in Section 3 Attributes.
68/// We offer various Attribute constructor functions that avoid the need for the caller to couple the right
69/// AttributeName and AttributeValue pairs together and to use the correct AttributeName text value and instead just Do
70/// The Right Thing for them.
71impl Attribute {
72    /// See KMIP 1.0 section 3.1 Unique Identifier.
73    #[allow(non_snake_case)]
74    pub fn UniqueIdentifier(value: String) -> Self {
75        Attribute(
76            AttributeName("Unique Identifier".into()),
77            Option::<AttributeIndex>::None,
78            AttributeValue::UniqueIdentifier(UniqueIdentifier(value)),
79        )
80    }
81
82    /// See KMIP 1.0 section 3.2 Name.
83    #[allow(non_snake_case)]
84    pub fn Name(value: String) -> Self {
85        Attribute(
86            AttributeName("Name".into()),
87            Option::<AttributeIndex>::None,
88            AttributeValue::Name(Name(NameValue(value), NameType::UninterpretedTextString)),
89        )
90    }
91
92    /// See KMIP 1.0 section 3.2 Name.
93    #[allow(non_snake_case)]
94    pub fn URI(value: String) -> Self {
95        Attribute(
96            AttributeName("Name".into()),
97            Option::<AttributeIndex>::None,
98            AttributeValue::Name(Name(NameValue(value), NameType::URI)),
99        )
100    }
101
102    /// See KMIP 1.0 section 3.3 Object Type.
103    #[allow(non_snake_case)]
104    pub fn ObjectType(value: ObjectType) -> Self {
105        Attribute(
106            AttributeName("Object Type".into()),
107            Option::<AttributeIndex>::None,
108            AttributeValue::ObjectType(value),
109        )
110    }
111
112    /// See KMIP 1.0 section 3.4 Cryptographic Algorithm.
113    #[allow(non_snake_case)]
114    pub fn CryptographicAlgorithm(value: CryptographicAlgorithm) -> Self {
115        Attribute(
116            AttributeName("Cryptographic Algorithm".into()),
117            Option::<AttributeIndex>::None,
118            AttributeValue::CryptographicAlgorithm(value),
119        )
120    }
121
122    /// See KMIP 1.0 section 3.5 Cryptographic Length.
123    #[allow(non_snake_case)]
124    pub fn CryptographicLength(value: i32) -> Self {
125        Attribute(
126            AttributeName("Cryptographic Length".into()),
127            Option::<AttributeIndex>::None,
128            AttributeValue::CryptographicLength(CryptographicLength(value)),
129        )
130    }
131
132    /// See KMIP 1.0 section 3.6 Cryptographic Parameters.
133    #[allow(non_snake_case)]
134    pub fn CryptographicParameters(cryptographic_parameters: CryptographicParameters) -> Self {
135        Attribute(
136            AttributeName("Cryptographic Parameters".into()),
137            Option::<AttributeIndex>::None,
138            cryptographic_parameters.into(),
139        )
140    }
141
142    // See KMIP 1.0 section 3.13 Operation Policy Name.
143    // Not implemented.
144
145    /// See KMIP 1.0 section 3.14 Cryptographic Usage Mask.
146    #[allow(non_snake_case)]
147    pub fn CryptographicUsageMask(value: CryptographicUsageMask) -> Self {
148        Attribute(
149            AttributeName("Cryptographic Usage Mask".into()),
150            Option::<AttributeIndex>::None,
151            AttributeValue::CryptographicUsageMask(value),
152        )
153    }
154
155    /// See KMIP 1.0 section 3.24 Activation Date.
156    #[allow(non_snake_case)]
157    pub fn ActivationDate(value: i64) -> Self {
158        Attribute(
159            AttributeName("Activation Date".into()),
160            Option::<AttributeIndex>::None,
161            AttributeValue::ActivationDate(value),
162        )
163    }
164
165    /// See KMIP 1.0 section 3.28 Object Group.
166    #[allow(non_snake_case)]
167    pub fn ObjectGroup(value: String) -> Self {
168        Attribute(
169            AttributeName("Object Group".into()),
170            Option::<AttributeIndex>::None,
171            AttributeValue::ObjectGroup(value),
172        )
173    }
174
175    /// See KMIP 1.0 section 3.29 Link.
176    #[allow(non_snake_case)]
177    pub fn Link(link_type: LinkType, linked_object_identifier: LinkedObjectIdentifier) -> Self {
178        Attribute(
179            AttributeName("Link".into()),
180            Option::<AttributeIndex>::None,
181            AttributeValue::Link(link_type, linked_object_identifier),
182        )
183    }
184
185    /// See KMIP 1.0 section 3.30 Application Specific Information.
186    #[allow(non_snake_case)]
187    pub fn ApplicationSpecificInformation(
188        application_namespace: ApplicationNamespace,
189        application_data: ApplicationData,
190    ) -> Self {
191        Attribute(
192            AttributeName("Application Specific Information".into()),
193            Option::<AttributeIndex>::None,
194            AttributeValue::ApplicationSpecificInformation(application_namespace, application_data),
195        )
196    }
197
198    /// See KMIP 1.0 section 3.31 Contact Information.
199    #[allow(non_snake_case)]
200    pub fn ContactInformation(value: String) -> Self {
201        Attribute(
202            AttributeName("Contact Information".into()),
203            Option::<AttributeIndex>::None,
204            AttributeValue::ContactInformation(value),
205        )
206    }
207}
208
209impl_ttlv_serde!(struct Attribute as 0x420008 {
210    fast_scan = |scanner| {
211        let name = AttributeName::fast_scan(&mut scanner)?;
212        let index = AttributeIndex::fast_scan_opt(&mut scanner)?;
213        let value = AttributeValue::fast_scan(&mut scanner, &name)?;
214        Self(name, index, value)
215    };
216
217    format = |&self, formatter| {
218        self.0.format(&mut formatter)?;
219        if let Some(index) = &self.1 {
220            index.format(&mut formatter)?;
221        }
222        self.2.format(&mut formatter)?;
223    };
224});
225
226// TODO: Create TemplateAttribute, CommonTemplateAttributes,
227// PrivateKeyTemplateAttributes and PublicKeyTemplateAttributes using a macro.
228
229/// See KMIP 1.0 section 2.1.8 [Template-Attribute Structures](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581162).
230#[derive(Clone, Debug, PartialEq, Eq)]
231pub struct TemplateAttribute {
232    template_names: Option<Vec<Name>>,
233    attributes: Option<Vec<Attribute>>,
234}
235
236impl TemplateAttribute {
237    pub fn new(attributes: Vec<Attribute>) -> Self {
238        Self {
239            template_names: None,
240            attributes: Some(attributes),
241        }
242    }
243
244    pub fn new_with_names(attributes: Vec<Attribute>, names: Vec<Name>) -> Self {
245        Self {
246            template_names: (!names.is_empty()).then_some(names),
247            attributes: (!attributes.is_empty()).then_some(attributes),
248        }
249    }
250
251    pub fn with_template_name(mut self, template_name: &'static str) -> Self {
252        // TODO: SAFETY
253        let template_name = Name::from_str(template_name).unwrap();
254        let mut template_names = self.template_names.unwrap_or_default();
255        template_names.push(template_name);
256        self.template_names = Some(template_names);
257        self
258    }
259
260    pub fn template_names(&self) -> &[Name] {
261        match &self.template_names {
262            Some(template_names) => template_names.as_slice(),
263            None => &[],
264        }
265    }
266
267    pub fn attributes(&self) -> &[Attribute] {
268        match &self.attributes {
269            Some(attributes) => attributes.as_slice(),
270            None => &[],
271        }
272    }
273}
274
275impl_ttlv_serde!(struct TemplateAttribute {
276    #[option+vec] template_names: Name,
277    #[option+vec] attributes: Attribute,
278} as 0x420091);
279
280/// See KMIP 1.0 section 2.1.8 [Template-Attribute Structures](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581162).
281#[derive(Clone, Debug, PartialEq, Eq)]
282pub struct CommonTemplateAttribute {
283    template_names: Option<Vec<Name>>,
284    attributes: Option<Vec<Attribute>>,
285}
286
287impl CommonTemplateAttribute {
288    pub fn new(attributes: Vec<Attribute>) -> Self {
289        Self {
290            template_names: None,
291            attributes: Some(attributes),
292        }
293    }
294
295    pub fn new_with_names(attributes: Vec<Attribute>, names: Vec<Name>) -> Self {
296        Self {
297            template_names: (!names.is_empty()).then_some(names),
298            attributes: (!attributes.is_empty()).then_some(attributes),
299        }
300    }
301
302    pub fn with_template_name(mut self, template_name: &'static str) -> Self {
303        // TODO: SAFETY
304        let template_name = Name::from_str(template_name).unwrap();
305        let mut template_names = self.template_names.unwrap_or_default();
306        template_names.push(template_name);
307        self.template_names = Some(template_names);
308        self
309    }
310
311    pub fn template_names(&self) -> &[Name] {
312        match &self.template_names {
313            Some(template_names) => template_names.as_slice(),
314            None => &[],
315        }
316    }
317
318    pub fn attributes(&self) -> &[Attribute] {
319        match &self.attributes {
320            Some(attributes) => attributes.as_slice(),
321            None => &[],
322        }
323    }
324}
325
326impl_ttlv_serde!(struct CommonTemplateAttribute as 0x42001F {
327    fast_scan = |scanner| {
328        let names = std::iter::from_fn(|| Name::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?;
329        let attributes =
330            std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?;
331        Self::new_with_names(attributes, names)
332    };
333
334    format = |&self, formatter| {
335        for name in self.template_names() {
336            name.format(&mut formatter)?;
337        }
338        for attribute in self.attributes() {
339            attribute.format(&mut formatter)?;
340        }
341    };
342});
343
344/// See KMIP 1.0 section 2.1.8 [Template-Attribute Structures](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581162).
345#[derive(Clone, Debug, PartialEq, Eq)]
346pub struct PrivateKeyTemplateAttribute {
347    template_names: Option<Vec<Name>>,
348    attributes: Option<Vec<Attribute>>,
349}
350
351impl PrivateKeyTemplateAttribute {
352    pub fn new(attributes: Vec<Attribute>) -> Self {
353        Self {
354            template_names: None,
355            attributes: Some(attributes),
356        }
357    }
358
359    pub fn new_with_names(attributes: Vec<Attribute>, names: Vec<Name>) -> Self {
360        Self {
361            template_names: (!names.is_empty()).then_some(names),
362            attributes: (!attributes.is_empty()).then_some(attributes),
363        }
364    }
365
366    pub fn with_template_name(mut self, template_name: &'static str) -> Self {
367        // TODO: SAFETY
368        let template_name = Name::from_str(template_name).unwrap();
369        let mut template_names = self.template_names.unwrap_or_default();
370        template_names.push(template_name);
371        self.template_names = Some(template_names);
372        self
373    }
374
375    pub fn template_names(&self) -> &[Name] {
376        match &self.template_names {
377            Some(template_names) => template_names.as_slice(),
378            None => &[],
379        }
380    }
381
382    pub fn attributes(&self) -> &[Attribute] {
383        match &self.attributes {
384            Some(attributes) => attributes.as_slice(),
385            None => &[],
386        }
387    }
388}
389
390impl_ttlv_serde!(struct PrivateKeyTemplateAttribute as 0x420065 {
391    fast_scan = |scanner| {
392        let names = std::iter::from_fn(|| Name::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?;
393        let attributes =
394            std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?;
395        Self::new_with_names(attributes, names)
396    };
397
398    format = |&self, formatter| {
399        for name in self.template_names() {
400            name.format(&mut formatter)?;
401        }
402        for attribute in self.attributes() {
403            attribute.format(&mut formatter)?;
404        }
405    };
406});
407
408/// See KMIP 1.0 section 2.1.8 [Template-Attribute Structures](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581162).
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct PublicKeyTemplateAttribute {
411    template_names: Option<Vec<Name>>,
412    attributes: Option<Vec<Attribute>>,
413}
414
415impl PublicKeyTemplateAttribute {
416    pub fn new(attributes: Vec<Attribute>) -> Self {
417        Self {
418            template_names: None,
419            attributes: Some(attributes),
420        }
421    }
422
423    pub fn new_with_names(attributes: Vec<Attribute>, names: Vec<Name>) -> Self {
424        Self {
425            template_names: (!names.is_empty()).then_some(names),
426            attributes: (!attributes.is_empty()).then_some(attributes),
427        }
428    }
429
430    pub fn with_template_name(mut self, template_name: &'static str) -> Self {
431        // TODO: SAFETY
432        let template_name = Name::from_str(template_name).unwrap();
433        let mut template_names = self.template_names.unwrap_or_default();
434        template_names.push(template_name);
435        self.template_names = Some(template_names);
436        self
437    }
438
439    pub fn template_names(&self) -> &[Name] {
440        match &self.template_names {
441            Some(template_names) => template_names.as_slice(),
442            None => &[],
443        }
444    }
445
446    pub fn attributes(&self) -> &[Attribute] {
447        match &self.attributes {
448            Some(attributes) => attributes.as_slice(),
449            None => &[],
450        }
451    }
452}
453
454impl_ttlv_serde!(struct PublicKeyTemplateAttribute as 0x42006E {
455    fast_scan = |scanner| {
456        let names = std::iter::from_fn(|| Name::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?;
457        let attributes =
458            std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?;
459        Self::new_with_names(attributes, names)
460    };
461
462    format = |&self, formatter| {
463        for name in self.template_names() {
464            name.format(&mut formatter)?;
465        }
466        for attribute in self.attributes() {
467            attribute.format(&mut formatter)?;
468        }
469    };
470});
471
472/// See KMIP 1.0 section 2.1.2 [Credential](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581156).
473#[derive(Clone, Debug, PartialEq, Eq)]
474pub struct Credential(pub CredentialType, pub CredentialValue);
475
476impl Credential {
477    pub fn credential_type(&self) -> CredentialType {
478        self.0
479    }
480
481    pub fn credential_value(&self) -> &CredentialValue {
482        &self.1
483    }
484}
485
486impl_ttlv_serde!(struct Credential as 0x420023 {
487    fast_scan = |scanner| {
488        let r#type = CredentialType::fast_scan(&mut scanner)?;
489        let value = CredentialValue::fast_scan(&mut scanner, &r#type)?;
490        Self(r#type, value)
491    };
492
493    format = |&self, formatter| {
494        self.0.format(&mut formatter)?;
495        self.1.format(&mut formatter)?;
496    };
497});
498
499/// See KMIP 1.0 section 2.1.2 [Credential](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581156).
500#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
501#[non_exhaustive]
502#[repr(u32)]
503pub enum CredentialType {
504    UsernameAndPassword = 1,
505}
506
507impl_ttlv_serde!(enum CredentialType as 0x420024);
508
509impl fmt::Display for CredentialType {
510    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
511        f.write_str(match self {
512            Self::UsernameAndPassword => "UsernameAndPassword",
513        })
514    }
515}
516
517/// See KMIP 1.0 section 2.1.2 [Credential](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581156).
518#[derive(Clone, Debug, PartialEq, Eq)]
519#[non_exhaustive]
520pub enum CredentialValue {
521    UsernameAndPassword(Username, Option<Password>),
522}
523
524impl CredentialValue {
525    pub fn username(&self) -> Option<&Username> {
526        match self {
527            CredentialValue::UsernameAndPassword(username, _password) => Some(username),
528        }
529    }
530
531    pub fn password(&self) -> Option<&Password> {
532        match self {
533            CredentialValue::UsernameAndPassword(_username, password) => password.as_ref(),
534        }
535    }
536}
537
538impl CredentialValue {
539    pub const TAG: Tag = Tag::new(0x420025);
540
541    pub fn fast_scan(scanner: &mut FastScanner<'_>, r#type: &CredentialType) -> Result<Self, FastScanError> {
542        match r#type {
543            CredentialType::UsernameAndPassword => {
544                let mut scanner = scanner.scan_struct(Self::TAG)?;
545                let this = Self::UsernameAndPassword(
546                    Username::fast_scan(&mut scanner)?,
547                    Password::fast_scan_opt(&mut scanner)?,
548                );
549                scanner.finish()?;
550                Ok(this)
551            }
552        }
553    }
554
555    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
556        match self {
557            CredentialValue::UsernameAndPassword(username, password) => {
558                let mut formatter = formatter.format_struct(Self::TAG)?;
559                username.format(&mut formatter)?;
560                if let Some(password) = password {
561                    password.format(&mut formatter)?;
562                }
563                Ok(formatter.finish())
564            }
565        }
566    }
567}
568
569/// See KMIP 1.0 section 2.1.2 [Credential](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581156).
570#[derive(Clone, Debug, PartialEq, Eq)]
571pub struct Username(pub String);
572
573impl Deref for Username {
574    type Target = str;
575
576    fn deref(&self) -> &Self::Target {
577        self.0.as_str()
578    }
579}
580
581impl_ttlv_serde!(text Username as 0x420099);
582
583/// See KMIP 1.0 section 2.1.2 [Credential](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581156).
584#[derive(Clone, Debug, PartialEq, Eq)]
585pub struct Password(pub String);
586
587impl Deref for Password {
588    type Target = str;
589
590    fn deref(&self) -> &Self::Target {
591        self.0.as_str()
592    }
593}
594
595impl_ttlv_serde!(text Password as 0x4200A1);
596
597/// See KMIP 1.0 section 2.1.3 [Key Block](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613459).
598#[derive(Clone, Debug, PartialEq, Eq)]
599pub struct KeyBlock(
600    pub KeyFormatType,
601    pub Option<KeyCompressionType>,
602    pub Option<KeyValue>,
603    pub Option<CryptographicAlgorithm>,
604    pub Option<CryptographicLength>,
605    pub Option<KeyWrappingData>,
606);
607
608impl_ttlv_serde!(struct KeyBlock as 0x420040 {
609    fast_scan = |scanner| {
610        let format = KeyFormatType::fast_scan(&mut scanner)?;
611        Self(
612            format,
613            KeyCompressionType::fast_scan_opt(&mut scanner)?,
614            KeyValue::fast_scan_opt(&mut scanner, &format)?,
615            CryptographicAlgorithm::fast_scan_opt(&mut scanner)?,
616            CryptographicLength::fast_scan_opt(&mut scanner)?,
617            KeyWrappingData::fast_scan_opt(&mut scanner)?,
618        )
619    };
620
621    format = |&self, formatter| {
622        self.0.format(&mut formatter)?;
623        if let Some(x) = &self.1 { x.format(&mut formatter)?; }
624        if let Some(x) = &self.2 { x.format(&mut formatter)?; }
625        if let Some(x) = &self.3 { x.format(&mut formatter)?; }
626        if let Some(x) = &self.4 { x.format(&mut formatter)?; }
627        if let Some(x) = &self.5 { x.format(&mut formatter)?; }
628    };
629});
630
631/// See KMIP 1.0 section 2.1.4 [Key Value](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581158).
632#[derive(Clone, Debug, PartialEq, Eq)]
633pub struct KeyValue(pub KeyMaterial, pub Option<Vec<Attribute>>);
634
635impl KeyValue {
636    pub const TAG: Tag = Tag::new(0x420045);
637
638    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, format: &KeyFormatType) -> Result<Option<Self>, FastScanError> {
639        let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? else {
640            return Ok(None);
641        };
642        let material = KeyMaterial::fast_scan(&mut scanner, format)?;
643        let attributes =
644            std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<Vec<_>, _>>()?;
645        let attributes = Some(attributes).filter(|a| !a.is_empty());
646        scanner.finish()?;
647        Ok(Some(Self(material, attributes)))
648    }
649
650    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
651        let mut formatter = formatter.format_struct(Self::TAG)?;
652        self.0.format(&mut formatter)?;
653        for attribute in self.1.iter().flatten() {
654            attribute.format(&mut formatter)?;
655        }
656        Ok(formatter.finish())
657    }
658}
659
660/// See KMIP 1.0 section 2.1.5 [Key Wrapping Data](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581159).
661#[derive(Clone, Debug, PartialEq, Eq)]
662pub struct KeyWrappingData(
663    pub WrappingMethod,
664    pub Option<EncryptionKeyInformation>,
665    pub Option<MACOrSignatureKeyInformation>,
666    pub Option<MACOrSignature>,
667    pub Option<IVOrCounterOrNonce>,
668    pub Option<Vec<Attribute>>,
669);
670
671impl_ttlv_serde!(struct KeyWrappingData(
672    a: WrappingMethod,
673    #[option] b: EncryptionKeyInformation,
674    #[option] c: MACOrSignatureKeyInformation,
675    #[option] d: MACOrSignature,
676    #[option] e: IVOrCounterOrNonce,
677    #[option+vec] f: Attribute,
678) as 0x420046);
679
680/// See KMIP 1.0 section 2.1.5 [Key Wrapping Data](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581159).
681#[derive(Clone, Debug, PartialEq, Eq)]
682pub struct MACOrSignature(Vec<u8>);
683
684impl_ttlv_serde!(bytes MACOrSignature as 0x42004D);
685
686/// See KMIP 1.0 section 2.1.5 [Key Wrapping Data](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581159).
687#[derive(Clone, Debug, PartialEq, Eq)]
688pub struct IVOrCounterOrNonce(Vec<u8>);
689
690impl_ttlv_serde!(bytes IVOrCounterOrNonce as 0x42003D);
691
692/// See KMIP 1.0 section 2.1.5 [Key Wrapping Data](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581159).
693#[derive(Clone, Debug, PartialEq, Eq)]
694pub struct EncryptionKeyInformation(pub UniqueIdentifier, pub Option<CryptographicParameters>);
695
696impl_ttlv_serde!(struct EncryptionKeyInformation(
697    id: UniqueIdentifier,
698    #[option] params: CryptographicParameters,
699) as 0x420036);
700
701/// See KMIP 1.0 section 2.1.5 [Key Wrapping Data](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581159).
702#[derive(Clone, Debug, PartialEq, Eq)]
703pub struct MACOrSignatureKeyInformation(pub UniqueIdentifier, pub Option<CryptographicParameters>);
704
705impl_ttlv_serde!(struct MACOrSignatureKeyInformation(
706    id: UniqueIdentifier,
707    #[option] params: CryptographicParameters,
708) as 0x42004E);
709
710/// See KMIP 1.0 section 2.1.6 [Key Wrapping Specification](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581160).
711#[derive(Clone, Debug, PartialEq, Eq)]
712pub struct KeyWrappingSpecification(
713    pub WrappingMethod,
714    pub Option<EncryptionKeyInformation>,
715    pub Option<MACOrSignatureKeyInformation>,
716    pub Option<Vec<Attribute>>,
717);
718
719impl_ttlv_serde!(struct KeyWrappingSpecification(
720    a: WrappingMethod,
721    #[option] b: EncryptionKeyInformation,
722    #[option] c: MACOrSignatureKeyInformation,
723    #[option+vec] d: Attribute,
724) as 0x420047);
725
726/// See KMIP 1.0 section 2.2 [Managed Objects](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581163).
727#[derive(Clone, Debug, PartialEq, Eq)]
728#[non_exhaustive]
729pub enum ManagedObject {
730    // Certificate(Certificate),
731    // Not implemented
732    SymmetricKey(SymmetricKey),
733
734    PublicKey(PublicKey),
735
736    PrivateKey(PrivateKey),
737
738    // SplitKey(SplitKey),
739    // Not implemented
740    Template(Template),
741    // SecretData(SecretData),
742    // Not implemented
743
744    // OpaqueObject(OpaqueObject),
745    // Not implemented
746}
747
748impl ManagedObject {
749    pub fn fast_scan(scanner: &mut FastScanner<'_>, r#type: ObjectType) -> Result<Self, FastScanError> {
750        match r#type {
751            ObjectType::SymmetricKey => SymmetricKey::fast_scan(scanner).map(Self::SymmetricKey),
752            ObjectType::PublicKey => PublicKey::fast_scan(scanner).map(Self::PublicKey),
753            ObjectType::PrivateKey => PrivateKey::fast_scan(scanner).map(Self::PrivateKey),
754            ObjectType::Template => Template::fast_scan(scanner).map(Self::Template),
755
756            ObjectType::Certificate
757            | ObjectType::SplitKey
758            | ObjectType::SecretData
759            | ObjectType::OpaqueObject
760            | ObjectType::PGPKey => unimplemented!(),
761        }
762    }
763
764    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, r#type: ObjectType) -> Result<Option<Self>, FastScanError> {
765        match r#type {
766            ObjectType::SymmetricKey => SymmetricKey::fast_scan_opt(scanner).map(|s| s.map(Self::SymmetricKey)),
767            ObjectType::PublicKey => PublicKey::fast_scan_opt(scanner).map(|s| s.map(Self::PublicKey)),
768            ObjectType::PrivateKey => PrivateKey::fast_scan_opt(scanner).map(|s| s.map(Self::PrivateKey)),
769            ObjectType::Template => Template::fast_scan_opt(scanner).map(|s| s.map(Self::Template)),
770
771            ObjectType::Certificate
772            | ObjectType::SplitKey
773            | ObjectType::SecretData
774            | ObjectType::OpaqueObject
775            | ObjectType::PGPKey => unimplemented!(),
776        }
777    }
778
779    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
780        match self {
781            ManagedObject::SymmetricKey(this) => this.format(formatter),
782            ManagedObject::PublicKey(this) => this.format(formatter),
783            ManagedObject::PrivateKey(this) => this.format(formatter),
784            ManagedObject::Template(this) => this.format(formatter),
785        }
786    }
787}
788
789/// See KMIP 1.0 section 2.2.2 [Symmetric Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581165).
790#[derive(Clone, Debug, PartialEq, Eq)]
791pub struct SymmetricKey(pub KeyBlock);
792
793impl_ttlv_serde!(struct SymmetricKey(block: KeyBlock) as 0x42008F);
794
795/// See KMIP 1.0 section 2.2.3 [Public Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581166).
796#[derive(Clone, Debug, PartialEq, Eq)]
797pub struct PublicKey(pub KeyBlock);
798
799impl_ttlv_serde!(struct PublicKey(block: KeyBlock) as 0x42006D);
800
801/// See KMIP 1.0 section 2.2.4 [Private Key](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581167).
802#[derive(Clone, Debug, PartialEq, Eq)]
803pub struct PrivateKey(pub KeyBlock);
804
805impl_ttlv_serde!(struct PrivateKey(block: KeyBlock) as 0x420064);
806
807/// See KMIP 1.0 section 2.2.6 [Template](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581169).
808#[derive(Clone, Debug, PartialEq, Eq)]
809pub struct Template(pub Vec<Attribute>);
810
811impl_ttlv_serde!(struct Template(#[vec] attrs: Attribute) as 0x420090);
812
813/// See KMIP 1.0 section 3.2 [Name](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581174).
814#[derive(Clone, Debug, PartialEq, Eq)]
815pub struct Name(pub NameValue, pub NameType);
816
817impl FromStr for Name {
818    type Err = ();
819
820    fn from_str(s: &str) -> Result<Self, Self::Err> {
821        Ok(Self(NameValue::from_str(s)?, NameType::UninterpretedTextString))
822    }
823}
824
825impl fmt::Display for Name {
826    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
827        f.write_fmt(format_args!("{}", self.0))
828    }
829}
830
831impl_ttlv_serde!(struct Name(
832    value: NameValue,
833    r#type: NameType,
834) as 0x420053);
835
836/// See KMIP 1.0 section 3.26 [Revocation Reason](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581200).
837#[derive(Clone, Debug, PartialEq, Eq)]
838pub struct RevocationReason(pub RevocationReasonCode, pub Option<RevocationMessage>);
839
840impl_ttlv_serde!(struct RevocationReason(
841    code: RevocationReasonCode,
842    #[option] message: RevocationMessage,
843) as 0x420081);
844
845/// See KMIP 1.0 section 6.1 [Protocol Version](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581239).
846#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
847pub struct ProtocolVersion(pub ProtocolVersionMajor, pub ProtocolVersionMinor);
848
849impl_ttlv_serde!(struct ProtocolVersion(
850    major: ProtocolVersionMajor,
851    minor: ProtocolVersionMinor,
852) as 0x420069);
853
854/// See KMIP 1.0 section 6.1 [Protocol Version](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581239).
855#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
856pub struct ProtocolVersionMajor(pub i32);
857
858impl_ttlv_serde!(int ProtocolVersionMajor as 0x42006A);
859
860/// See KMIP 1.0 section 6.1 [Protocol Version](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581239).
861#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
862pub struct ProtocolVersionMinor(pub i32);
863
864impl_ttlv_serde!(int ProtocolVersionMinor as 0x42006B);
865
866/// See KMIP 1.0 section 6.3 [Maximum Response Size](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581241).
867#[derive(Clone, Copy, Debug, PartialEq, Eq)]
868pub struct MaximumResponseSize(pub i32);
869
870impl_ttlv_serde!(int MaximumResponseSize as 0x420050);
871
872/// One (or more since KMIP 1.2) credentials to authenticate with.
873///
874/// In KMIP 1.0 and 1.1 only a single credential was supported.
875/// In KMIP 1.2 this was expanded to one or more credentials.
876/// In KMIP 2.0 it was specified that if multiple credentials are provided
877/// then they must all be satisfied, prior to that it was not specified what
878/// the server should require if multiple credentials are supplied.
879///
880/// See KMIP 1.0 section 6.6 [Authentication](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581244).
881/// See KMIP 1.2 section 6.6 [Authentication](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613576).
882/// See KMIP 2.0 section 9.4 [Authentication](https://docs.oasis-open.org/kmip/kmip-spec/v2.0/os/kmip-spec-v2.0-os.html#_Toc6497631).
883#[derive(Clone, Debug, PartialEq, Eq)]
884pub struct Authentication(pub Vec<Credential>);
885
886impl Authentication {
887    pub fn build(credential: CredentialValue) -> Authentication {
888        match credential {
889            CredentialValue::UsernameAndPassword(username, password) => Authentication(vec![Credential(
890                CredentialType::UsernameAndPassword,
891                CredentialValue::UsernameAndPassword(username, password),
892            )]),
893        }
894    }
895
896    pub fn credentials(&self) -> &[Credential] {
897        &self.0
898    }
899
900    pub fn username(&self) -> Option<&Username> {
901        self.credentials()
902            .iter()
903            .find(|c| matches!(c.credential_value(), CredentialValue::UsernameAndPassword(..)))
904            .and_then(|c| c.credential_value().username())
905    }
906
907    pub fn password(&self) -> Option<&Password> {
908        self.credentials()
909            .iter()
910            .find(|c| matches!(c.credential_value(), CredentialValue::UsernameAndPassword(..)))
911            .and_then(|c| c.credential_value().password())
912    }
913}
914
915impl_ttlv_serde!(struct Authentication(#[vec] credentials: Credential) as 0x42000C);
916
917/// See KMIP 1.0 section 6.14 [Batch Count](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581252).
918#[derive(Clone, Debug, Default, PartialEq, Eq)]
919pub struct BatchCount(pub i32);
920
921impl_ttlv_serde!(int BatchCount as 0x42000D);
922
923/// See KMIP 1.0 section 6.15 [Batch Item](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581253).
924#[derive(Clone, Debug, PartialEq, Eq)]
925pub struct BatchItem(
926    pub Operation, // TODO: set this somehow automatically to RequestPayload::operation()
927    pub Option<UniqueBatchItemID>,
928    pub RequestPayload,
929);
930
931impl BatchItem {
932    pub fn operation(&self) -> &Operation {
933        &self.0
934    }
935
936    pub fn unique_batch_item_id(&self) -> Option<&UniqueBatchItemID> {
937        self.1.as_ref()
938    }
939
940    pub fn request_payload(&self) -> &RequestPayload {
941        &self.2
942    }
943}
944
945impl_ttlv_serde!(struct BatchItem as 0x42000F {
946    fast_scan = |scanner| {
947        let operation = Operation::fast_scan(&mut scanner)?;
948        let id = UniqueBatchItemID::fast_scan_opt(&mut scanner)?;
949        let payload = RequestPayload::fast_scan(&mut scanner, operation)?;
950        Self(operation, id, payload)
951    };
952
953    format = |&self, formatter| {
954        self.0.format(&mut formatter)?;
955        if let Some(x) = &self.1 { x.format(&mut formatter)?; }
956        self.2.format(&mut formatter)?;
957    };
958});
959
960/// See KMIP 1.0 section 7.1 [Message Structure](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581256).
961#[derive(Clone, Debug, PartialEq, Eq)]
962pub struct RequestMessage(pub RequestHeader, pub Vec<BatchItem>);
963
964impl RequestMessage {
965    pub fn header(&self) -> &RequestHeader {
966        &self.0
967    }
968
969    pub fn batch_items(&self) -> &[BatchItem] {
970        &self.1
971    }
972}
973
974impl_ttlv_serde!(struct RequestMessage as 0x420078 {
975    fast_scan = |scanner| {
976        let header = RequestHeader::fast_scan(&mut scanner)?;
977        let BatchCount(count) = header.5;
978        let items = (0..count)
979            .map(|_| BatchItem::fast_scan(&mut scanner))
980            .collect::<Result<Vec<_>, _>>()?;
981        Self(header, items)
982    };
983
984    format = |&self, formatter| {
985        self.0.format(&mut formatter)?;
986        for item in &self.1 {
987            item.format(&mut formatter)?;
988        }
989    };
990});
991
992/// See KMIP 1.0 section 7.2 [Operations](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581257).
993#[derive(Clone, Debug, PartialEq, Eq)]
994pub struct RequestHeader(
995    pub ProtocolVersion,
996    pub Option<MaximumResponseSize>,
997    pub Option<Authentication>,
998    pub Option<BatchErrorContinuationOption>,
999    pub Option<bool>, // BatchOrderOption
1000    pub BatchCount,
1001);
1002
1003impl RequestHeader {
1004    pub fn protocol_version(&self) -> &ProtocolVersion {
1005        &self.0
1006    }
1007
1008    pub fn max_response_size(&self) -> Option<&MaximumResponseSize> {
1009        self.1.as_ref()
1010    }
1011
1012    pub fn authentication(&self) -> Option<&Authentication> {
1013        self.2.as_ref()
1014    }
1015
1016    pub fn batch_count(&self) -> &BatchCount {
1017        &self.5
1018    }
1019}
1020
1021impl_ttlv_serde!(struct RequestHeader as 0x420077 {
1022    fast_scan = |scanner| Self(
1023        ProtocolVersion::fast_scan(&mut scanner)?,
1024        MaximumResponseSize::fast_scan_opt(&mut scanner)?,
1025        Authentication::fast_scan_opt(&mut scanner)?,
1026        BatchErrorContinuationOption::fast_scan_opt(&mut scanner)?,
1027        scanner.scan_opt_bool(Tag::new(0x420010))?,
1028        BatchCount::fast_scan_opt(&mut scanner)?.unwrap_or_default(),
1029    );
1030
1031    format = |&self, formatter| {
1032        self.0.format(&mut formatter)?;
1033        if let Some(x) = &self.1 { x.format(&mut formatter)?; }
1034        if let Some(x) = &self.2 { x.format(&mut formatter)?; }
1035        if let Some(x) = &self.3 { x.format(&mut formatter)?; }
1036        if let Some(x) = &self.4 { formatter.format_bool(Tag::new(0x420010), *x)?; }
1037        self.5.format(&mut formatter)?;
1038    };
1039});
1040
1041#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1042#[non_exhaustive]
1043#[repr(u32)]
1044pub enum BatchErrorContinuationOption {
1045    Continue = 1,
1046    Stop,
1047    Undo,
1048}
1049
1050impl_ttlv_serde!(enum BatchErrorContinuationOption as 0x42000E);
1051
1052/// See KMIP 1.0 section 7.1 [Message Structure](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581256).
1053#[derive(Clone, Debug, PartialEq, Eq)]
1054#[non_exhaustive]
1055#[allow(clippy::large_enum_variant)]
1056pub enum RequestPayload {
1057    /// See KMIP 1.0 section 4.1 Create.
1058    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581209>
1059    Create(ObjectType, TemplateAttribute),
1060
1061    /// See KMIP 1.0 section 4.2 Create Key Pair.
1062    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581210>
1063    CreateKeyPair(
1064        Option<CommonTemplateAttribute>,
1065        Option<PrivateKeyTemplateAttribute>,
1066        Option<PublicKeyTemplateAttribute>,
1067    ),
1068
1069    /// See KMIP 1.0 section 4.3 Register.
1070    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581211>
1071    Register(ObjectType, TemplateAttribute, Option<ManagedObject>),
1072
1073    // TODO? Missing operation code mappings to request payloads
1074    // Re-key = 4
1075    // Derive Key = 5
1076    // Certify = 6
1077    // Re-certify = 7
1078    /// See KMIP 1.0 section 4.8 Locate.
1079    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581216>
1080    Locate(Vec<Attribute>), // TODO: Add MaximumItems and StorageStatusMask optional request payload fields
1081
1082    /// See KMIP 1.0 section 4.10 Get.
1083    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218>
1084    Get(
1085        Option<UniqueIdentifier>,
1086        Option<KeyFormatType>,
1087        Option<KeyCompressionType>,
1088        Option<KeyWrappingSpecification>,
1089    ),
1090
1091    /// See KMIP 1.0 section 4.11 Get Attributes.
1092    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581219>
1093    GetAttributes(Option<UniqueIdentifier>, Option<Vec<AttributeName>>),
1094
1095    /// See KMIP 1.0 section 4.12 Get Attribute List.
1096    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581220>
1097    GetAttributeList(Option<UniqueIdentifier>),
1098
1099    /// See KMIP 1.0 section 4.13 Add Attribute.
1100    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581221>
1101    AddAttribute(Option<UniqueIdentifier>, Attribute),
1102
1103    /// See KMIP 1.0 section 4.14 Modify Attribute.
1104    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222>
1105    ModifyAttribute(Option<UniqueIdentifier>, Attribute),
1106
1107    /// See KMIP 1.0 section 4.15 Delete Attribute.
1108    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581223>
1109    DeleteAttribute(Option<UniqueIdentifier>, AttributeName, Option<AttributeIndex>),
1110
1111    // TODO? Missing operation code mappings to request payloads
1112    // Obtain Lease = 10
1113    // Get Usage Allocation = 11
1114    /// See KMIP 1.0 section 4.18 Activate.
1115    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226>
1116    Activate(Option<UniqueIdentifier>),
1117
1118    /// See KMIP 1.0 section 4.19 Revoke.
1119    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227>
1120    Revoke(
1121        Option<UniqueIdentifier>,
1122        RevocationReason,
1123        Option<CompromiseOccurrenceDate>,
1124    ),
1125
1126    /// See KMIP 1.0 section 4.20 Destroy.
1127    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228>
1128    Destroy(Option<UniqueIdentifier>),
1129
1130    // TODO? Missing operation code mappings to request payloads
1131    // Archive = 15
1132    // Recover = 16
1133    // Validate = 17
1134    /// See KMIP 1.0 section 4.24 Query.
1135    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232>
1136    Query(Vec<QueryFunction>),
1137
1138    // TODO? Missing operation code mappings to request payloads
1139    // Cancel = 19
1140    // Poll = 1A
1141    // Notify = 1B
1142    // Put = 1C
1143    // Re-key Key Pair = 1D
1144    /// See KMIP 1.1 section 4.26 Discover Versions.
1145    /// See: <https://docs.oasis-open.org/kmip/spec/v1.1/cs01/kmip-spec-v1.1-cs01.html#_Toc332787652>
1146    DiscoverVersions(Vec<ProtocolVersion>),
1147
1148    // TODO? Missing operation code mappings to request payloads
1149    // Encrypt = 1F
1150    // Decrypt = 20
1151    /// See KMIP 1.2 section 4.31 Sign.
1152    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558>
1153    Sign(Option<UniqueIdentifier>, Option<CryptographicParameters>, Data),
1154
1155    // TODO? Missing operation code mappings to request payloads
1156    // Signature Verify = 22
1157    // MAC = 23
1158    // MAC Verify = 24
1159    /// See KMIP 1.2 section 4.35 RNG Retrieve.
1160    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613562>
1161    RNGRetrieve(DataLength),
1162}
1163
1164impl RequestPayload {
1165    pub fn operation(&self) -> Operation {
1166        match self {
1167            RequestPayload::Create(..) => Operation::Create,
1168            RequestPayload::CreateKeyPair(..) => Operation::CreateKeyPair,
1169            RequestPayload::Register(..) => Operation::Register,
1170            // Not implemented: Re-key (KMIP 1.0)
1171            // Not implemented: Re-key Key Pair (KMIP 1.1)
1172            // Not implemented: Derive Key (KMIP 1.0)
1173            // Not implemented: Certify (KMIP 1.0)
1174            // Not implemented: Re-certify (KMIP 1.0)
1175            RequestPayload::Locate(..) => Operation::Locate,
1176            // Not implemented: Check (KMIP 1.0)
1177            RequestPayload::Get(..) => Operation::Get,
1178            RequestPayload::GetAttributes(..) => Operation::GetAttributes,
1179            RequestPayload::GetAttributeList(..) => Operation::GetAttributeList,
1180            RequestPayload::AddAttribute(..) => Operation::AddAttribute,
1181            RequestPayload::ModifyAttribute(..) => Operation::ModifyAttribute,
1182            RequestPayload::DeleteAttribute(..) => Operation::DeleteAttribute,
1183            // Not implemented: Obtain Lease (KMIP 1.0)
1184            // Not implemented: Get Usage Allocation (KMIP 1.0)
1185            RequestPayload::Activate(..) => Operation::Activate,
1186            RequestPayload::Revoke(..) => Operation::Revoke,
1187            RequestPayload::Destroy(..) => Operation::Destroy,
1188            // Not implemented: Archive (KMIP 1.0)
1189            // Not implemented: Recover (KMIP 1.0)
1190            // Not implemented: Validate (KMIP 1.0)
1191            RequestPayload::Query(..) => Operation::Query,
1192            RequestPayload::DiscoverVersions(..) => Operation::DiscoverVersions,
1193            // Not implemented: Cancel (KMIP 1.0)
1194            // Not implemented: Poll (KMIP 1.0)
1195            // Not implemented: Encrypt (KMIP 1.2)
1196            // Not implemented: Decrypt (KMIP 1.2)
1197            RequestPayload::Sign(..) => Operation::Sign,
1198            // Not implemented: Signature Verify (KMIP 1.2)
1199            // Not implemented: MAC (KMIP 1.2)
1200            // Not implemented: MAC Verify (KMIP 1.2)
1201            RequestPayload::RNGRetrieve(..) => Operation::RNGRetrieve,
1202            // Not implemented: RNG Seed (KMIP 1.2)
1203            // Not implemented: Hash (KMIP 1.2)
1204            // Not implemented: Create Split Key (KMIP 1.2)
1205            // Not implemented: Join Split Key (KMIP 1.2)
1206        }
1207    }
1208
1209    pub fn protocol_version(&self) -> ProtocolVersion {
1210        match self {
1211            RequestPayload::Create(..)
1212            | RequestPayload::CreateKeyPair(..)
1213            | RequestPayload::Register(..)
1214            | RequestPayload::Locate(..)
1215            | RequestPayload::Get(..)
1216            | RequestPayload::GetAttributes(..)
1217            | RequestPayload::GetAttributeList(..)
1218            | RequestPayload::AddAttribute(..)
1219            | RequestPayload::ModifyAttribute(..)
1220            | RequestPayload::DeleteAttribute(..)
1221            | RequestPayload::Activate(..)
1222            | RequestPayload::Revoke(..)
1223            | RequestPayload::Destroy(..) => {
1224                // These KMIP operations are defined in the KMIP 1.0 specification
1225                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(0))
1226            }
1227            RequestPayload::DiscoverVersions(..) => {
1228                // These KMIP operations are defined in the KMIP 1.1 specification
1229                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(1))
1230            }
1231            RequestPayload::Sign(..) | RequestPayload::RNGRetrieve(..) => {
1232                // These KMIP operations are defined in the KMIP 1.2 specification
1233                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(2))
1234            }
1235            RequestPayload::Query(..) => {
1236                // TODO: Although query is defined in the KMIP 1.0 specification, KMIP servers that support KMIP >1.0
1237                // are required by the specification to "support backward compatibility with versions of the protocol
1238                // with the same major version". A KMIP 1.2 server cannot respond to a Query request with KMIP tag
1239                // numbers representing KMIP Operations that were only defined in a KMIP specification >1.0. Presumably
1240                // therefore we must pass the highest version number that both we and the server support. Currently
1241                // this is just dumb and passes the highest version number that we support, we should actually base
1242                // it on the result of a previous attempt to use the KMIP 1.1 Discover Versions request.
1243                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(2))
1244            }
1245        }
1246    }
1247}
1248
1249impl RequestPayload {
1250    pub const TAG: Tag = Tag::new(0x420079);
1251
1252    pub fn fast_scan(scanner: &mut FastScanner<'_>, operation: Operation) -> Result<Self, FastScanError> {
1253        let mut scanner = scanner.scan_struct(Self::TAG)?;
1254        let this = match operation {
1255            Operation::Create => Self::Create(
1256                ObjectType::fast_scan(&mut scanner)?,
1257                TemplateAttribute::fast_scan(&mut scanner)?,
1258            ),
1259            Operation::CreateKeyPair => Self::CreateKeyPair(
1260                CommonTemplateAttribute::fast_scan_opt(&mut scanner)?,
1261                PrivateKeyTemplateAttribute::fast_scan_opt(&mut scanner)?,
1262                PublicKeyTemplateAttribute::fast_scan_opt(&mut scanner)?,
1263            ),
1264            Operation::Register => {
1265                let r#type = ObjectType::fast_scan(&mut scanner)?;
1266                Self::Register(
1267                    r#type,
1268                    TemplateAttribute::fast_scan(&mut scanner)?,
1269                    ManagedObject::fast_scan_opt(&mut scanner, r#type)?,
1270                )
1271            }
1272            Operation::Locate => Self::Locate(
1273                std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?,
1274            ),
1275            Operation::Get => Self::Get(
1276                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1277                KeyFormatType::fast_scan_opt(&mut scanner)?,
1278                KeyCompressionType::fast_scan_opt(&mut scanner)?,
1279                KeyWrappingSpecification::fast_scan_opt(&mut scanner)?,
1280            ),
1281            Operation::GetAttributes => Self::GetAttributes(
1282                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1283                std::iter::from_fn(|| AttributeName::fast_scan_opt(&mut scanner).transpose())
1284                    .collect::<Result<Vec<_>, _>>()
1285                    .map(Some)?
1286                    .filter(|s| !s.is_empty()),
1287            ),
1288            Operation::GetAttributeList => Self::GetAttributeList(UniqueIdentifier::fast_scan_opt(&mut scanner)?),
1289            Operation::AddAttribute => Self::AddAttribute(
1290                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1291                Attribute::fast_scan(&mut scanner)?,
1292            ),
1293            Operation::ModifyAttribute => Self::ModifyAttribute(
1294                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1295                Attribute::fast_scan(&mut scanner)?,
1296            ),
1297            Operation::DeleteAttribute => Self::DeleteAttribute(
1298                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1299                AttributeName::fast_scan(&mut scanner)?,
1300                AttributeIndex::fast_scan_opt(&mut scanner)?,
1301            ),
1302            Operation::Activate => Self::Activate(UniqueIdentifier::fast_scan_opt(&mut scanner)?),
1303            Operation::Revoke => Self::Revoke(
1304                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1305                RevocationReason::fast_scan(&mut scanner)?,
1306                CompromiseOccurrenceDate::fast_scan_opt(&mut scanner)?,
1307            ),
1308            Operation::Destroy => Self::Destroy(UniqueIdentifier::fast_scan_opt(&mut scanner)?),
1309            Operation::Query => Self::Query(
1310                std::iter::from_fn(|| QueryFunction::fast_scan_opt(&mut scanner).transpose())
1311                    .collect::<Result<_, _>>()?,
1312            ),
1313            Operation::DiscoverVersions => Self::DiscoverVersions(
1314                std::iter::from_fn(|| ProtocolVersion::fast_scan_opt(&mut scanner).transpose())
1315                    .collect::<Result<_, _>>()?,
1316            ),
1317            Operation::Sign => Self::Sign(
1318                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1319                CryptographicParameters::fast_scan_opt(&mut scanner)?,
1320                Data::fast_scan(&mut scanner)?,
1321            ),
1322            Operation::RNGRetrieve => Self::RNGRetrieve(DataLength::fast_scan(&mut scanner)?),
1323
1324            _ => unimplemented!(),
1325        };
1326        scanner.finish()?;
1327        Ok(this)
1328    }
1329
1330    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1331        let mut formatter = formatter.format_struct(Self::TAG)?;
1332        match self {
1333            RequestPayload::Create(object_type, template_attribute) => {
1334                object_type.format(&mut formatter)?;
1335                template_attribute.format(&mut formatter)?;
1336            }
1337            RequestPayload::CreateKeyPair(
1338                common_template_attribute,
1339                private_key_template_attribute,
1340                public_key_template_attribute,
1341            ) => {
1342                if let Some(x) = common_template_attribute {
1343                    x.format(&mut formatter)?;
1344                }
1345                if let Some(x) = private_key_template_attribute {
1346                    x.format(&mut formatter)?;
1347                }
1348                if let Some(x) = public_key_template_attribute {
1349                    x.format(&mut formatter)?;
1350                }
1351            }
1352            RequestPayload::Register(object_type, template_attribute, managed_object) => {
1353                object_type.format(&mut formatter)?;
1354                template_attribute.format(&mut formatter)?;
1355                if let Some(x) = managed_object {
1356                    x.format(&mut formatter)?;
1357                }
1358            }
1359            RequestPayload::Locate(attributes) => {
1360                for x in attributes {
1361                    x.format(&mut formatter)?;
1362                }
1363            }
1364            RequestPayload::Get(
1365                unique_identifier,
1366                key_format_type,
1367                key_compression_type,
1368                key_wrapping_specification,
1369            ) => {
1370                if let Some(x) = unique_identifier {
1371                    x.format(&mut formatter)?;
1372                }
1373                if let Some(x) = key_format_type {
1374                    x.format(&mut formatter)?;
1375                }
1376                if let Some(x) = key_compression_type {
1377                    x.format(&mut formatter)?;
1378                }
1379                if let Some(x) = key_wrapping_specification {
1380                    x.format(&mut formatter)?;
1381                }
1382            }
1383            RequestPayload::GetAttributes(unique_identifier, attribute_names) => {
1384                if let Some(x) = unique_identifier {
1385                    x.format(&mut formatter)?;
1386                }
1387                for x in attribute_names.iter().flatten() {
1388                    x.format(&mut formatter)?;
1389                }
1390            }
1391            RequestPayload::GetAttributeList(unique_identifier) => {
1392                if let Some(x) = unique_identifier {
1393                    x.format(&mut formatter)?;
1394                }
1395            }
1396            RequestPayload::AddAttribute(unique_identifier, attribute) => {
1397                if let Some(x) = unique_identifier {
1398                    x.format(&mut formatter)?;
1399                }
1400                attribute.format(&mut formatter)?;
1401            }
1402            RequestPayload::ModifyAttribute(unique_identifier, attribute) => {
1403                if let Some(x) = unique_identifier {
1404                    x.format(&mut formatter)?;
1405                }
1406                attribute.format(&mut formatter)?;
1407            }
1408            RequestPayload::DeleteAttribute(unique_identifier, attribute_name, attribute_index) => {
1409                if let Some(x) = unique_identifier {
1410                    x.format(&mut formatter)?;
1411                }
1412                attribute_name.format(&mut formatter)?;
1413                if let Some(x) = attribute_index {
1414                    x.format(&mut formatter)?;
1415                }
1416            }
1417            RequestPayload::Activate(unique_identifier) => {
1418                if let Some(x) = unique_identifier {
1419                    x.format(&mut formatter)?;
1420                }
1421            }
1422            RequestPayload::Revoke(unique_identifier, revocation_reason, compromise_occurrence_date) => {
1423                if let Some(x) = unique_identifier {
1424                    x.format(&mut formatter)?;
1425                }
1426                revocation_reason.format(&mut formatter)?;
1427                if let Some(x) = compromise_occurrence_date {
1428                    x.format(&mut formatter)?;
1429                }
1430            }
1431            RequestPayload::Destroy(unique_identifier) => {
1432                if let Some(x) = unique_identifier {
1433                    x.format(&mut formatter)?;
1434                }
1435            }
1436            RequestPayload::Query(query_functions) => {
1437                for x in query_functions {
1438                    x.format(&mut formatter)?;
1439                }
1440            }
1441            RequestPayload::DiscoverVersions(protocol_versions) => {
1442                for x in protocol_versions {
1443                    x.format(&mut formatter)?;
1444                }
1445            }
1446            RequestPayload::Sign(unique_identifier, cryptographic_parameters, data) => {
1447                if let Some(x) = unique_identifier {
1448                    x.format(&mut formatter)?;
1449                }
1450                if let Some(x) = cryptographic_parameters {
1451                    x.format(&mut formatter)?;
1452                }
1453                data.format(&mut formatter)?;
1454            }
1455            RequestPayload::RNGRetrieve(data_length) => {
1456                data_length.format(&mut formatter)?;
1457            }
1458        }
1459        Ok(formatter.finish())
1460    }
1461}
1462
1463/// See KMIP 1.0 section 9.1.3.2.4 [Wrapping Method Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Ref241993348).
1464#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1465#[non_exhaustive]
1466#[repr(u32)]
1467pub enum WrappingMethod {
1468    Encrypt = 1,
1469    MACSign,
1470    EncryptThenMACSign,
1471    MACSignThenEncrypt,
1472    TR31,
1473}
1474
1475impl_ttlv_serde!(enum WrappingMethod as 0x42009E);
1476
1477impl fmt::Display for WrappingMethod {
1478    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1479        f.write_str(match self {
1480            Self::Encrypt => "Encrypt",
1481            Self::MACSign => "MACSign",
1482            Self::EncryptThenMACSign => "EncryptThenMACSign",
1483            Self::MACSignThenEncrypt => "MACSignThenEncrypt",
1484            Self::TR31 => "TR31",
1485        })
1486    }
1487}
1488
1489/// See KMIP 1.0 section 9.1.3.2.23 [Query Function Enumeration](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Ref242030554).
1490#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1491#[non_exhaustive]
1492#[repr(u32)]
1493pub enum QueryFunction {
1494    QueryOperations = 0x00000001,
1495    QueryObjects,
1496    QueryServerInformation,
1497    QueryExtensionList = 0x00000005,
1498}
1499
1500impl_ttlv_serde!(enum QueryFunction as 0x420074);
1501
1502impl fmt::Display for QueryFunction {
1503    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1504        f.write_str(match self {
1505            Self::QueryOperations => "QueryOperations",
1506            Self::QueryObjects => "QueryObjects",
1507            Self::QueryServerInformation => "QueryServerInformation",
1508            Self::QueryExtensionList => "QueryExtensionList",
1509        })
1510    }
1511}