Skip to main content

kmip_protocol/types/
response.rs

1//! Rust types for deserializing KMIP responses.
2use std::fmt;
3
4use enum_ordinalize::Ordinalize;
5
6use crate::ttlv::fast_scan::{FastScanError, FastScanner};
7use crate::ttlv::format::{FormatDone, FormatResult, Formatter, TruncationError};
8use crate::ttlv::types::Tag;
9use crate::types::common::{CryptographicLength, Data};
10
11use super::common::{
12    AttributeIndex, AttributeName, AttributeValue, CertificateType, CryptographicAlgorithm, KeyCompressionType,
13    KeyFormatType, KeyMaterial, NameType, NameValue, ObjectType, Operation, UniqueBatchItemID, UniqueIdentifier,
14};
15
16use super::impl_ttlv_serde;
17
18pub fn from_slice(buffer: &[u8]) -> Result<ResponseMessage, FastScanError> {
19    let (res, rest) = crate::ttlv::from_slice(buffer, ResponseMessage::fast_scan)?;
20    if !rest.is_empty() {
21        Err(FastScanError::assert())
22    } else {
23        Ok(res)
24    }
25}
26
27pub fn to_vec(response: ResponseMessage) -> std::result::Result<Vec<u8>, TruncationError> {
28    crate::ttlv::to_vec(|f| response.format(f))
29}
30
31///  See KMIP 1.0 section 2.1.3 [Key Block](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581157).
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct KeyBlock {
34    pub key_format_type: KeyFormatType,
35    pub key_compression_type: Option<KeyCompressionType>,
36    pub key_value: KeyValue,
37    pub cryptographic_algorithm: Option<CryptographicAlgorithm>,
38    pub cryptographic_length: Option<i32>,
39    pub key_wrapping_data: Option<()>, // TODO
40}
41
42impl_ttlv_serde!(struct KeyBlock as 0x420040 {
43    fast_scan = |scanner| {
44        let key_format_type = KeyFormatType::fast_scan(&mut scanner)?;
45        Self {
46            key_format_type,
47            key_compression_type: KeyCompressionType::fast_scan_opt(&mut scanner)?,
48            key_value: KeyValue::fast_scan(&mut scanner, &key_format_type)?,
49            cryptographic_algorithm: CryptographicAlgorithm::fast_scan_opt(&mut scanner)?,
50            cryptographic_length: CryptographicLength::fast_scan_opt(&mut scanner)?.map(|s| s.0),
51            key_wrapping_data: { scanner.skip_opt_struct(Tag::new(0x420046))?; None },
52        }
53    };
54
55    format = |&self, formatter| {
56        self.key_format_type.format(&mut formatter)?;
57        if let Some(x) = &self.key_compression_type { x.format(&mut formatter)?; }
58        self.key_value.format(&mut formatter)?;
59        if let Some(x) = self.cryptographic_algorithm { x.format(&mut formatter)?; }
60        if let Some(x) = self.cryptographic_length { CryptographicLength(x).format(&mut formatter)?; }
61    };
62});
63
64///  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).
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct KeyValue {
67    pub key_material: KeyMaterial,
68    pub attributes: Option<Vec<Attribute>>,
69}
70
71impl KeyValue {
72    pub const TAG: Tag = Tag::new(0x420045);
73    pub const KEY_MATERIAL_TAG: Tag = Tag::new(0x420043);
74
75    pub fn fast_scan(scanner: &mut FastScanner<'_>, format: &KeyFormatType) -> Result<Self, FastScanError> {
76        // 2.1.4 Key Value
77        // The Key Value is used only inside a Key Block and is either a Byte String or a structure (see Table 8):
78
79        // Try first as a byte string.
80        let (key_material, attributes) = if let Some(bytes) = scanner.scan_opt_bytes(Self::KEY_MATERIAL_TAG)? {
81            (KeyMaterial::Bytes(bytes.to_vec()), None)
82        } else {
83            let mut scanner = scanner.scan_struct(Self::TAG)?;
84            let key_material = KeyMaterial::fast_scan(&mut scanner, format)?;
85            let attributes = std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose())
86                .collect::<Result<Vec<_>, _>>()?;
87            let attributes = Some(attributes).filter(|a| !a.is_empty());
88            scanner.finish()?;
89            (key_material, attributes)
90        };
91        Ok(Self {
92            key_material,
93            attributes,
94        })
95    }
96
97    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, format: &KeyFormatType) -> Result<Option<Self>, FastScanError> {
98        // 2.1.4 Key Value
99        // The Key Value is used only inside a Key Block and is either a Byte String or a structure (see Table 8):
100
101        // Try first as a byte string.
102        let (key_material, attributes) = if let Some(bytes) = scanner.scan_opt_bytes(Self::TAG)? {
103            (KeyMaterial::Bytes(bytes.to_vec()), None)
104        } else if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
105            let key_material = KeyMaterial::fast_scan(&mut scanner, format)?;
106            let attributes = std::iter::from_fn(|| Attribute::fast_scan_opt(&mut scanner).transpose())
107                .collect::<Result<Vec<_>, _>>()?;
108            let attributes = Some(attributes).filter(|a| !a.is_empty());
109            scanner.finish()?;
110            (key_material, attributes)
111        } else {
112            return Ok(None);
113        };
114        Ok(Some(Self {
115            key_material,
116            attributes,
117        }))
118    }
119
120    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
121        let mut formatter = formatter.format_struct(Self::TAG)?;
122        self.key_material.format(&mut formatter)?;
123        for attribute in self.attributes.iter().flatten() {
124            attribute.format(&mut formatter)?;
125        }
126        Ok(formatter.finish())
127    }
128}
129
130///  See KMIP 1.0 section 2.1.8 [Template Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581162).
131#[derive(Clone, Debug, PartialEq, Eq)]
132pub struct TemplateAttribute {
133    pub names: Option<Vec<Name>>,
134    pub attributes: Option<Vec<Attribute>>,
135}
136
137impl_ttlv_serde!(struct TemplateAttribute {
138    #[option+vec] names: Name,
139    #[option+vec] attributes: Attribute,
140} as 0x420091);
141
142///  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).
143#[derive(Clone, Debug, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum ManagedObject {
146    Certificate(Certificate),
147    SymmetricKey(SymmetricKey),
148    PublicKey(PublicKey),
149    PrivateKey(PrivateKey),
150    // TODO:
151    // SplitKey(SplitKey),
152    // Template(Template),
153    // SecretData(SecretData),
154    // OpaqueObject(OpaqueObject),
155}
156
157impl ManagedObject {
158    pub fn fast_scan(scanner: &mut FastScanner<'_>, object_type: ObjectType) -> Result<Self, FastScanError> {
159        let this = match object_type {
160            ObjectType::Certificate => Self::Certificate(Certificate::fast_scan(scanner)?),
161            ObjectType::SymmetricKey => Self::SymmetricKey(SymmetricKey::fast_scan(scanner)?),
162            ObjectType::PublicKey => Self::PublicKey(PublicKey::fast_scan(scanner)?),
163            ObjectType::PrivateKey => Self::PrivateKey(PrivateKey::fast_scan(scanner)?),
164            _ => unimplemented!(),
165        };
166        Ok(this)
167    }
168
169    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
170        match self {
171            ManagedObject::Certificate(certificate) => certificate.format(formatter)?,
172            ManagedObject::SymmetricKey(symmetric_key) => symmetric_key.format(formatter)?,
173            ManagedObject::PublicKey(public_key) => public_key.format(formatter)?,
174            ManagedObject::PrivateKey(private_key) => private_key.format(formatter)?,
175        };
176        Ok(FormatDone::assert())
177    }
178}
179
180impl fmt::Display for ManagedObject {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        match self {
183            ManagedObject::Certificate(_) => write!(f, "Certificate"),
184            ManagedObject::SymmetricKey(_) => write!(f, "SymmetricKey"),
185            ManagedObject::PublicKey(_) => write!(f, "PublicKey"),
186            ManagedObject::PrivateKey(_) => write!(f, "PrivateKey"),
187        }
188    }
189}
190
191///  See KMIP 1.0 section 2.2.1 [Certificate](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581164).
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub struct Certificate {
194    pub certificate_type: CertificateType,
195    pub certificate_value: Vec<u8>,
196}
197
198impl Certificate {
199    pub const TAG: Tag = Tag::new(0x420013);
200    pub const CERTIFICATE_VALUE_TAG: Tag = Tag::new(0x42001E);
201
202    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
203        let mut scanner = scanner.scan_struct(Self::TAG)?;
204        let this = Self {
205            certificate_type: CertificateType::fast_scan(&mut scanner)?,
206            certificate_value: scanner.scan_bytes(Self::CERTIFICATE_VALUE_TAG)?.into(),
207        };
208        scanner.finish()?;
209        Ok(this)
210    }
211
212    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
213        let mut formatter = formatter.format_struct(Self::TAG)?;
214        self.certificate_type.format(&mut formatter)?;
215        formatter.format_bytes(Self::CERTIFICATE_VALUE_TAG, &self.certificate_value)?;
216        Ok(formatter.finish())
217    }
218}
219
220///  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).
221#[derive(Clone, Debug, PartialEq, Eq)]
222pub struct SymmetricKey {
223    pub key_block: KeyBlock,
224}
225
226impl_ttlv_serde!(struct SymmetricKey { key_block: KeyBlock } as 0x42008F);
227
228///  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).
229#[derive(Clone, Debug, PartialEq, Eq)]
230pub struct PublicKey {
231    pub key_block: KeyBlock,
232}
233
234impl_ttlv_serde!(struct PublicKey { key_block: KeyBlock } as 0x42006D);
235
236///  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).
237#[derive(Clone, Debug, PartialEq, Eq)]
238pub struct PrivateKey {
239    pub key_block: KeyBlock,
240}
241
242impl_ttlv_serde!(struct PrivateKey { key_block: KeyBlock } as 0x420064);
243
244///  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).
245#[derive(Clone, Debug, PartialEq, Eq)]
246pub struct Name {
247    pub name: NameValue,
248    pub r#type: NameType,
249}
250
251impl_ttlv_serde!(struct Name {
252    name: NameValue,
253    r#type: NameType,
254} as 0x420053);
255
256///  See KMIP 1.0 section 4.1 [Create](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581209).
257#[derive(Clone, Debug, PartialEq, Eq)]
258pub struct CreateResponsePayload {
259    pub object_type: ObjectType,
260    pub unique_identifier: UniqueIdentifier,
261    pub object_attributes: Option<Vec<Attribute>>,
262}
263
264impl_ttlv_serde!(struct CreateResponsePayload {
265    object_type: ObjectType,
266    unique_identifier: UniqueIdentifier,
267    #[option+vec] object_attributes: Attribute,
268} as 0x42007C);
269
270///  See KMIP 1.0 section 4.2 [Create Key Pair](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581210).
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub struct CreateKeyPairResponsePayload {
273    pub private_key_unique_identifier: UniqueIdentifier,
274    pub public_key_unique_identifier: UniqueIdentifier,
275    // TODO: Add the optional response field that lists attributes for the private key
276    // TODO: Add the optional response field that lists attributes for the public key
277}
278
279impl CreateKeyPairResponsePayload {
280    pub const TAG: Tag = Tag::new(0x42007C);
281    pub const PRIVATE_KEY_IDENTIFICATION_TAG: Tag = Tag::new(0x420066);
282    pub const PUBLIC_KEY_IDENTIFICATION_TAG: Tag = Tag::new(0x42006F);
283
284    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
285        let scanner = scanner.scan_struct(Self::TAG)?;
286        Self::fast_scan_inner(scanner)
287    }
288
289    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
290        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
291            Ok(Some(Self::fast_scan_inner(scanner)?))
292        } else {
293            Ok(None)
294        }
295    }
296
297    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
298        let mut formatter = formatter.format_struct(Self::TAG)?;
299        self.private_key_unique_identifier.format(&mut formatter)?;
300        self.public_key_unique_identifier.format(&mut formatter)?;
301        Ok(formatter.finish())
302    }
303
304    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<Self, FastScanError> {
305        let private_key_unique_identifier =
306            UniqueIdentifier::fast_scan_with(&mut scanner, Self::PRIVATE_KEY_IDENTIFICATION_TAG)?;
307        let public_key_unique_identifier =
308            UniqueIdentifier::fast_scan_with(&mut scanner, Self::PUBLIC_KEY_IDENTIFICATION_TAG)?;
309        Ok(Self {
310            private_key_unique_identifier,
311            public_key_unique_identifier,
312        })
313    }
314}
315
316///  See KMIP 1.0 section 4.3 [Register](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581211).
317#[derive(Clone, Debug, PartialEq, Eq)]
318pub struct RegisterResponsePayload {
319    pub unique_identifier: UniqueIdentifier,
320    pub template_attributes: Option<Vec<TemplateAttribute>>,
321}
322
323impl_ttlv_serde!(struct RegisterResponsePayload {
324    unique_identifier: UniqueIdentifier,
325    #[option+vec] template_attributes: TemplateAttribute,
326} as 0x42007C);
327
328///  See KMIP 1.0 section 4.8 [Locate](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581216).
329#[derive(Clone, Debug, PartialEq, Eq)]
330pub struct LocateResponsePayload {
331    pub unique_identifiers: Vec<UniqueIdentifier>,
332}
333
334impl_ttlv_serde!(struct LocateResponsePayload {
335    #[vec] unique_identifiers: UniqueIdentifier,
336} as 0x42007C);
337
338///  See KMIP 1.0 section 4.10 [Get](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218).
339#[derive(Clone, Debug, PartialEq, Eq)]
340pub struct GetResponsePayload {
341    pub object_type: ObjectType,
342    pub unique_identifier: UniqueIdentifier,
343    pub cryptographic_object: ManagedObject,
344}
345
346impl_ttlv_serde!(struct GetResponsePayload as 0x42007C {
347    fast_scan = |scanner| {
348        let object_type = ObjectType::fast_scan(&mut scanner)?;
349        let unique_identifier = UniqueIdentifier::fast_scan(&mut scanner)?;
350        let cryptographic_object = ManagedObject::fast_scan(&mut scanner, object_type)?;
351        Self { object_type, unique_identifier, cryptographic_object }
352    };
353
354    format = |&self, formatter| {
355        self.object_type.format(&mut formatter)?;
356        self.unique_identifier.format(&mut formatter)?;
357        self.cryptographic_object.format(&mut formatter)?;
358    };
359});
360
361///  See KMIP 1.0 section 4.11 [Get Attributes](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581219).
362#[derive(Clone, Debug, PartialEq, Eq)]
363pub struct GetAttributesResponsePayload {
364    pub unique_identifier: UniqueIdentifier,
365    pub attributes: Option<Vec<Attribute>>,
366}
367
368impl_ttlv_serde!(struct GetAttributesResponsePayload {
369    unique_identifier: UniqueIdentifier,
370    #[option+vec] attributes: Attribute,
371} as 0x42007C);
372
373///  See KMIP 1.0 section 4.12 [Get Attribute List](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581220).
374#[derive(Clone, Debug, PartialEq, Eq)]
375pub struct GetAttributeListResponsePayload {
376    pub unique_identifier: UniqueIdentifier,
377    pub attributes: Vec<AttributeName>,
378}
379
380impl_ttlv_serde!(struct GetAttributeListResponsePayload {
381    unique_identifier: UniqueIdentifier,
382    #[vec] attributes: AttributeName,
383} as 0x42007C);
384
385/// Fields common to sections 4.18 [Activate](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226),
386/// 4.19 [Revoke](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227)
387/// and 4.20 [Destroy](http://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228) responses.
388#[derive(Clone, Debug, PartialEq, Eq)]
389pub struct UniqueIdentifierResponsePayload {
390    pub unique_identifier: UniqueIdentifier,
391}
392
393impl_ttlv_serde!(struct UniqueIdentifierResponsePayload {
394    unique_identifier: UniqueIdentifier,
395} as 0x42007C);
396
397///  See KMIP 1.0 section 4.18 [Activate](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226).
398pub type ActivateResponsePayload = UniqueIdentifierResponsePayload;
399
400///  See KMIP 1.0 section 4.19 [Revoke](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227).
401pub type RevokeResponsePayload = UniqueIdentifierResponsePayload;
402
403///  See KMIP 1.0 section 4.20 [Destroy](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228).
404pub type DestroyResponsePayload = UniqueIdentifierResponsePayload;
405
406/// Fields common to sections 4.13 [Add](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581221),
407/// 4.14 [Modify](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222) and 4.15
408/// [Delete](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581223) Attribute responses.
409#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct AttributeEditResponsePayload {
411    pub unique_identifier: UniqueIdentifier,
412    pub attribute: Attribute,
413}
414
415impl_ttlv_serde!(struct AttributeEditResponsePayload {
416    unique_identifier: UniqueIdentifier,
417    attribute: Attribute,
418} as 0x42007C);
419
420///  See KMIP 1.0 section 4.13 [Add Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581221).
421pub type AddAttributeResponsePayload = AttributeEditResponsePayload;
422
423///  See KMIP 1.0 section 4.14 [Modify Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222).
424pub type ModifyAttributeResponsePayload = AttributeEditResponsePayload;
425
426///  See KMIP 1.0 section 4.15 [Delete Attribute](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581223).
427pub type DeleteAttributeResponsePayload = AttributeEditResponsePayload;
428
429///  See KMIP 1.0 section 4.24 [Query](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232).
430#[derive(Clone, Debug, Default, PartialEq, Eq)]
431pub struct QueryResponsePayload {
432    pub operations: Option<Vec<Operation>>,
433    pub object_types: Option<Vec<ObjectType>>,
434    pub vendor_identification: Option<String>,
435    pub server_information: Option<ServerInformation>,
436    pub extension_information: Option<Vec<ExtensionInformation>>,
437}
438
439impl QueryResponsePayload {
440    pub const TAG: Tag = Tag::new(0x42007C);
441    pub const VENDOR_IDENTIFICATION_TAG: Tag = Tag::new(0x42009D);
442
443    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
444        let scanner = scanner.scan_struct(Self::TAG)?;
445        Self::fast_scan_inner(scanner)
446    }
447
448    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
449        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
450            Ok(Some(Self::fast_scan_inner(scanner)?))
451        } else {
452            Ok(None)
453        }
454    }
455
456    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
457        let mut formatter = formatter.format_struct(Self::TAG)?;
458        for operation in self.operations.iter().flatten() {
459            operation.format(&mut formatter)?;
460        }
461        for object_type in self.object_types.iter().flatten() {
462            object_type.format(&mut formatter)?;
463        }
464        if let Some(vendor_identification) = &self.vendor_identification {
465            formatter.format_text(Self::VENDOR_IDENTIFICATION_TAG, vendor_identification)?;
466        }
467        if let Some(server_information) = &self.server_information {
468            server_information.format(&mut formatter)?;
469        }
470        for extension_information in self.extension_information.iter().flatten() {
471            extension_information.format(&mut formatter)?;
472        }
473        Ok(formatter.finish())
474    }
475
476    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<Self, FastScanError> {
477        let operations =
478            std::iter::from_fn(|| Operation::fast_scan_opt(&mut scanner).transpose()).collect::<Result<Vec<_>, _>>()?;
479        let operations = Some(operations).filter(|a| !a.is_empty());
480        let object_types = std::iter::from_fn(|| ObjectType::fast_scan_opt(&mut scanner).transpose())
481            .collect::<Result<Vec<_>, _>>()?;
482        let object_types = Some(object_types).filter(|a| !a.is_empty());
483        let vendor_identification = scanner
484            .scan_opt_text(Self::VENDOR_IDENTIFICATION_TAG)?
485            .map(ToString::to_string);
486        let server_information = ServerInformation::fast_scan_opt(&mut scanner)?;
487        let extension_information =
488            std::iter::from_fn(|| ExtensionInformation::fast_scan_opt(&mut scanner).transpose())
489                .collect::<Result<Vec<_>, _>>()?;
490        let extension_information = Some(extension_information).filter(|a| !a.is_empty());
491        scanner.finish()?;
492        let this = Self {
493            operations,
494            object_types,
495            vendor_identification,
496            server_information,
497            extension_information,
498        };
499        Ok(this)
500    }
501}
502
503///  See KMIP 1.0 section 4.24 [Query](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232).
504#[derive(Clone, Debug, PartialEq, Eq)]
505pub struct RNGRetrieveResponsePayload(pub Data);
506
507impl_ttlv_serde!(struct RNGRetrieveResponsePayload(data: Data) as 0x42007C);
508
509///  See KMIP 1.0 section 4.24 [Server Information](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232).
510///  The Server Information field in the response is a structure containing vendor-specific fields and/or substructures.
511#[derive(Clone, Debug, PartialEq, Eq, Default)]
512pub struct ServerInformation;
513
514impl ServerInformation {
515    pub const TAG: Tag = Tag::new(0x420088);
516
517    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
518        if scanner.skip_opt_struct(Self::TAG)? {
519            Ok(Some(ServerInformation))
520        } else {
521            Ok(None)
522        }
523    }
524
525    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
526        let formatter = formatter.format_struct(Self::TAG)?;
527        Ok(formatter.finish())
528    }
529}
530
531///  See KMIP 1.1 section 4.26 [Discover Versions](https://docs.oasis-open.org/kmip/spec/v1.1/cs01/kmip-spec-v1.1-cs01.html#_Toc332787652).
532#[derive(Clone, Debug, PartialEq, Eq)]
533pub struct DiscoverVersionsResponsePayload {
534    pub supported_versions: Option<Vec<ProtocolVersion>>,
535}
536
537impl_ttlv_serde!(struct DiscoverVersionsResponsePayload {
538    #[option+vec] supported_versions: ProtocolVersion,
539} as 0x42007C);
540
541///  See KMIP 1.2 section 4.31 [Sign](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558).
542#[derive(Clone, Debug, PartialEq, Eq)]
543pub struct SignResponsePayload {
544    pub unique_identifier: UniqueIdentifier,
545    pub signature_data: Vec<u8>,
546}
547
548impl SignResponsePayload {
549    pub const TAG: Tag = Tag::new(0x42007C);
550    pub const SIGNATURE_DATA_TAG: Tag = Tag::new(0x4200C3);
551
552    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
553        Self::fast_scan_inner(scanner.scan_struct(Self::TAG)?)
554    }
555
556    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
557        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
558            Ok(Some(Self::fast_scan_inner(scanner)?))
559        } else {
560            Ok(None)
561        }
562    }
563
564    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
565        let mut formatter = formatter.format_struct(Self::TAG)?;
566        self.unique_identifier.format(&mut formatter)?;
567        formatter.format_bytes(Self::SIGNATURE_DATA_TAG, &self.signature_data)?;
568        Ok(formatter.finish())
569    }
570
571    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<Self, FastScanError> {
572        let this = Self {
573            unique_identifier: UniqueIdentifier::fast_scan(&mut scanner)?,
574            signature_data: scanner.scan_bytes(Self::SIGNATURE_DATA_TAG)?.into(),
575        };
576        scanner.finish()?;
577        Ok(this)
578    }
579}
580
581///  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).
582#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
583pub struct ProtocolVersion {
584    pub major: i32,
585    pub minor: i32,
586}
587
588impl Default for ProtocolVersion {
589    fn default() -> Self {
590        Self { major: 1, minor: 0 }
591    }
592}
593
594impl ProtocolVersion {
595    pub const TAG: Tag = Tag::new(0x420069);
596    pub const MAJOR_TAG: Tag = Tag::new(0x42006A);
597    pub const MINOR_TAG: Tag = Tag::new(0x42006B);
598
599    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
600        let mut scanner = scanner.scan_struct(Self::TAG)?;
601        let major = scanner.scan_int(Self::MAJOR_TAG)?;
602        let minor = scanner.scan_int(Self::MINOR_TAG)?;
603        scanner.finish()?;
604        Ok(Self { major, minor })
605    }
606
607    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
608        if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
609            let major = scanner.scan_int(Self::MAJOR_TAG)?;
610            let minor = scanner.scan_int(Self::MINOR_TAG)?;
611            scanner.finish()?;
612            Ok(Some(Self { major, minor }))
613        } else {
614            Ok(None)
615        }
616    }
617
618    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
619        let mut formatter = formatter.format_struct(Self::TAG)?;
620        formatter.format_int(Self::MAJOR_TAG, self.major)?;
621        formatter.format_int(Self::MINOR_TAG, self.minor)?;
622        Ok(formatter.finish())
623    }
624}
625
626///  See KMIP 1.0 section 6.9 [Result Status](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581247).
627#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
628#[non_exhaustive]
629#[repr(u32)]
630pub enum ResultStatus {
631    Success,
632    OperationFailed,
633    OperationPending,
634    OperationUndone,
635}
636
637impl_ttlv_serde!(enum ResultStatus as 0x42007F);
638
639impl fmt::Display for ResultStatus {
640    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
641        f.write_str(match self {
642            Self::Success => "Success",
643            Self::OperationFailed => "OperationFailed",
644            Self::OperationPending => "OperationPending",
645            Self::OperationUndone => "OperationUndone",
646        })
647    }
648}
649
650///  See KMIP 1.0 section 6.10 [Result Reason](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581248).
651#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
652#[non_exhaustive]
653#[repr(u32)]
654pub enum ResultReason {
655    ItemNotFound = 1,
656    ResponseTooLarge,
657    AuthenticationNotSuccessful,
658    InvalidMessage,
659    OperationNotSupported,
660    MissingData,
661    InvalidField,
662    FeatureNotSupported,
663    OperationCanceledByRequester,
664    CryptographicFailure,
665    IllegalOperation,
666    PermissionDenied,
667    ObjectArchived,
668    IndexOutOfBounds,
669    ApplicationNamespaceNotSupported,
670    KeyFormatTypeNotSupported,
671    KeyCompressionTypeNotSupported,
672    GeneralFailure,
673}
674
675impl_ttlv_serde!(enum ResultReason as 0x42007E);
676
677impl fmt::Display for ResultReason {
678    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
679        f.write_str(match self {
680            Self::ItemNotFound => "ItemNotFound",
681            Self::ResponseTooLarge => "ResponseTooLarge",
682            Self::AuthenticationNotSuccessful => "AuthenticationNotSuccessful",
683            Self::InvalidMessage => "InvalidMessage",
684            Self::OperationNotSupported => "OperationNotSupported",
685            Self::MissingData => "MissingData",
686            Self::InvalidField => "InvalidField",
687            Self::FeatureNotSupported => "FeatureNotSupported",
688            Self::OperationCanceledByRequester => "OperationCanceledByRequester",
689            Self::CryptographicFailure => "CryptographicFailure",
690            Self::IllegalOperation => "IllegalOperation",
691            Self::PermissionDenied => "PermissionDenied",
692            Self::ObjectArchived => "ObjectArchived",
693            Self::IndexOutOfBounds => "IndexOutOfBounds",
694            Self::ApplicationNamespaceNotSupported => "ApplicationNamespaceNotSupported",
695            Self::KeyFormatTypeNotSupported => "KeyFormatTypeNotSupported",
696            Self::KeyCompressionTypeNotSupported => "KeyCompressionTypeNotSupported",
697            Self::GeneralFailure => "GeneralFailure",
698        })
699    }
700}
701
702///  See KMIP 1.0 section 6.16 [Message Extension](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581254).
703#[derive(Clone, Debug, PartialEq, Eq)]
704pub struct MessageExtension {
705    pub vendor_identification: String,
706    pub criticality_indicator: bool,
707    pub vendor_extension: VendorExtension,
708}
709
710impl MessageExtension {
711    pub const TAG: Tag = Tag::new(0x420051);
712    pub const VI_TAG: Tag = Tag::new(0x42007D);
713    pub const CI_TAG: Tag = Tag::new(0x420026);
714    pub const VE_TAG: Tag = Tag::new(0x42009C);
715
716    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
717        let mut scanner = scanner.scan_struct(Self::TAG)?;
718        let vendor_identification = scanner.scan_text(Self::VI_TAG)?.into();
719        let criticality_indicator = scanner.scan_bool(Self::CI_TAG)?;
720        let vendor_extension = VendorExtension;
721        scanner.skip_struct(Self::VE_TAG)?;
722        scanner.finish()?;
723        Ok(Self {
724            vendor_identification,
725            criticality_indicator,
726            vendor_extension,
727        })
728    }
729
730    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
731        if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
732            let vendor_identification = scanner.scan_text(Self::VI_TAG)?.into();
733            let criticality_indicator = scanner.scan_bool(Self::CI_TAG)?;
734            let vendor_extension = VendorExtension;
735            scanner.skip_struct(Self::VE_TAG)?;
736            scanner.finish()?;
737            Ok(Some(Self {
738                vendor_identification,
739                criticality_indicator,
740                vendor_extension,
741            }))
742        } else {
743            Ok(None)
744        }
745    }
746
747    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
748        let mut formatter = formatter.format_struct(Self::TAG)?;
749        formatter.format_text(Self::VI_TAG, &self.vendor_identification)?;
750        formatter.format_bool(Self::CI_TAG, self.criticality_indicator)?;
751        let field_formatter = formatter.format_struct(Self::VE_TAG)?;
752        field_formatter.finish();
753        Ok(formatter.finish())
754    }
755}
756
757///  See KMIP 1.0 section 6.16 [Message Extension](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581254).
758#[derive(Clone, Debug, PartialEq, Eq, Default)]
759pub struct VendorExtension;
760
761///  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).
762#[derive(Clone, Debug, PartialEq, Eq)]
763pub struct ResponseMessage {
764    pub header: ResponseHeader,
765    pub batch_items: Vec<BatchItem>,
766}
767
768impl_ttlv_serde!(struct ResponseMessage {
769    header: ResponseHeader,
770    #[vec] batch_items: BatchItem,
771} as 0x42007A);
772
773///  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).
774#[derive(Clone, Debug, PartialEq, Eq)]
775pub struct ResponseHeader {
776    pub protocol_version: ProtocolVersion,
777    pub timestamp: i64,
778    pub batch_count: i32,
779    pub nonce: Option<Nonce>,                           // KMIP 1.2
780    pub attestation_type: Option<Vec<AttestationType>>, // KMIP 1.2
781    pub client_correlation_value: Option<String>,       // KMIP 1.4
782    pub server_correlation_value: Option<String>,       // KMIP 1.4
783}
784
785impl ResponseHeader {
786    pub const TAG: Tag = Tag::new(0x42007A);
787    pub const TIMESTAMP_TAG: Tag = Tag::new(0x420092);
788    pub const BATCH_COUNT_TAG: Tag = Tag::new(0x42000D);
789    pub const CLIENT_CORRELATION_VALUE_TAG: Tag = Tag::new(0x420105);
790    pub const SERVER_CORRELATION_VALUE_TAG: Tag = Tag::new(0x420106);
791
792    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
793        let mut scanner = scanner.scan_struct(Self::TAG)?;
794        let protocol_version = ProtocolVersion::fast_scan(&mut scanner)?;
795        let timestamp = scanner.scan_date_time(Self::TIMESTAMP_TAG)?;
796        let batch_count = scanner.scan_int(Self::BATCH_COUNT_TAG)?;
797        let nonce = Nonce::fast_scan_opt(&mut scanner)?;
798        let attestation_type = std::iter::from_fn(|| AttestationType::fast_scan_opt(&mut scanner).transpose())
799            .collect::<Result<Vec<_>, _>>()?;
800        let attestation_type = Some(attestation_type).filter(|a| !a.is_empty());
801        let client_correlation_value = scanner
802            .scan_opt_text(Self::CLIENT_CORRELATION_VALUE_TAG)?
803            .map(ToString::to_string);
804        let server_correlation_value = scanner
805            .scan_opt_text(Self::SERVER_CORRELATION_VALUE_TAG)?
806            .map(ToString::to_string);
807        scanner.finish()?;
808        Ok(Self {
809            protocol_version,
810            timestamp,
811            batch_count,
812            nonce,
813            attestation_type,
814            client_correlation_value,
815            server_correlation_value,
816        })
817    }
818
819    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
820        let mut formatter = formatter.format_struct(Self::TAG)?;
821        self.protocol_version.format(&mut formatter)?;
822        formatter.format_date_time(Self::TIMESTAMP_TAG, self.timestamp)?;
823        formatter.format_int(Self::BATCH_COUNT_TAG, self.batch_count)?;
824        if let Some(nonce) = &self.nonce {
825            nonce.format(&mut formatter)?;
826        }
827        for attestation_type in self.attestation_type.iter().flatten() {
828            attestation_type.format(&mut formatter)?;
829        }
830        if let Some(client_correlation_value) = &self.client_correlation_value {
831            formatter.format_text(Self::CLIENT_CORRELATION_VALUE_TAG, client_correlation_value)?;
832        }
833        if let Some(server_correlation_value) = &self.server_correlation_value {
834            formatter.format_text(Self::SERVER_CORRELATION_VALUE_TAG, server_correlation_value)?;
835        }
836        Ok(formatter.finish())
837    }
838}
839
840///  See KMIP 1.2 sefction 2.1.14 [Nonce](
841/// https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613470).
842#[derive(Clone, Debug, PartialEq, Eq)]
843pub struct Nonce {
844    pub nonce_id: Vec<u8>,
845    pub nonce_value: Vec<u8>,
846}
847
848impl Nonce {
849    pub const TAG: Tag = Tag::new(0x4200C8);
850    pub const NONCE_ID_TAG: Tag = Tag::new(0x4200C9);
851    pub const NONCE_VALUE_TAG: Tag = Tag::new(0x4200CA);
852
853    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
854        if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
855            let nonce_id = scanner.scan_bytes(Self::NONCE_ID_TAG)?.to_vec();
856            let nonce_value = scanner.scan_bytes(Self::NONCE_VALUE_TAG)?.to_vec();
857            scanner.finish()?;
858            Ok(Some(Self { nonce_id, nonce_value }))
859        } else {
860            Ok(None)
861        }
862    }
863
864    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
865        let mut formatter = formatter.format_struct(Self::TAG)?;
866        formatter.format_bytes(Self::NONCE_ID_TAG, &self.nonce_id)?;
867        formatter.format_bytes(Self::NONCE_VALUE_TAG, &self.nonce_value)?;
868        Ok(formatter.finish())
869    }
870}
871
872///  See KMIP 1.2 section 9.1.3.2.36 [Attestation Type](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc395776649).
873#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
874#[non_exhaustive]
875#[repr(u32)]
876pub enum AttestationType {
877    TpmQuote,
878    TcgIntegrityReport,
879    SamlAssertion,
880}
881
882impl_ttlv_serde!(enum AttestationType as 0x4200C7);
883
884impl fmt::Display for AttestationType {
885    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
886        f.write_str(match self {
887            AttestationType::TpmQuote => "TpmQuote",
888            AttestationType::TcgIntegrityReport => "TcgIntegrityReport",
889            AttestationType::SamlAssertion => "SamlAssertion",
890        })
891    }
892}
893
894///  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).
895#[derive(Clone, Debug, PartialEq, Eq)]
896pub struct BatchItem {
897    pub operation: Option<Operation>,
898    pub unique_batch_item_id: Option<UniqueBatchItemID>,
899    pub result_status: ResultStatus,
900    pub result_reason: Option<ResultReason>,
901    pub result_message: Option<String>,
902    // pub asynchronous_correlation_value: Option<??>,
903    pub payload: Option<ResponsePayload>,
904    pub message_extension: Option<MessageExtension>,
905}
906
907impl BatchItem {
908    pub const TAG: Tag = Tag::new(0x42000F);
909    pub const RESULT_MESSAGE_TAG: Tag = Tag::new(0x42007D);
910
911    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
912        Self::fast_scan_inner(scanner.scan_struct(Self::TAG)?)
913    }
914
915    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
916        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
917            Self::fast_scan_inner(scanner).map(Some)
918        } else {
919            Ok(None)
920        }
921    }
922
923    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
924        let mut formatter = formatter.format_struct(Self::TAG)?;
925        if let Some(operation) = self.operation {
926            operation.format(&mut formatter)?;
927        }
928        // if let Some(unique_batch_item_id) = &self.unique_batch_item_id {
929        //     unique_batch_item_id.format(&mut formatter)?;
930        // }
931        self.result_status.format(&mut formatter)?;
932        if let Some(result_reason) = self.result_reason {
933            result_reason.format(&mut formatter)?;
934        }
935        if let Some(result_message) = &self.result_message {
936            formatter.format_text(Self::RESULT_MESSAGE_TAG, result_message)?;
937        }
938        if let Some(payload) = &self.payload {
939            payload.format(&mut formatter)?;
940        }
941        if let Some(message_extension) = &self.message_extension {
942            message_extension.format(&mut formatter)?;
943        }
944        Ok(formatter.finish())
945    }
946
947    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<BatchItem, FastScanError> {
948        let operation = Operation::fast_scan_opt(&mut scanner)?;
949        let unique_batch_item_id = UniqueBatchItemID::fast_scan_opt(&mut scanner)?;
950        let result_status = ResultStatus::fast_scan(&mut scanner)?;
951        let result_reason = ResultReason::fast_scan_opt(&mut scanner)?;
952        let result_message = scanner
953            .scan_opt_text(Self::RESULT_MESSAGE_TAG)?
954            .map(ToString::to_string);
955        let payload = if result_status == ResultStatus::Success
956            && let Some(operation) = operation
957        {
958            ResponsePayload::fast_scan_opt(&mut scanner, operation)?
959        } else {
960            None
961        };
962        let message_extension = MessageExtension::fast_scan_opt(&mut scanner)?;
963        scanner.finish()?;
964        Ok(Self {
965            operation,
966            unique_batch_item_id,
967            result_status,
968            result_reason,
969            result_message,
970            payload,
971            message_extension,
972        })
973    }
974}
975
976///  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).
977#[derive(Clone, Debug, PartialEq, Eq)]
978#[non_exhaustive]
979#[allow(clippy::large_enum_variant)]
980pub enum ResponsePayload {
981    /// See KMIP 1.0 section 4.1 Create.
982    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581209>
983    Create(CreateResponsePayload),
984
985    /// See KMIP 1.0 section 4.2 Create Key Pair.
986    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581210>
987    CreateKeyPair(CreateKeyPairResponsePayload),
988
989    /// See KMIP 1.0 section 4.3 Register.
990    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581211>
991    Register(RegisterResponsePayload),
992
993    /// See KMIP 1.0 section 4.8 Locate.
994    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581216>
995    Locate(LocateResponsePayload),
996
997    /// See KMIP 1.0 section 4.10 Get.
998    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218>
999    Get(GetResponsePayload),
1000
1001    /// See KMIP 1.0 section 4.11 Get Attributes.
1002    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581219>
1003    GetAttributes(GetAttributesResponsePayload),
1004
1005    /// See KMIP 1.0 section 4.12 Get Attribute List.
1006    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581220>
1007    GetAttributeList(GetAttributeListResponsePayload),
1008
1009    /// See KMIP 1.0 section 4.13 Add Attribute.
1010    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581221>
1011    AddAttribute(AddAttributeResponsePayload),
1012
1013    /// See KMIP 1.0 section 4.14 Modify Attribute.
1014    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222>
1015    ModifyAttribute(ModifyAttributeResponsePayload),
1016
1017    /// See KMIP 1.0 section 4.15 Delete Attribute.
1018    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581223>
1019    DeleteAttribute(DeleteAttributeResponsePayload),
1020
1021    /// See KMIP 1.0 section 4.18 Activate.
1022    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226>
1023    Activate(ActivateResponsePayload),
1024
1025    /// See KMIP 1.0 section 4.19 Revoke.
1026    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227>
1027    Revoke(RevokeResponsePayload),
1028
1029    /// See KMIP 1.0 section 4.20 Destroy.
1030    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228>
1031    Destroy(DestroyResponsePayload),
1032
1033    /// See KMIP 1.0 section 4.24 Query.
1034    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232>
1035    Query(QueryResponsePayload),
1036
1037    /// See KMIP 1.1 section 4.26 Discover Versions.
1038    /// See: <https://docs.oasis-open.org/kmip/spec/v1.1/cs01/kmip-spec-v1.1-cs01.html#_Toc332787652>
1039    DiscoverVersions(DiscoverVersionsResponsePayload),
1040
1041    /// See KMIP 1.2 section 4.31 Sign.
1042    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558>
1043    Sign(SignResponsePayload),
1044
1045    /// See KMIP 1.2 section 4.35 RNG Retrieve.
1046    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613562>
1047    RNGRetrieve(RNGRetrieveResponsePayload),
1048    // Note: This set of enum variants is deliberately limited to those that we currently support.
1049}
1050
1051impl ResponsePayload {
1052    pub fn operation(&self) -> Operation {
1053        match self {
1054            ResponsePayload::Create(_) => Operation::Create,
1055            ResponsePayload::CreateKeyPair(_) => Operation::CreateKeyPair,
1056            ResponsePayload::Register(_) => Operation::Register,
1057            ResponsePayload::Locate(_) => Operation::Locate,
1058            ResponsePayload::Get(_) => Operation::Get,
1059            ResponsePayload::GetAttributes(_) => Operation::GetAttributes,
1060            ResponsePayload::GetAttributeList(_) => Operation::GetAttributeList,
1061            ResponsePayload::AddAttribute(_) => Operation::AddAttribute,
1062            ResponsePayload::ModifyAttribute(_) => Operation::ModifyAttribute,
1063            ResponsePayload::DeleteAttribute(_) => Operation::DeleteAttribute,
1064            ResponsePayload::Activate(_) => Operation::Activate,
1065            ResponsePayload::Revoke(_) => Operation::Revoke,
1066            ResponsePayload::Destroy(_) => Operation::Destroy,
1067            ResponsePayload::Query(_) => Operation::Query,
1068            ResponsePayload::DiscoverVersions(_) => Operation::DiscoverVersions,
1069            ResponsePayload::Sign(_) => Operation::Sign,
1070            ResponsePayload::RNGRetrieve(_) => Operation::RNGRetrieve,
1071        }
1072    }
1073
1074    pub fn protocol_version(&self) -> ProtocolVersion {
1075        match self {
1076            ResponsePayload::Create(_)
1077            | ResponsePayload::CreateKeyPair(_)
1078            | ResponsePayload::Register(_)
1079            | ResponsePayload::Locate(_)
1080            | ResponsePayload::Get(_)
1081            | ResponsePayload::GetAttributes(_)
1082            | ResponsePayload::GetAttributeList(_)
1083            | ResponsePayload::AddAttribute(_)
1084            | ResponsePayload::ModifyAttribute(_)
1085            | ResponsePayload::DeleteAttribute(_)
1086            | ResponsePayload::Activate(_)
1087            | ResponsePayload::Revoke(_)
1088            | ResponsePayload::Destroy(_) => ProtocolVersion { major: 1, minor: 0 },
1089            ResponsePayload::DiscoverVersions(_) => ProtocolVersion { major: 1, minor: 1 },
1090            ResponsePayload::Sign(_) | ResponsePayload::RNGRetrieve(_) | ResponsePayload::Query(_) => {
1091                ProtocolVersion { major: 1, minor: 2 }
1092            }
1093        }
1094    }
1095}
1096
1097impl ResponsePayload {
1098    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, operation: Operation) -> Result<Option<Self>, FastScanError> {
1099        let this = match operation {
1100            Operation::Create => CreateResponsePayload::fast_scan_opt(scanner)?.map(Self::Create),
1101            Operation::CreateKeyPair => CreateKeyPairResponsePayload::fast_scan_opt(scanner)?.map(Self::CreateKeyPair),
1102            Operation::Register => RegisterResponsePayload::fast_scan_opt(scanner)?.map(Self::Register),
1103            Operation::Locate => LocateResponsePayload::fast_scan_opt(scanner)?.map(Self::Locate),
1104            Operation::Get => GetResponsePayload::fast_scan_opt(scanner)?.map(Self::Get),
1105            Operation::GetAttributes => GetAttributesResponsePayload::fast_scan_opt(scanner)?.map(Self::GetAttributes),
1106            Operation::GetAttributeList => {
1107                GetAttributeListResponsePayload::fast_scan_opt(scanner)?.map(Self::GetAttributeList)
1108            }
1109            Operation::AddAttribute => AddAttributeResponsePayload::fast_scan_opt(scanner)?.map(Self::AddAttribute),
1110            Operation::ModifyAttribute => {
1111                ModifyAttributeResponsePayload::fast_scan_opt(scanner)?.map(Self::ModifyAttribute)
1112            }
1113            Operation::DeleteAttribute => {
1114                DeleteAttributeResponsePayload::fast_scan_opt(scanner)?.map(Self::DeleteAttribute)
1115            }
1116            Operation::Activate => ActivateResponsePayload::fast_scan_opt(scanner)?.map(Self::Activate),
1117            Operation::Revoke => RevokeResponsePayload::fast_scan_opt(scanner)?.map(Self::Revoke),
1118            Operation::Destroy => DestroyResponsePayload::fast_scan_opt(scanner)?.map(Self::Destroy),
1119            Operation::Query => QueryResponsePayload::fast_scan_opt(scanner)?.map(Self::Query),
1120            Operation::DiscoverVersions => {
1121                DiscoverVersionsResponsePayload::fast_scan_opt(scanner)?.map(Self::DiscoverVersions)
1122            }
1123            Operation::Sign => SignResponsePayload::fast_scan_opt(scanner)?.map(Self::Sign),
1124            Operation::RNGRetrieve => RNGRetrieveResponsePayload::fast_scan_opt(scanner)?.map(Self::RNGRetrieve),
1125            _ => unimplemented!(),
1126        };
1127        Ok(this)
1128    }
1129
1130    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1131        match self {
1132            ResponsePayload::Create(payload) => payload.format(formatter),
1133            ResponsePayload::CreateKeyPair(payload) => payload.format(formatter),
1134            ResponsePayload::Register(payload) => payload.format(formatter),
1135            ResponsePayload::Locate(payload) => payload.format(formatter),
1136            ResponsePayload::Get(payload) => payload.format(formatter),
1137            ResponsePayload::GetAttributes(payload) => payload.format(formatter),
1138            ResponsePayload::GetAttributeList(payload) => payload.format(formatter),
1139            ResponsePayload::AddAttribute(payload) => payload.format(formatter),
1140            ResponsePayload::ModifyAttribute(payload) => payload.format(formatter),
1141            ResponsePayload::DeleteAttribute(payload) => payload.format(formatter),
1142            ResponsePayload::Activate(payload) => payload.format(formatter),
1143            ResponsePayload::Revoke(payload) => payload.format(formatter),
1144            ResponsePayload::Destroy(payload) => payload.format(formatter),
1145            ResponsePayload::Query(payload) => payload.format(formatter),
1146            ResponsePayload::DiscoverVersions(payload) => payload.format(formatter),
1147            ResponsePayload::Sign(payload) => payload.format(formatter),
1148            ResponsePayload::RNGRetrieve(payload) => payload.format(formatter),
1149        }
1150    }
1151}
1152
1153impl std::fmt::Display for ResponsePayload {
1154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1155        match self {
1156            ResponsePayload::Create(_) => f.write_str("Create"),
1157            ResponsePayload::CreateKeyPair(_) => f.write_str("CreateKeyPair"),
1158            ResponsePayload::Register(_) => f.write_str("Register"),
1159            ResponsePayload::Locate(_) => f.write_str("Locate"),
1160            ResponsePayload::Get(_) => f.write_str("Get"),
1161            ResponsePayload::GetAttributes(_) => f.write_str("GetAttributes"),
1162            ResponsePayload::GetAttributeList(_) => f.write_str("GetAttributeList"),
1163            ResponsePayload::AddAttribute(_) => f.write_str("AddAttribute"),
1164            ResponsePayload::ModifyAttribute(_) => f.write_str("ModifyAttribute"),
1165            ResponsePayload::DeleteAttribute(_) => f.write_str("DeleteAttribute"),
1166            ResponsePayload::Activate(_) => f.write_str("Activate"),
1167            ResponsePayload::Revoke(_) => f.write_str("Revoke"),
1168            ResponsePayload::Destroy(_) => f.write_str("Destroy"),
1169            ResponsePayload::Query(_) => f.write_str("Query"),
1170            ResponsePayload::DiscoverVersions(_) => f.write_str("DiscoverVersions"),
1171            ResponsePayload::Sign(_) => f.write_str("Sign"),
1172            ResponsePayload::RNGRetrieve(_) => f.write_str("RNGRetrieve"),
1173        }
1174    }
1175}
1176
1177///  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).
1178#[derive(Clone, Debug, PartialEq, Eq)]
1179pub struct Attribute {
1180    pub name: AttributeName,
1181    pub index: Option<AttributeIndex>,
1182    pub value: AttributeValue,
1183}
1184
1185impl_ttlv_serde!(struct Attribute as 0x420008 {
1186    fast_scan = |scanner| {
1187        let name = AttributeName::fast_scan(&mut scanner)?;
1188        let index = AttributeIndex::fast_scan_opt(&mut scanner)?;
1189        let value = AttributeValue::fast_scan(&mut scanner, &name)?;
1190        Self{name, index, value}
1191    };
1192
1193    format = |&self, formatter| {
1194        self.name.format(&mut formatter)?;
1195        if let Some(index) = &self.index {
1196            index.format(&mut formatter)?;
1197        }
1198        self.value.format(&mut formatter)?;
1199    };
1200});
1201
1202#[derive(Clone, Debug, PartialEq, Eq)]
1203pub struct ExtensionInformation {
1204    pub extension_name: String,
1205    pub extension_tag: Option<i32>,
1206    pub extension_type: Option<ItemType>,
1207}
1208
1209impl ExtensionInformation {
1210    pub const TAG: Tag = Tag::new(0x4200A4);
1211    pub const EXTENSION_NAME_TAG: Tag = Tag::new(0x4200A5);
1212    pub const EXTENSION_TAG_TAG: Tag = Tag::new(0x4200A6);
1213    pub const EXTENSION_TYPE_TAG: Tag = Tag::new(0x4200A7);
1214
1215    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
1216        let scanner = scanner.scan_struct(Self::TAG)?;
1217        Self::fast_scan_inner(scanner)
1218    }
1219
1220    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
1221        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
1222            Ok(Some(Self::fast_scan_inner(scanner)?))
1223        } else {
1224            Ok(None)
1225        }
1226    }
1227
1228    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<Self, FastScanError> {
1229        let extension_name = scanner.scan_text(Self::EXTENSION_NAME_TAG)?.to_string();
1230        let extension_tag = scanner.scan_opt_int(Self::EXTENSION_TAG_TAG)?;
1231        let extension_type = ItemType::fast_scan_opt(&mut scanner)?;
1232        scanner.finish()?;
1233        Ok(Self {
1234            extension_name,
1235            extension_tag,
1236            extension_type,
1237        })
1238    }
1239
1240    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1241        let mut formatter = formatter.format_struct(Self::TAG)?;
1242        formatter.format_text(Self::EXTENSION_NAME_TAG, &self.extension_name)?;
1243        if let Some(v) = self.extension_tag {
1244            formatter.format_int(Self::EXTENSION_TAG_TAG, v)?;
1245        }
1246        if let Some(v) = self.extension_type {
1247            v.format(&mut formatter)?;
1248        }
1249        Ok(formatter.finish())
1250    }
1251}
1252
1253/// Item Type as a KMIP Integer (u32).
1254///
1255/// Note: We don't encode it as a u8 which is how Item Type is defined in
1256/// [KMIP 1.1 section 9.1.1.2](https://docs.oasis-open.org/kmip/spec/v1.1/os/kmip-spec-v1.1-os.html#_toc8562)
1257/// because this is for use with
1258/// [KMIP 1.1 section 2.1.9 Extension Information](https://docs.oasis-open.org/kmip/spec/v1.1/os/kmip-spec-v1.1-os.html#_Toc333494476)
1259/// which defines it as a KMIP Integer (i32).
1260//
1261// Note: We cannot use impl_ttlv_serde!(int ItemType as 0x4200A7) as that
1262// expects the TTLV to have initial Type of Enum rather than Integer and thus
1263// parsing fails.
1264#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1265#[non_exhaustive]
1266#[repr(i32)]
1267pub enum ItemType {
1268    Structure,
1269    Integer,
1270    LongInteger,
1271    BigInteger,
1272    Enumeration,
1273    Boolean,
1274    TextString,
1275    ByteString,
1276    DateTime,
1277    Interval,
1278}
1279
1280impl ItemType {
1281    pub const TAG: Tag = Tag::new(0x4200A7);
1282
1283    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
1284        Self::fast_scan_with(scanner, Self::TAG)
1285    }
1286
1287    pub fn fast_scan_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Self, FastScanError> {
1288        Self::from_ordinal(scanner.scan_int(tag)?).ok_or_else(FastScanError::assert)
1289    }
1290
1291    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
1292        Self::fast_scan_opt_with(scanner, Self::TAG)
1293    }
1294
1295    pub fn fast_scan_opt_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Option<Self>, FastScanError> {
1296        scanner
1297            .scan_opt_int(tag)?
1298            .map(|d| Self::from_ordinal(d).ok_or_else(FastScanError::assert))
1299            .transpose()
1300    }
1301
1302    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1303        self.format_with(formatter, Self::TAG)
1304    }
1305
1306    pub fn format_with(&self, formatter: &mut Formatter<'_>, tag: Tag) -> FormatResult {
1307        formatter.format_int(tag, self.ordinal())
1308    }
1309}