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 std::fmt::Display for ProtocolVersion {
595    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
596        write!(f, "{}.{}", self.major, self.minor)
597    }
598}
599
600impl ProtocolVersion {
601    pub const TAG: Tag = Tag::new(0x420069);
602    pub const MAJOR_TAG: Tag = Tag::new(0x42006A);
603    pub const MINOR_TAG: Tag = Tag::new(0x42006B);
604
605    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
606        let mut scanner = scanner.scan_struct(Self::TAG)?;
607        let major = scanner.scan_int(Self::MAJOR_TAG)?;
608        let minor = scanner.scan_int(Self::MINOR_TAG)?;
609        scanner.finish()?;
610        Ok(Self { major, minor })
611    }
612
613    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
614        if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
615            let major = scanner.scan_int(Self::MAJOR_TAG)?;
616            let minor = scanner.scan_int(Self::MINOR_TAG)?;
617            scanner.finish()?;
618            Ok(Some(Self { major, minor }))
619        } else {
620            Ok(None)
621        }
622    }
623
624    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
625        let mut formatter = formatter.format_struct(Self::TAG)?;
626        formatter.format_int(Self::MAJOR_TAG, self.major)?;
627        formatter.format_int(Self::MINOR_TAG, self.minor)?;
628        Ok(formatter.finish())
629    }
630}
631
632///  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).
633#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
634#[non_exhaustive]
635#[repr(u32)]
636pub enum ResultStatus {
637    Success,
638    OperationFailed,
639    OperationPending,
640    OperationUndone,
641}
642
643impl_ttlv_serde!(enum ResultStatus as 0x42007F);
644
645impl fmt::Display for ResultStatus {
646    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
647        write!(f, "{self:?}")
648    }
649}
650
651///  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).
652#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
653#[non_exhaustive]
654#[repr(u32)]
655pub enum ResultReason {
656    ItemNotFound = 0x00000001,
657    ResponseTooLarge,
658    AuthenticationNotSuccessful,
659    InvalidMessage,
660    OperationNotSupported,
661    MissingData,
662    InvalidField,
663    FeatureNotSupported,
664    OperationCanceledByRequester,
665    CryptographicFailure,
666    IllegalOperation,
667    PermissionDenied,
668    ObjectArchived,
669    IndexOutOfBounds,
670    ApplicationNamespaceNotSupported,
671    KeyFormatTypeNotSupported,
672    KeyCompressionTypeNotSupported,
673
674    // KMIP 1.1
675    EncodingOptionError,
676
677    // KMIP 1.2
678    KeyValueNotPresent,
679    AttestationRequired,
680    AttestationFailed,
681
682    // KMIP 1.0
683    GeneralFailure = 0x00000100,
684}
685
686impl_ttlv_serde!(enum ResultReason as 0x42007E);
687
688impl fmt::Display for ResultReason {
689    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
690        write!(f, "{self:?}")
691    }
692}
693
694///  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).
695#[derive(Clone, Debug, PartialEq, Eq)]
696pub struct MessageExtension {
697    pub vendor_identification: String,
698    pub criticality_indicator: bool,
699    pub vendor_extension: VendorExtension,
700}
701
702impl MessageExtension {
703    pub const TAG: Tag = Tag::new(0x420051);
704    pub const VI_TAG: Tag = Tag::new(0x42007D);
705    pub const CI_TAG: Tag = Tag::new(0x420026);
706    pub const VE_TAG: Tag = Tag::new(0x42009C);
707
708    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
709        let mut scanner = scanner.scan_struct(Self::TAG)?;
710        let vendor_identification = scanner.scan_text(Self::VI_TAG)?.into();
711        let criticality_indicator = scanner.scan_bool(Self::CI_TAG)?;
712        let vendor_extension = VendorExtension;
713        scanner.skip_struct(Self::VE_TAG)?;
714        scanner.finish()?;
715        Ok(Self {
716            vendor_identification,
717            criticality_indicator,
718            vendor_extension,
719        })
720    }
721
722    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
723        if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
724            let vendor_identification = scanner.scan_text(Self::VI_TAG)?.into();
725            let criticality_indicator = scanner.scan_bool(Self::CI_TAG)?;
726            let vendor_extension = VendorExtension;
727            scanner.skip_struct(Self::VE_TAG)?;
728            scanner.finish()?;
729            Ok(Some(Self {
730                vendor_identification,
731                criticality_indicator,
732                vendor_extension,
733            }))
734        } else {
735            Ok(None)
736        }
737    }
738
739    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
740        let mut formatter = formatter.format_struct(Self::TAG)?;
741        formatter.format_text(Self::VI_TAG, &self.vendor_identification)?;
742        formatter.format_bool(Self::CI_TAG, self.criticality_indicator)?;
743        let field_formatter = formatter.format_struct(Self::VE_TAG)?;
744        field_formatter.finish();
745        Ok(formatter.finish())
746    }
747}
748
749///  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).
750#[derive(Clone, Debug, PartialEq, Eq, Default)]
751pub struct VendorExtension;
752
753///  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).
754#[derive(Clone, Debug, PartialEq, Eq)]
755pub struct ResponseMessage {
756    pub header: ResponseHeader,
757    pub batch_items: Vec<BatchItem>,
758}
759
760impl_ttlv_serde!(struct ResponseMessage {
761    header: ResponseHeader,
762    #[vec] batch_items: BatchItem,
763} as 0x42007A);
764
765///  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).
766#[derive(Clone, Debug, PartialEq, Eq)]
767pub struct ResponseHeader {
768    pub protocol_version: ProtocolVersion,
769    pub timestamp: i64,
770    pub batch_count: i32,
771    pub nonce: Option<Nonce>,                           // KMIP 1.2
772    pub attestation_type: Option<Vec<AttestationType>>, // KMIP 1.2
773    pub client_correlation_value: Option<String>,       // KMIP 1.4
774    pub server_correlation_value: Option<String>,       // KMIP 1.4
775}
776
777impl ResponseHeader {
778    pub const TAG: Tag = Tag::new(0x42007A);
779    pub const TIMESTAMP_TAG: Tag = Tag::new(0x420092);
780    pub const BATCH_COUNT_TAG: Tag = Tag::new(0x42000D);
781    pub const CLIENT_CORRELATION_VALUE_TAG: Tag = Tag::new(0x420105);
782    pub const SERVER_CORRELATION_VALUE_TAG: Tag = Tag::new(0x420106);
783
784    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
785        let mut scanner = scanner.scan_struct(Self::TAG)?;
786        let protocol_version = ProtocolVersion::fast_scan(&mut scanner)?;
787        let timestamp = scanner.scan_date_time(Self::TIMESTAMP_TAG)?;
788        let batch_count = scanner.scan_int(Self::BATCH_COUNT_TAG)?;
789        let nonce = Nonce::fast_scan_opt(&mut scanner)?;
790        let attestation_type = std::iter::from_fn(|| AttestationType::fast_scan_opt(&mut scanner).transpose())
791            .collect::<Result<Vec<_>, _>>()?;
792        let attestation_type = Some(attestation_type).filter(|a| !a.is_empty());
793        let client_correlation_value = scanner
794            .scan_opt_text(Self::CLIENT_CORRELATION_VALUE_TAG)?
795            .map(ToString::to_string);
796        let server_correlation_value = scanner
797            .scan_opt_text(Self::SERVER_CORRELATION_VALUE_TAG)?
798            .map(ToString::to_string);
799        scanner.finish()?;
800        Ok(Self {
801            protocol_version,
802            timestamp,
803            batch_count,
804            nonce,
805            attestation_type,
806            client_correlation_value,
807            server_correlation_value,
808        })
809    }
810
811    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
812        let mut formatter = formatter.format_struct(Self::TAG)?;
813        self.protocol_version.format(&mut formatter)?;
814        formatter.format_date_time(Self::TIMESTAMP_TAG, self.timestamp)?;
815        formatter.format_int(Self::BATCH_COUNT_TAG, self.batch_count)?;
816        if let Some(nonce) = &self.nonce {
817            nonce.format(&mut formatter)?;
818        }
819        for attestation_type in self.attestation_type.iter().flatten() {
820            attestation_type.format(&mut formatter)?;
821        }
822        if let Some(client_correlation_value) = &self.client_correlation_value {
823            formatter.format_text(Self::CLIENT_CORRELATION_VALUE_TAG, client_correlation_value)?;
824        }
825        if let Some(server_correlation_value) = &self.server_correlation_value {
826            formatter.format_text(Self::SERVER_CORRELATION_VALUE_TAG, server_correlation_value)?;
827        }
828        Ok(formatter.finish())
829    }
830}
831
832///  See KMIP 1.2 sefction 2.1.14 [Nonce](
833/// https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613470).
834#[derive(Clone, Debug, PartialEq, Eq)]
835pub struct Nonce {
836    pub nonce_id: Vec<u8>,
837    pub nonce_value: Vec<u8>,
838}
839
840impl Nonce {
841    pub const TAG: Tag = Tag::new(0x4200C8);
842    pub const NONCE_ID_TAG: Tag = Tag::new(0x4200C9);
843    pub const NONCE_VALUE_TAG: Tag = Tag::new(0x4200CA);
844
845    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
846        if let Some(mut scanner) = scanner.scan_opt_struct(Self::TAG)? {
847            let nonce_id = scanner.scan_bytes(Self::NONCE_ID_TAG)?.to_vec();
848            let nonce_value = scanner.scan_bytes(Self::NONCE_VALUE_TAG)?.to_vec();
849            scanner.finish()?;
850            Ok(Some(Self { nonce_id, nonce_value }))
851        } else {
852            Ok(None)
853        }
854    }
855
856    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
857        let mut formatter = formatter.format_struct(Self::TAG)?;
858        formatter.format_bytes(Self::NONCE_ID_TAG, &self.nonce_id)?;
859        formatter.format_bytes(Self::NONCE_VALUE_TAG, &self.nonce_value)?;
860        Ok(formatter.finish())
861    }
862}
863
864///  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).
865#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
866#[non_exhaustive]
867#[repr(u32)]
868pub enum AttestationType {
869    TpmQuote,
870    TcgIntegrityReport,
871    SamlAssertion,
872}
873
874impl_ttlv_serde!(enum AttestationType as 0x4200C7);
875
876impl fmt::Display for AttestationType {
877    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
878        write!(f, "{self:?}")
879    }
880}
881
882///  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).
883#[derive(Clone, Debug, PartialEq, Eq)]
884pub struct BatchItem {
885    pub operation: Option<Operation>,
886    pub unique_batch_item_id: Option<UniqueBatchItemID>,
887    pub result_status: ResultStatus,
888    pub result_reason: Option<ResultReason>,
889    pub result_message: Option<String>,
890    // pub asynchronous_correlation_value: Option<??>,
891    pub payload: Option<ResponsePayload>,
892    pub message_extension: Option<MessageExtension>,
893}
894
895impl BatchItem {
896    pub const TAG: Tag = Tag::new(0x42000F);
897    pub const RESULT_MESSAGE_TAG: Tag = Tag::new(0x42007D);
898
899    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
900        Self::fast_scan_inner(scanner.scan_struct(Self::TAG)?)
901    }
902
903    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
904        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
905            Self::fast_scan_inner(scanner).map(Some)
906        } else {
907            Ok(None)
908        }
909    }
910
911    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
912        let mut formatter = formatter.format_struct(Self::TAG)?;
913        if let Some(operation) = self.operation {
914            operation.format(&mut formatter)?;
915        }
916        // if let Some(unique_batch_item_id) = &self.unique_batch_item_id {
917        //     unique_batch_item_id.format(&mut formatter)?;
918        // }
919        self.result_status.format(&mut formatter)?;
920        if let Some(result_reason) = self.result_reason {
921            result_reason.format(&mut formatter)?;
922        }
923        if let Some(result_message) = &self.result_message {
924            formatter.format_text(Self::RESULT_MESSAGE_TAG, result_message)?;
925        }
926        if let Some(payload) = &self.payload {
927            payload.format(&mut formatter)?;
928        }
929        if let Some(message_extension) = &self.message_extension {
930            message_extension.format(&mut formatter)?;
931        }
932        Ok(formatter.finish())
933    }
934
935    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<BatchItem, FastScanError> {
936        let operation = Operation::fast_scan_opt(&mut scanner)?;
937        let unique_batch_item_id = UniqueBatchItemID::fast_scan_opt(&mut scanner)?;
938        let result_status = ResultStatus::fast_scan(&mut scanner)?;
939        let result_reason = ResultReason::fast_scan_opt(&mut scanner)?;
940        let result_message = scanner
941            .scan_opt_text(Self::RESULT_MESSAGE_TAG)?
942            .map(ToString::to_string);
943        let payload = if result_status == ResultStatus::Success
944            && let Some(operation) = operation
945        {
946            ResponsePayload::fast_scan_opt(&mut scanner, operation)?
947        } else {
948            None
949        };
950        let message_extension = MessageExtension::fast_scan_opt(&mut scanner)?;
951        scanner.finish()?;
952        Ok(Self {
953            operation,
954            unique_batch_item_id,
955            result_status,
956            result_reason,
957            result_message,
958            payload,
959            message_extension,
960        })
961    }
962}
963
964///  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).
965#[derive(Clone, Debug, PartialEq, Eq)]
966#[non_exhaustive]
967#[allow(clippy::large_enum_variant)]
968pub enum ResponsePayload {
969    /// See KMIP 1.0 section 4.1 Create.
970    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581209>
971    Create(CreateResponsePayload),
972
973    /// See KMIP 1.0 section 4.2 Create Key Pair.
974    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581210>
975    CreateKeyPair(CreateKeyPairResponsePayload),
976
977    /// See KMIP 1.0 section 4.3 Register.
978    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581211>
979    Register(RegisterResponsePayload),
980
981    /// See KMIP 1.0 section 4.8 Locate.
982    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581216>
983    Locate(LocateResponsePayload),
984
985    /// See KMIP 1.0 section 4.10 Get.
986    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218>
987    Get(GetResponsePayload),
988
989    /// See KMIP 1.0 section 4.11 Get Attributes.
990    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581219>
991    GetAttributes(GetAttributesResponsePayload),
992
993    /// See KMIP 1.0 section 4.12 Get Attribute List.
994    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581220>
995    GetAttributeList(GetAttributeListResponsePayload),
996
997    /// See KMIP 1.0 section 4.13 Add Attribute.
998    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581221>
999    AddAttribute(AddAttributeResponsePayload),
1000
1001    /// See KMIP 1.0 section 4.14 Modify Attribute.
1002    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222>
1003    ModifyAttribute(ModifyAttributeResponsePayload),
1004
1005    /// See KMIP 1.0 section 4.15 Delete Attribute.
1006    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581223>
1007    DeleteAttribute(DeleteAttributeResponsePayload),
1008
1009    /// See KMIP 1.0 section 4.18 Activate.
1010    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226>
1011    Activate(ActivateResponsePayload),
1012
1013    /// See KMIP 1.0 section 4.19 Revoke.
1014    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227>
1015    Revoke(RevokeResponsePayload),
1016
1017    /// See KMIP 1.0 section 4.20 Destroy.
1018    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228>
1019    Destroy(DestroyResponsePayload),
1020
1021    /// See KMIP 1.0 section 4.24 Query.
1022    /// See: <https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232>
1023    Query(QueryResponsePayload),
1024
1025    /// See KMIP 1.1 section 4.26 Discover Versions.
1026    /// See: <https://docs.oasis-open.org/kmip/spec/v1.1/cs01/kmip-spec-v1.1-cs01.html#_Toc332787652>
1027    DiscoverVersions(DiscoverVersionsResponsePayload),
1028
1029    /// See KMIP 1.2 section 4.31 Sign.
1030    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558>
1031    Sign(SignResponsePayload),
1032
1033    /// See KMIP 1.2 section 4.35 RNG Retrieve.
1034    /// See: <https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613562>
1035    RNGRetrieve(RNGRetrieveResponsePayload),
1036    // Note: This set of enum variants is deliberately limited to those that we currently support.
1037}
1038
1039impl ResponsePayload {
1040    pub fn operation(&self) -> Operation {
1041        match self {
1042            ResponsePayload::Create(_) => Operation::Create,
1043            ResponsePayload::CreateKeyPair(_) => Operation::CreateKeyPair,
1044            ResponsePayload::Register(_) => Operation::Register,
1045            ResponsePayload::Locate(_) => Operation::Locate,
1046            ResponsePayload::Get(_) => Operation::Get,
1047            ResponsePayload::GetAttributes(_) => Operation::GetAttributes,
1048            ResponsePayload::GetAttributeList(_) => Operation::GetAttributeList,
1049            ResponsePayload::AddAttribute(_) => Operation::AddAttribute,
1050            ResponsePayload::ModifyAttribute(_) => Operation::ModifyAttribute,
1051            ResponsePayload::DeleteAttribute(_) => Operation::DeleteAttribute,
1052            ResponsePayload::Activate(_) => Operation::Activate,
1053            ResponsePayload::Revoke(_) => Operation::Revoke,
1054            ResponsePayload::Destroy(_) => Operation::Destroy,
1055            ResponsePayload::Query(_) => Operation::Query,
1056            ResponsePayload::DiscoverVersions(_) => Operation::DiscoverVersions,
1057            ResponsePayload::Sign(_) => Operation::Sign,
1058            ResponsePayload::RNGRetrieve(_) => Operation::RNGRetrieve,
1059        }
1060    }
1061
1062    pub fn protocol_version(&self) -> ProtocolVersion {
1063        match self {
1064            ResponsePayload::Create(_)
1065            | ResponsePayload::CreateKeyPair(_)
1066            | ResponsePayload::Register(_)
1067            | ResponsePayload::Locate(_)
1068            | ResponsePayload::Get(_)
1069            | ResponsePayload::GetAttributes(_)
1070            | ResponsePayload::GetAttributeList(_)
1071            | ResponsePayload::AddAttribute(_)
1072            | ResponsePayload::ModifyAttribute(_)
1073            | ResponsePayload::DeleteAttribute(_)
1074            | ResponsePayload::Activate(_)
1075            | ResponsePayload::Revoke(_)
1076            | ResponsePayload::Destroy(_) => ProtocolVersion { major: 1, minor: 0 },
1077            ResponsePayload::DiscoverVersions(_) => ProtocolVersion { major: 1, minor: 1 },
1078            ResponsePayload::Sign(_) | ResponsePayload::RNGRetrieve(_) | ResponsePayload::Query(_) => {
1079                ProtocolVersion { major: 1, minor: 2 }
1080            }
1081        }
1082    }
1083}
1084
1085impl ResponsePayload {
1086    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>, operation: Operation) -> Result<Option<Self>, FastScanError> {
1087        let this = match operation {
1088            Operation::Create => CreateResponsePayload::fast_scan_opt(scanner)?.map(Self::Create),
1089            Operation::CreateKeyPair => CreateKeyPairResponsePayload::fast_scan_opt(scanner)?.map(Self::CreateKeyPair),
1090            Operation::Register => RegisterResponsePayload::fast_scan_opt(scanner)?.map(Self::Register),
1091            Operation::Locate => LocateResponsePayload::fast_scan_opt(scanner)?.map(Self::Locate),
1092            Operation::Get => GetResponsePayload::fast_scan_opt(scanner)?.map(Self::Get),
1093            Operation::GetAttributes => GetAttributesResponsePayload::fast_scan_opt(scanner)?.map(Self::GetAttributes),
1094            Operation::GetAttributeList => {
1095                GetAttributeListResponsePayload::fast_scan_opt(scanner)?.map(Self::GetAttributeList)
1096            }
1097            Operation::AddAttribute => AddAttributeResponsePayload::fast_scan_opt(scanner)?.map(Self::AddAttribute),
1098            Operation::ModifyAttribute => {
1099                ModifyAttributeResponsePayload::fast_scan_opt(scanner)?.map(Self::ModifyAttribute)
1100            }
1101            Operation::DeleteAttribute => {
1102                DeleteAttributeResponsePayload::fast_scan_opt(scanner)?.map(Self::DeleteAttribute)
1103            }
1104            Operation::Activate => ActivateResponsePayload::fast_scan_opt(scanner)?.map(Self::Activate),
1105            Operation::Revoke => RevokeResponsePayload::fast_scan_opt(scanner)?.map(Self::Revoke),
1106            Operation::Destroy => DestroyResponsePayload::fast_scan_opt(scanner)?.map(Self::Destroy),
1107            Operation::Query => QueryResponsePayload::fast_scan_opt(scanner)?.map(Self::Query),
1108            Operation::DiscoverVersions => {
1109                DiscoverVersionsResponsePayload::fast_scan_opt(scanner)?.map(Self::DiscoverVersions)
1110            }
1111            Operation::Sign => SignResponsePayload::fast_scan_opt(scanner)?.map(Self::Sign),
1112            Operation::RNGRetrieve => RNGRetrieveResponsePayload::fast_scan_opt(scanner)?.map(Self::RNGRetrieve),
1113            _ => unimplemented!(),
1114        };
1115        Ok(this)
1116    }
1117
1118    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1119        match self {
1120            ResponsePayload::Create(payload) => payload.format(formatter),
1121            ResponsePayload::CreateKeyPair(payload) => payload.format(formatter),
1122            ResponsePayload::Register(payload) => payload.format(formatter),
1123            ResponsePayload::Locate(payload) => payload.format(formatter),
1124            ResponsePayload::Get(payload) => payload.format(formatter),
1125            ResponsePayload::GetAttributes(payload) => payload.format(formatter),
1126            ResponsePayload::GetAttributeList(payload) => payload.format(formatter),
1127            ResponsePayload::AddAttribute(payload) => payload.format(formatter),
1128            ResponsePayload::ModifyAttribute(payload) => payload.format(formatter),
1129            ResponsePayload::DeleteAttribute(payload) => payload.format(formatter),
1130            ResponsePayload::Activate(payload) => payload.format(formatter),
1131            ResponsePayload::Revoke(payload) => payload.format(formatter),
1132            ResponsePayload::Destroy(payload) => payload.format(formatter),
1133            ResponsePayload::Query(payload) => payload.format(formatter),
1134            ResponsePayload::DiscoverVersions(payload) => payload.format(formatter),
1135            ResponsePayload::Sign(payload) => payload.format(formatter),
1136            ResponsePayload::RNGRetrieve(payload) => payload.format(formatter),
1137        }
1138    }
1139}
1140
1141impl std::fmt::Display for ResponsePayload {
1142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1143        match self {
1144            ResponsePayload::Create(_) => f.write_str("Create"),
1145            ResponsePayload::CreateKeyPair(_) => f.write_str("CreateKeyPair"),
1146            ResponsePayload::Register(_) => f.write_str("Register"),
1147            ResponsePayload::Locate(_) => f.write_str("Locate"),
1148            ResponsePayload::Get(_) => f.write_str("Get"),
1149            ResponsePayload::GetAttributes(_) => f.write_str("GetAttributes"),
1150            ResponsePayload::GetAttributeList(_) => f.write_str("GetAttributeList"),
1151            ResponsePayload::AddAttribute(_) => f.write_str("AddAttribute"),
1152            ResponsePayload::ModifyAttribute(_) => f.write_str("ModifyAttribute"),
1153            ResponsePayload::DeleteAttribute(_) => f.write_str("DeleteAttribute"),
1154            ResponsePayload::Activate(_) => f.write_str("Activate"),
1155            ResponsePayload::Revoke(_) => f.write_str("Revoke"),
1156            ResponsePayload::Destroy(_) => f.write_str("Destroy"),
1157            ResponsePayload::Query(_) => f.write_str("Query"),
1158            ResponsePayload::DiscoverVersions(_) => f.write_str("DiscoverVersions"),
1159            ResponsePayload::Sign(_) => f.write_str("Sign"),
1160            ResponsePayload::RNGRetrieve(_) => f.write_str("RNGRetrieve"),
1161        }
1162    }
1163}
1164
1165///  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).
1166#[derive(Clone, Debug, PartialEq, Eq)]
1167pub struct Attribute {
1168    pub name: AttributeName,
1169    pub index: Option<AttributeIndex>,
1170    pub value: AttributeValue,
1171}
1172
1173impl_ttlv_serde!(struct Attribute as 0x420008 {
1174    fast_scan = |scanner| {
1175        let name = AttributeName::fast_scan(&mut scanner)?;
1176        let index = AttributeIndex::fast_scan_opt(&mut scanner)?;
1177        let value = AttributeValue::fast_scan(&mut scanner, &name)?;
1178        Self{name, index, value}
1179    };
1180
1181    format = |&self, formatter| {
1182        self.name.format(&mut formatter)?;
1183        if let Some(index) = &self.index {
1184            index.format(&mut formatter)?;
1185        }
1186        self.value.format(&mut formatter)?;
1187    };
1188});
1189
1190#[derive(Clone, Debug, PartialEq, Eq)]
1191pub struct ExtensionInformation {
1192    pub extension_name: String,
1193    pub extension_tag: Option<i32>,
1194    pub extension_type: Option<ItemType>,
1195}
1196
1197impl ExtensionInformation {
1198    pub const TAG: Tag = Tag::new(0x4200A4);
1199    pub const EXTENSION_NAME_TAG: Tag = Tag::new(0x4200A5);
1200    pub const EXTENSION_TAG_TAG: Tag = Tag::new(0x4200A6);
1201    pub const EXTENSION_TYPE_TAG: Tag = Tag::new(0x4200A7);
1202
1203    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
1204        let scanner = scanner.scan_struct(Self::TAG)?;
1205        Self::fast_scan_inner(scanner)
1206    }
1207
1208    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
1209        if let Some(scanner) = scanner.scan_opt_struct(Self::TAG)? {
1210            Ok(Some(Self::fast_scan_inner(scanner)?))
1211        } else {
1212            Ok(None)
1213        }
1214    }
1215
1216    fn fast_scan_inner(mut scanner: FastScanner<'_>) -> Result<Self, FastScanError> {
1217        let extension_name = scanner.scan_text(Self::EXTENSION_NAME_TAG)?.to_string();
1218        let extension_tag = scanner.scan_opt_int(Self::EXTENSION_TAG_TAG)?;
1219        let extension_type = ItemType::fast_scan_opt(&mut scanner)?;
1220        scanner.finish()?;
1221        Ok(Self {
1222            extension_name,
1223            extension_tag,
1224            extension_type,
1225        })
1226    }
1227
1228    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1229        let mut formatter = formatter.format_struct(Self::TAG)?;
1230        formatter.format_text(Self::EXTENSION_NAME_TAG, &self.extension_name)?;
1231        if let Some(v) = self.extension_tag {
1232            formatter.format_int(Self::EXTENSION_TAG_TAG, v)?;
1233        }
1234        if let Some(v) = self.extension_type {
1235            v.format(&mut formatter)?;
1236        }
1237        Ok(formatter.finish())
1238    }
1239}
1240
1241/// Item Type as a KMIP Integer (u32).
1242///
1243/// Note: We don't encode it as a u8 which is how Item Type is defined in
1244/// [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)
1245/// because this is for use with
1246/// [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)
1247/// which defines it as a KMIP Integer (i32).
1248//
1249// Note: We cannot use impl_ttlv_serde!(int ItemType as 0x4200A7) as that
1250// expects the TTLV to have initial Type of Enum rather than Integer and thus
1251// parsing fails.
1252#[derive(Clone, Copy, Debug, PartialEq, Eq, Ordinalize)]
1253#[non_exhaustive]
1254#[repr(i32)]
1255pub enum ItemType {
1256    Structure,
1257    Integer,
1258    LongInteger,
1259    BigInteger,
1260    Enumeration,
1261    Boolean,
1262    TextString,
1263    ByteString,
1264    DateTime,
1265    Interval,
1266}
1267
1268impl ItemType {
1269    pub const TAG: Tag = Tag::new(0x4200A7);
1270
1271    pub fn fast_scan(scanner: &mut FastScanner<'_>) -> Result<Self, FastScanError> {
1272        Self::fast_scan_with(scanner, Self::TAG)
1273    }
1274
1275    pub fn fast_scan_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Self, FastScanError> {
1276        Self::from_ordinal(scanner.scan_int(tag)?).ok_or_else(FastScanError::assert)
1277    }
1278
1279    pub fn fast_scan_opt(scanner: &mut FastScanner<'_>) -> Result<Option<Self>, FastScanError> {
1280        Self::fast_scan_opt_with(scanner, Self::TAG)
1281    }
1282
1283    pub fn fast_scan_opt_with(scanner: &mut FastScanner<'_>, tag: Tag) -> Result<Option<Self>, FastScanError> {
1284        scanner
1285            .scan_opt_int(tag)?
1286            .map(|d| Self::from_ordinal(d).ok_or_else(FastScanError::assert))
1287            .transpose()
1288    }
1289
1290    pub fn format(&self, formatter: &mut Formatter<'_>) -> FormatResult {
1291        self.format_with(formatter, Self::TAG)
1292    }
1293
1294    pub fn format_with(&self, formatter: &mut Formatter<'_>, tag: Tag) -> FormatResult {
1295        formatter.format_int(tag, self.ordinal())
1296    }
1297}