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        write!(f, "{self:?}")
512    }
513}
514
515/// 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).
516#[derive(Clone, Debug, PartialEq, Eq)]
517#[non_exhaustive]
518pub enum CredentialValue {
519    UsernameAndPassword(Username, Option<Password>),
520}
521
522impl CredentialValue {
523    pub fn username(&self) -> Option<&Username> {
524        match self {
525            CredentialValue::UsernameAndPassword(username, _password) => Some(username),
526        }
527    }
528
529    pub fn password(&self) -> Option<&Password> {
530        match self {
531            CredentialValue::UsernameAndPassword(_username, password) => password.as_ref(),
532        }
533    }
534}
535
536impl CredentialValue {
537    pub const TAG: Tag = Tag::new(0x420025);
538
539    pub fn fast_scan(scanner: &mut FastScanner<'_>, r#type: &CredentialType) -> Result<Self, FastScanError> {
540        match r#type {
541            CredentialType::UsernameAndPassword => {
542                let mut scanner = scanner.scan_struct(Self::TAG)?;
543                let this = Self::UsernameAndPassword(
544                    Username::fast_scan(&mut scanner)?,
545                    Password::fast_scan_opt(&mut scanner)?,
546                );
547                scanner.finish()?;
548                Ok(this)
549            }
550        }
551    }
552
553    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
554        match self {
555            CredentialValue::UsernameAndPassword(username, password) => {
556                let mut formatter = formatter.format_struct(Self::TAG)?;
557                username.format(&mut formatter)?;
558                if let Some(password) = password {
559                    password.format(&mut formatter)?;
560                }
561                Ok(formatter.finish())
562            }
563        }
564    }
565}
566
567/// 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).
568#[derive(Clone, Debug, PartialEq, Eq)]
569pub struct Username(pub String);
570
571impl Deref for Username {
572    type Target = str;
573
574    fn deref(&self) -> &Self::Target {
575        self.0.as_str()
576    }
577}
578
579impl_ttlv_serde!(text Username as 0x420099);
580
581/// 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).
582#[derive(Clone, Debug, PartialEq, Eq)]
583pub struct Password(pub String);
584
585impl Deref for Password {
586    type Target = str;
587
588    fn deref(&self) -> &Self::Target {
589        self.0.as_str()
590    }
591}
592
593impl_ttlv_serde!(text Password as 0x4200A1);
594
595/// 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).
596#[derive(Clone, Debug, PartialEq, Eq)]
597pub struct KeyBlock(
598    pub KeyFormatType,
599    pub Option<KeyCompressionType>,
600    pub Option<KeyValue>,
601    pub Option<CryptographicAlgorithm>,
602    pub Option<CryptographicLength>,
603    pub Option<KeyWrappingData>,
604);
605
606impl_ttlv_serde!(struct KeyBlock as 0x420040 {
607    fast_scan = |scanner| {
608        let format = KeyFormatType::fast_scan(&mut scanner)?;
609        Self(
610            format,
611            KeyCompressionType::fast_scan_opt(&mut scanner)?,
612            KeyValue::fast_scan_opt(&mut scanner, &format)?,
613            CryptographicAlgorithm::fast_scan_opt(&mut scanner)?,
614            CryptographicLength::fast_scan_opt(&mut scanner)?,
615            KeyWrappingData::fast_scan_opt(&mut scanner)?,
616        )
617    };
618
619    format = |&self, formatter| {
620        self.0.format(&mut formatter)?;
621        if let Some(x) = &self.1 { x.format(&mut formatter)?; }
622        if let Some(x) = &self.2 { x.format(&mut formatter)?; }
623        if let Some(x) = &self.3 { x.format(&mut formatter)?; }
624        if let Some(x) = &self.4 { x.format(&mut formatter)?; }
625        if let Some(x) = &self.5 { x.format(&mut formatter)?; }
626    };
627});
628
629/// 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).
630#[derive(Clone, Debug, PartialEq, Eq)]
631pub struct KeyValue(pub KeyMaterial, pub Option<Vec<Attribute>>);
632
633impl KeyValue {
634    pub const TAG: Tag = Tag::new(0x420045);
635
636    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, format: &KeyFormatType) -> Result<Option<Self>, FastScanError> {
637        let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? else {
638            return Ok(None);
639        };
640        let material = KeyMaterial::fast_scan(&mut scanner, format)?;
641        let attributes =
642            std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<Vec<_>, _>>()?;
643        let attributes = Some(attributes).filter(|a| !a.is_empty());
644        scanner.finish()?;
645        Ok(Some(Self(material, attributes)))
646    }
647
648    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
649        let mut formatter = formatter.format_struct(Self::TAG)?;
650        self.0.format(&mut formatter)?;
651        for attribute in self.1.iter().flatten() {
652            attribute.format(&mut formatter)?;
653        }
654        Ok(formatter.finish())
655    }
656}
657
658/// 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).
659#[derive(Clone, Debug, PartialEq, Eq)]
660pub struct KeyWrappingData(
661    pub WrappingMethod,
662    pub Option<EncryptionKeyInformation>,
663    pub Option<MACOrSignatureKeyInformation>,
664    pub Option<MACOrSignature>,
665    pub Option<IVOrCounterOrNonce>,
666    pub Option<Vec<Attribute>>,
667);
668
669impl_ttlv_serde!(struct KeyWrappingData(
670    a: WrappingMethod,
671    #[option] b: EncryptionKeyInformation,
672    #[option] c: MACOrSignatureKeyInformation,
673    #[option] d: MACOrSignature,
674    #[option] e: IVOrCounterOrNonce,
675    #[option+vec] f: Attribute,
676) as 0x420046);
677
678/// 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).
679#[derive(Clone, Debug, PartialEq, Eq)]
680pub struct MACOrSignature(Vec<u8>);
681
682impl_ttlv_serde!(bytes MACOrSignature as 0x42004D);
683
684/// 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).
685#[derive(Clone, Debug, PartialEq, Eq)]
686pub struct IVOrCounterOrNonce(Vec<u8>);
687
688impl_ttlv_serde!(bytes IVOrCounterOrNonce as 0x42003D);
689
690/// 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).
691#[derive(Clone, Debug, PartialEq, Eq)]
692pub struct EncryptionKeyInformation(pub UniqueIdentifier, pub Option<CryptographicParameters>);
693
694impl_ttlv_serde!(struct EncryptionKeyInformation(
695    id: UniqueIdentifier,
696    #[option] params: CryptographicParameters,
697) as 0x420036);
698
699/// 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).
700#[derive(Clone, Debug, PartialEq, Eq)]
701pub struct MACOrSignatureKeyInformation(pub UniqueIdentifier, pub Option<CryptographicParameters>);
702
703impl_ttlv_serde!(struct MACOrSignatureKeyInformation(
704    id: UniqueIdentifier,
705    #[option] params: CryptographicParameters,
706) as 0x42004E);
707
708/// 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).
709#[derive(Clone, Debug, PartialEq, Eq)]
710pub struct KeyWrappingSpecification(
711    pub WrappingMethod,
712    pub Option<EncryptionKeyInformation>,
713    pub Option<MACOrSignatureKeyInformation>,
714    pub Option<Vec<Attribute>>,
715);
716
717impl_ttlv_serde!(struct KeyWrappingSpecification(
718    a: WrappingMethod,
719    #[option] b: EncryptionKeyInformation,
720    #[option] c: MACOrSignatureKeyInformation,
721    #[option+vec] d: Attribute,
722) as 0x420047);
723
724/// 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).
725#[derive(Clone, Debug, PartialEq, Eq)]
726#[non_exhaustive]
727pub enum ManagedObject {
728    // Certificate(Certificate),
729    // Not implemented
730    SymmetricKey(SymmetricKey),
731
732    PublicKey(PublicKey),
733
734    PrivateKey(PrivateKey),
735
736    // SplitKey(SplitKey),
737    // Not implemented
738    Template(Template),
739    // SecretData(SecretData),
740    // Not implemented
741
742    // OpaqueObject(OpaqueObject),
743    // Not implemented
744}
745
746impl ManagedObject {
747    pub fn fast_scan(scanner: &mut FastScanner<'_>, r#type: ObjectType) -> Result<Self, FastScanError> {
748        match r#type {
749            ObjectType::SymmetricKey => SymmetricKey::fast_scan(scanner).map(Self::SymmetricKey),
750            ObjectType::PublicKey => PublicKey::fast_scan(scanner).map(Self::PublicKey),
751            ObjectType::PrivateKey => PrivateKey::fast_scan(scanner).map(Self::PrivateKey),
752            ObjectType::Template => Template::fast_scan(scanner).map(Self::Template),
753
754            ObjectType::Certificate
755            | ObjectType::SplitKey
756            | ObjectType::SecretData
757            | ObjectType::OpaqueObject
758            | ObjectType::PGPKey => unimplemented!(),
759        }
760    }
761
762    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, r#type: ObjectType) -> Result<Option<Self>, FastScanError> {
763        match r#type {
764            ObjectType::SymmetricKey => SymmetricKey::fast_scan_opt(scanner).map(|s| s.map(Self::SymmetricKey)),
765            ObjectType::PublicKey => PublicKey::fast_scan_opt(scanner).map(|s| s.map(Self::PublicKey)),
766            ObjectType::PrivateKey => PrivateKey::fast_scan_opt(scanner).map(|s| s.map(Self::PrivateKey)),
767            ObjectType::Template => Template::fast_scan_opt(scanner).map(|s| s.map(Self::Template)),
768
769            ObjectType::Certificate
770            | ObjectType::SplitKey
771            | ObjectType::SecretData
772            | ObjectType::OpaqueObject
773            | ObjectType::PGPKey => unimplemented!(),
774        }
775    }
776
777    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
778        match self {
779            ManagedObject::SymmetricKey(this) => this.format(formatter),
780            ManagedObject::PublicKey(this) => this.format(formatter),
781            ManagedObject::PrivateKey(this) => this.format(formatter),
782            ManagedObject::Template(this) => this.format(formatter),
783        }
784    }
785}
786
787/// 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).
788#[derive(Clone, Debug, PartialEq, Eq)]
789pub struct SymmetricKey(pub KeyBlock);
790
791impl_ttlv_serde!(struct SymmetricKey(block: KeyBlock) as 0x42008F);
792
793/// 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).
794#[derive(Clone, Debug, PartialEq, Eq)]
795pub struct PublicKey(pub KeyBlock);
796
797impl_ttlv_serde!(struct PublicKey(block: KeyBlock) as 0x42006D);
798
799/// 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).
800#[derive(Clone, Debug, PartialEq, Eq)]
801pub struct PrivateKey(pub KeyBlock);
802
803impl_ttlv_serde!(struct PrivateKey(block: KeyBlock) as 0x420064);
804
805/// 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).
806#[derive(Clone, Debug, PartialEq, Eq)]
807pub struct Template(pub Vec<Attribute>);
808
809impl_ttlv_serde!(struct Template(#[vec] attrs: Attribute) as 0x420090);
810
811/// 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).
812#[derive(Clone, Debug, PartialEq, Eq)]
813pub struct Name(pub NameValue, pub NameType);
814
815impl FromStr for Name {
816    type Err = ();
817
818    fn from_str(s: &str) -> Result<Self, Self::Err> {
819        Ok(Self(NameValue::from_str(s)?, NameType::UninterpretedTextString))
820    }
821}
822
823impl fmt::Display for Name {
824    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
825        f.write_fmt(format_args!("{}", self.0))
826    }
827}
828
829impl_ttlv_serde!(struct Name(
830    value: NameValue,
831    r#type: NameType,
832) as 0x420053);
833
834/// 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).
835#[derive(Clone, Debug, PartialEq, Eq)]
836pub struct RevocationReason(pub RevocationReasonCode, pub Option<RevocationMessage>);
837
838impl_ttlv_serde!(struct RevocationReason(
839    code: RevocationReasonCode,
840    #[option] message: RevocationMessage,
841) as 0x420081);
842
843/// 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).
844#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd)]
845pub struct ProtocolVersion(pub ProtocolVersionMajor, pub ProtocolVersionMinor);
846
847impl_ttlv_serde!(struct ProtocolVersion(
848    major: ProtocolVersionMajor,
849    minor: ProtocolVersionMinor,
850) as 0x420069);
851
852/// 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).
853#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
854pub struct ProtocolVersionMajor(pub i32);
855
856impl_ttlv_serde!(int ProtocolVersionMajor as 0x42006A);
857
858/// 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).
859#[derive(Clone, Copy, Debug, PartialEq, Eq, Ord, PartialOrd)]
860pub struct ProtocolVersionMinor(pub i32);
861
862impl_ttlv_serde!(int ProtocolVersionMinor as 0x42006B);
863
864/// 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).
865#[derive(Clone, Copy, Debug, PartialEq, Eq)]
866pub struct MaximumResponseSize(pub i32);
867
868impl_ttlv_serde!(int MaximumResponseSize as 0x420050);
869
870/// One (or more since KMIP 1.2) credentials to authenticate with.
871///
872/// In KMIP 1.0 and 1.1 only a single credential was supported.
873/// In KMIP 1.2 this was expanded to one or more credentials.
874/// In KMIP 2.0 it was specified that if multiple credentials are provided
875/// then they must all be satisfied, prior to that it was not specified what
876/// the server should require if multiple credentials are supplied.
877///
878/// 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).
879/// 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).
880/// 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).
881#[derive(Clone, Debug, PartialEq, Eq)]
882pub struct Authentication(pub Vec<Credential>);
883
884impl Authentication {
885    pub fn build(credential: CredentialValue) -> Authentication {
886        match credential {
887            CredentialValue::UsernameAndPassword(username, password) => Authentication(vec![Credential(
888                CredentialType::UsernameAndPassword,
889                CredentialValue::UsernameAndPassword(username, password),
890            )]),
891        }
892    }
893
894    pub fn credentials(&self) -> &[Credential] {
895        &self.0
896    }
897
898    pub fn username(&self) -> Option<&Username> {
899        self.credentials()
900            .iter()
901            .find(|c| matches!(c.credential_value(), CredentialValue::UsernameAndPassword(..)))
902            .and_then(|c| c.credential_value().username())
903    }
904
905    pub fn password(&self) -> Option<&Password> {
906        self.credentials()
907            .iter()
908            .find(|c| matches!(c.credential_value(), CredentialValue::UsernameAndPassword(..)))
909            .and_then(|c| c.credential_value().password())
910    }
911}
912
913impl_ttlv_serde!(struct Authentication(#[vec] credentials: Credential) as 0x42000C);
914
915/// 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).
916#[derive(Clone, Debug, Default, PartialEq, Eq)]
917pub struct BatchCount(pub i32);
918
919impl_ttlv_serde!(int BatchCount as 0x42000D);
920
921/// 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).
922#[derive(Clone, Debug, PartialEq, Eq)]
923pub struct BatchItem(
924    pub Operation, // TODO: set this somehow automatically to RequestPayload::operation()
925    pub Option<UniqueBatchItemID>,
926    pub RequestPayload,
927);
928
929impl BatchItem {
930    pub fn operation(&self) -> &Operation {
931        &self.0
932    }
933
934    pub fn unique_batch_item_id(&self) -> Option<&UniqueBatchItemID> {
935        self.1.as_ref()
936    }
937
938    pub fn request_payload(&self) -> &RequestPayload {
939        &self.2
940    }
941}
942
943impl_ttlv_serde!(struct BatchItem as 0x42000F {
944    fast_scan = |scanner| {
945        let operation = Operation::fast_scan(&mut scanner)?;
946        let id = UniqueBatchItemID::fast_scan_opt(&mut scanner)?;
947        let payload = RequestPayload::fast_scan(&mut scanner, operation)?;
948        Self(operation, id, payload)
949    };
950
951    format = |&self, formatter| {
952        self.0.format(&mut formatter)?;
953        if let Some(x) = &self.1 { x.format(&mut formatter)?; }
954        self.2.format(&mut formatter)?;
955    };
956});
957
958/// 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).
959#[derive(Clone, Debug, PartialEq, Eq)]
960pub struct RequestMessage(pub RequestHeader, pub Vec<BatchItem>);
961
962impl RequestMessage {
963    pub fn header(&self) -> &RequestHeader {
964        &self.0
965    }
966
967    pub fn batch_items(&self) -> &[BatchItem] {
968        &self.1
969    }
970}
971
972impl_ttlv_serde!(struct RequestMessage as 0x420078 {
973    fast_scan = |scanner| {
974        let header = RequestHeader::fast_scan(&mut scanner)?;
975        let BatchCount(count) = header.5;
976        let items = (0..count)
977            .map(|_| BatchItem::fast_scan(&mut scanner))
978            .collect::<Result<Vec<_>, _>>()?;
979        Self(header, items)
980    };
981
982    format = |&self, formatter| {
983        self.0.format(&mut formatter)?;
984        for item in &self.1 {
985            item.format(&mut formatter)?;
986        }
987    };
988});
989
990/// 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).
991#[derive(Clone, Debug, PartialEq, Eq)]
992pub struct RequestHeader(
993    pub ProtocolVersion,
994    pub Option<MaximumResponseSize>,
995    pub Option<Authentication>,
996    pub Option<BatchErrorContinuationOption>,
997    pub Option<bool>, // BatchOrderOption
998    pub BatchCount,
999);
1000
1001impl RequestHeader {
1002    pub fn protocol_version(&self) -> &ProtocolVersion {
1003        &self.0
1004    }
1005
1006    pub fn max_response_size(&self) -> Option<&MaximumResponseSize> {
1007        self.1.as_ref()
1008    }
1009
1010    pub fn authentication(&self) -> Option<&Authentication> {
1011        self.2.as_ref()
1012    }
1013
1014    pub fn batch_count(&self) -> &BatchCount {
1015        &self.5
1016    }
1017}
1018
1019impl_ttlv_serde!(struct RequestHeader as 0x420077 {
1020    fast_scan = |scanner| Self(
1021        ProtocolVersion::fast_scan(&mut scanner)?,
1022        MaximumResponseSize::fast_scan_opt(&mut scanner)?,
1023        Authentication::fast_scan_opt(&mut scanner)?,
1024        BatchErrorContinuationOption::fast_scan_opt(&mut scanner)?,
1025        scanner.scan_opt_bool(Tag::new(0x420010))?,
1026        BatchCount::fast_scan_opt(&mut scanner)?.unwrap_or_default(),
1027    );
1028
1029    format = |&self, formatter| {
1030        self.0.format(&mut formatter)?;
1031        if let Some(x) = &self.1 { x.format(&mut formatter)?; }
1032        if let Some(x) = &self.2 { x.format(&mut formatter)?; }
1033        if let Some(x) = &self.3 { x.format(&mut formatter)?; }
1034        if let Some(x) = &self.4 { formatter.format_bool(Tag::new(0x420010), *x)?; }
1035        self.5.format(&mut formatter)?;
1036    };
1037});
1038
1039#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1040#[non_exhaustive]
1041#[repr(u32)]
1042pub enum BatchErrorContinuationOption {
1043    Continue = 1,
1044    Stop,
1045    Undo,
1046}
1047
1048impl_ttlv_serde!(enum BatchErrorContinuationOption as 0x42000E);
1049
1050/// 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).
1051#[derive(Clone, Debug, PartialEq, Eq)]
1052#[non_exhaustive]
1053#[allow(clippy::large_enum_variant)]
1054pub enum RequestPayload {
1055    /// See KMIP 1.0 section 4.1 Create.
1056    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581209>
1057    Create(ObjectType, TemplateAttribute),
1058
1059    /// See KMIP 1.0 section 4.2 Create Key Pair.
1060    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581210>
1061    CreateKeyPair(
1062        Option<CommonTemplateAttribute>,
1063        Option<PrivateKeyTemplateAttribute>,
1064        Option<PublicKeyTemplateAttribute>,
1065    ),
1066
1067    /// See KMIP 1.0 section 4.3 Register.
1068    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581211>
1069    Register(ObjectType, TemplateAttribute, Option<ManagedObject>),
1070
1071    // TODO? Missing operation code mappings to request payloads
1072    // Re-key = 4
1073    // Derive Key = 5
1074    // Certify = 6
1075    // Re-certify = 7
1076    /// See KMIP 1.0 section 4.8 Locate.
1077    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581216>
1078    Locate(Vec<Attribute>), // TODO: Add MaximumItems and StorageStatusMask optional request payload fields
1079
1080    /// See KMIP 1.0 section 4.10 Get.
1081    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218>
1082    Get(
1083        Option<UniqueIdentifier>,
1084        Option<KeyFormatType>,
1085        Option<KeyCompressionType>,
1086        Option<KeyWrappingSpecification>,
1087    ),
1088
1089    /// See KMIP 1.0 section 4.11 Get Attributes.
1090    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581219>
1091    GetAttributes(Option<UniqueIdentifier>, Option<Vec<AttributeName>>),
1092
1093    /// See KMIP 1.0 section 4.12 Get Attribute List.
1094    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581220>
1095    GetAttributeList(Option<UniqueIdentifier>),
1096
1097    /// See KMIP 1.0 section 4.13 Add Attribute.
1098    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581221>
1099    AddAttribute(Option<UniqueIdentifier>, Attribute),
1100
1101    /// See KMIP 1.0 section 4.14 Modify Attribute.
1102    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222>
1103    ModifyAttribute(Option<UniqueIdentifier>, Attribute),
1104
1105    /// See KMIP 1.0 section 4.15 Delete Attribute.
1106    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581223>
1107    DeleteAttribute(Option<UniqueIdentifier>, AttributeName, Option<AttributeIndex>),
1108
1109    // TODO? Missing operation code mappings to request payloads
1110    // Obtain Lease = 10
1111    // Get Usage Allocation = 11
1112    /// See KMIP 1.0 section 4.18 Activate.
1113    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226>
1114    Activate(Option<UniqueIdentifier>),
1115
1116    /// See KMIP 1.0 section 4.19 Revoke.
1117    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227>
1118    Revoke(
1119        Option<UniqueIdentifier>,
1120        RevocationReason,
1121        Option<CompromiseOccurrenceDate>,
1122    ),
1123
1124    /// See KMIP 1.0 section 4.20 Destroy.
1125    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228>
1126    Destroy(Option<UniqueIdentifier>),
1127
1128    // TODO? Missing operation code mappings to request payloads
1129    // Archive = 15
1130    // Recover = 16
1131    // Validate = 17
1132    /// See KMIP 1.0 section 4.24 Query.
1133    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232>
1134    Query(Vec<QueryFunction>),
1135
1136    // TODO? Missing operation code mappings to request payloads
1137    // Cancel = 19
1138    // Poll = 1A
1139    // Notify = 1B
1140    // Put = 1C
1141    // Re-key Key Pair = 1D
1142    /// See KMIP 1.1 section 4.26 Discover Versions.
1143    /// See: <https://docs.oasis-open.org/kmip/spec/v1.1/cs01/kmip-spec-v1.1-cs01.html#_Toc332787652>
1144    DiscoverVersions(Vec<ProtocolVersion>),
1145
1146    // TODO? Missing operation code mappings to request payloads
1147    // Encrypt = 1F
1148    // Decrypt = 20
1149    /// See KMIP 1.2 section 4.31 Sign.
1150    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558>
1151    Sign(Option<UniqueIdentifier>, Option<CryptographicParameters>, Data),
1152
1153    // TODO? Missing operation code mappings to request payloads
1154    // Signature Verify = 22
1155    // MAC = 23
1156    // MAC Verify = 24
1157    /// See KMIP 1.2 section 4.35 RNG Retrieve.
1158    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613562>
1159    RNGRetrieve(DataLength),
1160}
1161
1162impl RequestPayload {
1163    pub fn operation(&self) -> Operation {
1164        match self {
1165            RequestPayload::Create(..) => Operation::Create,
1166            RequestPayload::CreateKeyPair(..) => Operation::CreateKeyPair,
1167            RequestPayload::Register(..) => Operation::Register,
1168            // Not implemented: Re-key (KMIP 1.0)
1169            // Not implemented: Re-key Key Pair (KMIP 1.1)
1170            // Not implemented: Derive Key (KMIP 1.0)
1171            // Not implemented: Certify (KMIP 1.0)
1172            // Not implemented: Re-certify (KMIP 1.0)
1173            RequestPayload::Locate(..) => Operation::Locate,
1174            // Not implemented: Check (KMIP 1.0)
1175            RequestPayload::Get(..) => Operation::Get,
1176            RequestPayload::GetAttributes(..) => Operation::GetAttributes,
1177            RequestPayload::GetAttributeList(..) => Operation::GetAttributeList,
1178            RequestPayload::AddAttribute(..) => Operation::AddAttribute,
1179            RequestPayload::ModifyAttribute(..) => Operation::ModifyAttribute,
1180            RequestPayload::DeleteAttribute(..) => Operation::DeleteAttribute,
1181            // Not implemented: Obtain Lease (KMIP 1.0)
1182            // Not implemented: Get Usage Allocation (KMIP 1.0)
1183            RequestPayload::Activate(..) => Operation::Activate,
1184            RequestPayload::Revoke(..) => Operation::Revoke,
1185            RequestPayload::Destroy(..) => Operation::Destroy,
1186            // Not implemented: Archive (KMIP 1.0)
1187            // Not implemented: Recover (KMIP 1.0)
1188            // Not implemented: Validate (KMIP 1.0)
1189            RequestPayload::Query(..) => Operation::Query,
1190            RequestPayload::DiscoverVersions(..) => Operation::DiscoverVersions,
1191            // Not implemented: Cancel (KMIP 1.0)
1192            // Not implemented: Poll (KMIP 1.0)
1193            // Not implemented: Encrypt (KMIP 1.2)
1194            // Not implemented: Decrypt (KMIP 1.2)
1195            RequestPayload::Sign(..) => Operation::Sign,
1196            // Not implemented: Signature Verify (KMIP 1.2)
1197            // Not implemented: MAC (KMIP 1.2)
1198            // Not implemented: MAC Verify (KMIP 1.2)
1199            RequestPayload::RNGRetrieve(..) => Operation::RNGRetrieve,
1200            // Not implemented: RNG Seed (KMIP 1.2)
1201            // Not implemented: Hash (KMIP 1.2)
1202            // Not implemented: Create Split Key (KMIP 1.2)
1203            // Not implemented: Join Split Key (KMIP 1.2)
1204        }
1205    }
1206
1207    pub fn protocol_version(&self) -> ProtocolVersion {
1208        match self {
1209            RequestPayload::Create(..)
1210            | RequestPayload::CreateKeyPair(..)
1211            | RequestPayload::Register(..)
1212            | RequestPayload::Locate(..)
1213            | RequestPayload::Get(..)
1214            | RequestPayload::GetAttributes(..)
1215            | RequestPayload::GetAttributeList(..)
1216            | RequestPayload::AddAttribute(..)
1217            | RequestPayload::ModifyAttribute(..)
1218            | RequestPayload::DeleteAttribute(..)
1219            | RequestPayload::Activate(..)
1220            | RequestPayload::Revoke(..)
1221            | RequestPayload::Destroy(..) => {
1222                // These KMIP operations are defined in the KMIP 1.0 specification
1223                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(0))
1224            }
1225            RequestPayload::DiscoverVersions(..) => {
1226                // These KMIP operations are defined in the KMIP 1.1 specification
1227                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(1))
1228            }
1229            RequestPayload::Sign(..) | RequestPayload::RNGRetrieve(..) => {
1230                // These KMIP operations are defined in the KMIP 1.2 specification
1231                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(2))
1232            }
1233            RequestPayload::Query(..) => {
1234                // TODO: Although query is defined in the KMIP 1.0 specification, KMIP servers that support KMIP >1.0
1235                // are required by the specification to "support backward compatibility with versions of the protocol
1236                // with the same major version". A KMIP 1.2 server cannot respond to a Query request with KMIP tag
1237                // numbers representing KMIP Operations that were only defined in a KMIP specification >1.0. Presumably
1238                // therefore we must pass the highest version number that both we and the server support. Currently
1239                // this is just dumb and passes the highest version number that we support, we should actually base
1240                // it on the result of a previous attempt to use the KMIP 1.1 Discover Versions request.
1241                ProtocolVersion(ProtocolVersionMajor(1), ProtocolVersionMinor(2))
1242            }
1243        }
1244    }
1245}
1246
1247impl RequestPayload {
1248    pub const TAG: Tag = Tag::new(0x420079);
1249
1250    pub fn fast_scan(scanner: &mut FastScanner<'_>, operation: Operation) -> Result<Self, FastScanError> {
1251        let mut scanner = scanner.scan_struct(Self::TAG)?;
1252        let this = match operation {
1253            Operation::Create => Self::Create(
1254                ObjectType::fast_scan(&mut scanner)?,
1255                TemplateAttribute::fast_scan(&mut scanner)?,
1256            ),
1257            Operation::CreateKeyPair => Self::CreateKeyPair(
1258                CommonTemplateAttribute::fast_scan_opt(&mut scanner)?,
1259                PrivateKeyTemplateAttribute::fast_scan_opt(&mut scanner)?,
1260                PublicKeyTemplateAttribute::fast_scan_opt(&mut scanner)?,
1261            ),
1262            Operation::Register => {
1263                let r#type = ObjectType::fast_scan(&mut scanner)?;
1264                Self::Register(
1265                    r#type,
1266                    TemplateAttribute::fast_scan(&mut scanner)?,
1267                    ManagedObject::fast_scan_opt(&mut scanner, r#type)?,
1268                )
1269            }
1270            Operation::Locate => Self::Locate(
1271                std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose()).collect::<Result<_, _>>()?,
1272            ),
1273            Operation::Get => Self::Get(
1274                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1275                KeyFormatType::fast_scan_opt(&mut scanner)?,
1276                KeyCompressionType::fast_scan_opt(&mut scanner)?,
1277                KeyWrappingSpecification::fast_scan_opt(&mut scanner)?,
1278            ),
1279            Operation::GetAttributes => Self::GetAttributes(
1280                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1281                std::iter::from_fn(|| AttributeName::fast_scan_opt(&mut scanner).transpose())
1282                    .collect::<Result<Vec<_>, _>>()
1283                    .map(Some)?
1284                    .filter(|s| !s.is_empty()),
1285            ),
1286            Operation::GetAttributeList => Self::GetAttributeList(UniqueIdentifier::fast_scan_opt(&mut scanner)?),
1287            Operation::AddAttribute => Self::AddAttribute(
1288                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1289                Attribute::fast_scan(&mut scanner)?,
1290            ),
1291            Operation::ModifyAttribute => Self::ModifyAttribute(
1292                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1293                Attribute::fast_scan(&mut scanner)?,
1294            ),
1295            Operation::DeleteAttribute => Self::DeleteAttribute(
1296                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1297                AttributeName::fast_scan(&mut scanner)?,
1298                AttributeIndex::fast_scan_opt(&mut scanner)?,
1299            ),
1300            Operation::Activate => Self::Activate(UniqueIdentifier::fast_scan_opt(&mut scanner)?),
1301            Operation::Revoke => Self::Revoke(
1302                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1303                RevocationReason::fast_scan(&mut scanner)?,
1304                CompromiseOccurrenceDate::fast_scan_opt(&mut scanner)?,
1305            ),
1306            Operation::Destroy => Self::Destroy(UniqueIdentifier::fast_scan_opt(&mut scanner)?),
1307            Operation::Query => Self::Query(
1308                std::iter::from_fn(|| QueryFunction::fast_scan_opt(&mut scanner).transpose())
1309                    .collect::<Result<_, _>>()?,
1310            ),
1311            Operation::DiscoverVersions => Self::DiscoverVersions(
1312                std::iter::from_fn(|| ProtocolVersion::fast_scan_opt(&mut scanner).transpose())
1313                    .collect::<Result<_, _>>()?,
1314            ),
1315            Operation::Sign => Self::Sign(
1316                UniqueIdentifier::fast_scan_opt(&mut scanner)?,
1317                CryptographicParameters::fast_scan_opt(&mut scanner)?,
1318                Data::fast_scan(&mut scanner)?,
1319            ),
1320            Operation::RNGRetrieve => Self::RNGRetrieve(DataLength::fast_scan(&mut scanner)?),
1321
1322            _ => unimplemented!(),
1323        };
1324        scanner.finish()?;
1325        Ok(this)
1326    }
1327
1328    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1329        let mut formatter = formatter.format_struct(Self::TAG)?;
1330        match self {
1331            RequestPayload::Create(object_type, template_attribute) => {
1332                object_type.format(&mut formatter)?;
1333                template_attribute.format(&mut formatter)?;
1334            }
1335            RequestPayload::CreateKeyPair(
1336                common_template_attribute,
1337                private_key_template_attribute,
1338                public_key_template_attribute,
1339            ) => {
1340                if let Some(x) = common_template_attribute {
1341                    x.format(&mut formatter)?;
1342                }
1343                if let Some(x) = private_key_template_attribute {
1344                    x.format(&mut formatter)?;
1345                }
1346                if let Some(x) = public_key_template_attribute {
1347                    x.format(&mut formatter)?;
1348                }
1349            }
1350            RequestPayload::Register(object_type, template_attribute, managed_object) => {
1351                object_type.format(&mut formatter)?;
1352                template_attribute.format(&mut formatter)?;
1353                if let Some(x) = managed_object {
1354                    x.format(&mut formatter)?;
1355                }
1356            }
1357            RequestPayload::Locate(attributes) => {
1358                for x in attributes {
1359                    x.format(&mut formatter)?;
1360                }
1361            }
1362            RequestPayload::Get(
1363                unique_identifier,
1364                key_format_type,
1365                key_compression_type,
1366                key_wrapping_specification,
1367            ) => {
1368                if let Some(x) = unique_identifier {
1369                    x.format(&mut formatter)?;
1370                }
1371                if let Some(x) = key_format_type {
1372                    x.format(&mut formatter)?;
1373                }
1374                if let Some(x) = key_compression_type {
1375                    x.format(&mut formatter)?;
1376                }
1377                if let Some(x) = key_wrapping_specification {
1378                    x.format(&mut formatter)?;
1379                }
1380            }
1381            RequestPayload::GetAttributes(unique_identifier, attribute_names) => {
1382                if let Some(x) = unique_identifier {
1383                    x.format(&mut formatter)?;
1384                }
1385                for x in attribute_names.iter().flatten() {
1386                    x.format(&mut formatter)?;
1387                }
1388            }
1389            RequestPayload::GetAttributeList(unique_identifier) => {
1390                if let Some(x) = unique_identifier {
1391                    x.format(&mut formatter)?;
1392                }
1393            }
1394            RequestPayload::AddAttribute(unique_identifier, attribute) => {
1395                if let Some(x) = unique_identifier {
1396                    x.format(&mut formatter)?;
1397                }
1398                attribute.format(&mut formatter)?;
1399            }
1400            RequestPayload::ModifyAttribute(unique_identifier, attribute) => {
1401                if let Some(x) = unique_identifier {
1402                    x.format(&mut formatter)?;
1403                }
1404                attribute.format(&mut formatter)?;
1405            }
1406            RequestPayload::DeleteAttribute(unique_identifier, attribute_name, attribute_index) => {
1407                if let Some(x) = unique_identifier {
1408                    x.format(&mut formatter)?;
1409                }
1410                attribute_name.format(&mut formatter)?;
1411                if let Some(x) = attribute_index {
1412                    x.format(&mut formatter)?;
1413                }
1414            }
1415            RequestPayload::Activate(unique_identifier) => {
1416                if let Some(x) = unique_identifier {
1417                    x.format(&mut formatter)?;
1418                }
1419            }
1420            RequestPayload::Revoke(unique_identifier, revocation_reason, compromise_occurrence_date) => {
1421                if let Some(x) = unique_identifier {
1422                    x.format(&mut formatter)?;
1423                }
1424                revocation_reason.format(&mut formatter)?;
1425                if let Some(x) = compromise_occurrence_date {
1426                    x.format(&mut formatter)?;
1427                }
1428            }
1429            RequestPayload::Destroy(unique_identifier) => {
1430                if let Some(x) = unique_identifier {
1431                    x.format(&mut formatter)?;
1432                }
1433            }
1434            RequestPayload::Query(query_functions) => {
1435                for x in query_functions {
1436                    x.format(&mut formatter)?;
1437                }
1438            }
1439            RequestPayload::DiscoverVersions(protocol_versions) => {
1440                for x in protocol_versions {
1441                    x.format(&mut formatter)?;
1442                }
1443            }
1444            RequestPayload::Sign(unique_identifier, cryptographic_parameters, data) => {
1445                if let Some(x) = unique_identifier {
1446                    x.format(&mut formatter)?;
1447                }
1448                if let Some(x) = cryptographic_parameters {
1449                    x.format(&mut formatter)?;
1450                }
1451                data.format(&mut formatter)?;
1452            }
1453            RequestPayload::RNGRetrieve(data_length) => {
1454                data_length.format(&mut formatter)?;
1455            }
1456        }
1457        Ok(formatter.finish())
1458    }
1459}
1460
1461/// 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).
1462#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1463#[non_exhaustive]
1464#[repr(u32)]
1465pub enum WrappingMethod {
1466    Encrypt = 1,
1467    MACSign,
1468    EncryptThenMACSign,
1469    MACSignThenEncrypt,
1470    TR31,
1471}
1472
1473impl_ttlv_serde!(enum WrappingMethod as 0x42009E);
1474
1475impl fmt::Display for WrappingMethod {
1476    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1477        write!(f, "{self:?}")
1478    }
1479}
1480
1481/// 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).
1482#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1483#[non_exhaustive]
1484#[repr(u32)]
1485pub enum QueryFunction {
1486    QueryOperations = 0x00000001,
1487    QueryObjects,
1488    QueryServerInformation,
1489    QueryExtensionList = 0x00000005,
1490}
1491
1492impl_ttlv_serde!(enum QueryFunction as 0x420074);
1493
1494impl fmt::Display for QueryFunction {
1495    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1496        write!(f, "{self:?}")
1497    }
1498}