Skip to main content

kmip_protocol/net/client/
mod.rs

1//! A high level KMIP "operation" oriented client interface for request/response construction & (de)serialization.
2pub mod builder;
3pub mod tests;
4pub mod util;
5
6use std::{
7    mem::MaybeUninit,
8    ops::DerefMut,
9    sync::{
10        Arc,
11        atomic::{AtomicUsize, Ordering},
12    },
13};
14
15#[cfg(not(feature = "tokio"))]
16use std::sync::Mutex;
17
18#[cfg(feature = "tokio")]
19use tokio::sync::Mutex;
20
21use tracing::trace;
22
23use crate::{
24    net::{
25        batch_items_to_request,
26        common::{
27            error::{NetError, NetResult},
28            io::read_message_from_stream,
29        },
30        payload_to_request,
31    },
32    types::{
33        common::*,
34        request::{
35            self, Authentication, BatchItem, CommonTemplateAttribute, KeyWrappingSpecification, MaximumResponseSize,
36            PrivateKeyTemplateAttribute, PublicKeyTemplateAttribute, QueryFunction, RequestMessage, RequestPayload,
37            RevocationReason,
38        },
39        response::{
40            self, CreateKeyPairResponsePayload, GetResponsePayload, QueryResponsePayload, ResponseMessage,
41            ResponsePayload, ResultReason, ResultStatus,
42        },
43        traits::*,
44    },
45};
46
47/// A client for serializing KMIP requests and deserializing KMIP responses
48/// to/from an established read/write stream.
49///
50/// Use the [crate::net::ClientBuilder] to build a [Client] instance to work
51/// with.
52#[derive(Debug)]
53pub struct Client<T: ReadWrite> {
54    auth: Option<Authentication>,
55    max_message_size: i32,
56    stream: Arc<Mutex<T>>,
57    read_buf: Vec<u8>,
58    write_buf: Vec<MaybeUninit<u8>>,
59    connection_error_count: Arc<AtomicUsize>,
60    cached_query_response_payload: Option<QueryResponsePayload>,
61}
62
63//--- High level client interface
64
65impl<T: ReadWrite> Client<T> {
66    /// Serialize a KMIP 1.0 [Query](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581232)
67    /// request.
68    ///
69    /// See also: [do_request()](Self::do_request())
70    #[maybe_async::maybe_async]
71    pub async fn query(&mut self) -> NetResult<QueryResponsePayload> {
72        // Don't repeatedly query the server as the result should be the same
73        // every time for the same client connection. Instead cache the result
74        // and return it on subsequent requests.
75        if let Some(payload) = &self.cached_query_response_payload {
76            return Ok(payload.clone());
77        }
78
79        // Setup the request
80        let wanted_info = vec![
81            QueryFunction::QueryOperations,
82            QueryFunction::QueryObjects,
83            QueryFunction::QueryServerInformation,
84            QueryFunction::QueryExtensionList,
85        ];
86        let request = RequestPayload::Query(wanted_info);
87
88        // Execute the request and capture the response
89        let res = self.do_request_payload(request).await?.try_into()?;
90
91        let ResponsePayload::Query(payload) = res else {
92            return Err(NetError::UnexpectedData(format!(
93                "Expected Query payload but response has {res}"
94            )));
95        };
96
97        self.cached_query_response_payload = Some(payload.clone());
98
99        Ok(payload)
100    }
101
102    /// Serialize a KMIP 1.0 [Create Key Pair](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581269)
103    /// request to create an RSA key pair.
104    ///
105    /// See also: [do_request()](Self::do_request())
106    ///
107    /// Creates an RSA key pair.
108    ///
109    /// To create keys of other types or with other parameters you must compose the Create Key Pair request manually
110    /// and pass it to [do_request()](Self::do_request()) directly.
111    #[maybe_async::maybe_async]
112    pub async fn create_rsa_key_pair(
113        &mut self,
114        key_length: i32,
115        private_key_name: String,
116        public_key_name: String,
117    ) -> NetResult<(String, String)> {
118        // Setup the request
119        let request = RequestPayload::CreateKeyPair(
120            Some(CommonTemplateAttribute::new(vec![
121                request::Attribute::CryptographicAlgorithm(CryptographicAlgorithm::RSA),
122                request::Attribute::CryptographicLength(key_length),
123            ])),
124            Some(PrivateKeyTemplateAttribute::new(vec![
125                request::Attribute::Name(private_key_name),
126                request::Attribute::CryptographicUsageMask(CryptographicUsageMask::Sign),
127            ])),
128            Some(PublicKeyTemplateAttribute::new(vec![
129                request::Attribute::Name(public_key_name),
130                request::Attribute::CryptographicUsageMask(CryptographicUsageMask::Verify),
131            ])),
132        );
133
134        // Execute the request and capture the response
135        let res = self.do_request_payload(request).await?.try_into()?;
136
137        // Execute the request and capture the response
138        let ResponsePayload::CreateKeyPair(payload) = res else {
139            return Err(NetError::UnexpectedData(format!(
140                "Expected Query payload but response has {res}"
141            )));
142        };
143
144        let CreateKeyPairResponsePayload {
145            private_key_unique_identifier: UniqueIdentifier(prikey),
146            public_key_unique_identifier: UniqueIdentifier(pubkey),
147        } = payload;
148
149        Ok((prikey, pubkey))
150    }
151
152    /// Serialize a KMIP 1.2 [Rng Retrieve](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613562)
153    /// operation to retrieve a number of random bytes.
154    ///
155    /// See also: [do_request()](Self::do_request())
156    ///
157    #[maybe_async::maybe_async]
158    pub async fn rng_retrieve(&mut self, num_bytes: i32) -> NetResult<Vec<u8>> {
159        let request = RequestPayload::RNGRetrieve(DataLength(num_bytes));
160
161        // Execute the request and capture the response
162        let res = self.do_request_payload(request).await?.try_into()?;
163
164        let ResponsePayload::RNGRetrieve(payload) = res else {
165            return Err(NetError::UnexpectedData(format!(
166                "Expected RNGRetrieve payload but response has {res}"
167            )));
168        };
169
170        Ok(payload.0.0)
171    }
172
173    /// Serialize a KMIP 1.2 [Sign](https://docs.oasis-open.org/kmip/spec/v1.2/os/kmip-spec-v1.2-os.html#_Toc409613558)
174    /// operation to sign the given bytes with the given private key ID.
175    ///
176    /// See also: [do_request()](Self::do_request())
177    ///
178    #[maybe_async::maybe_async]
179    pub async fn sign(&mut self, private_key_id: &str, in_bytes: &[u8]) -> NetResult<Vec<u8>> {
180        let request = RequestPayload::Sign(
181            Some(UniqueIdentifier(private_key_id.to_owned())),
182            Some(
183                CryptographicParameters::default()
184                    .with_padding_method(PaddingMethod::PKCS1_v1_5)
185                    .with_hashing_algorithm(HashingAlgorithm::SHA256)
186                    .with_cryptographic_algorithm(CryptographicAlgorithm::RSA),
187            ),
188            Data(in_bytes.to_vec()),
189        );
190
191        // Execute the request and capture the response
192        let res = self.do_request_payload(request).await?.try_into()?;
193
194        let ResponsePayload::Sign(payload) = res else {
195            return Err(NetError::UnexpectedData(format!(
196                "Expected Sign payload but response has {res}"
197            )));
198        };
199
200        Ok(payload.signature_data)
201    }
202
203    /// Serialize a KMIP 1.0 [Activate](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581226)
204    /// operation to activate a given private key ID.
205    ///
206    /// See also: [do_request()](Self::do_request())
207    ///
208    /// To activate other kinds of managed object you must compose the Activate request manually and pass it to
209    /// [do_request()](Self::do_request()) directly.
210    #[maybe_async::maybe_async]
211    pub async fn activate_key(&mut self, private_key_id: &str) -> NetResult<()> {
212        let request = RequestPayload::Activate(UniqueIdentifier(private_key_id.to_owned()).into());
213
214        // Execute the request and capture the response
215        let res = self.do_request_payload(request).await?.try_into()?;
216
217        let ResponsePayload::Activate(_) = res else {
218            return Err(NetError::UnexpectedData(format!(
219                "Expected Activate payload but response has {res}"
220            )));
221        };
222
223        Ok(())
224    }
225
226    /// Serialize a KMIP 1.0 [Revoke](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581227)
227    /// operation to deactivate a given private key ID.
228    ///
229    /// See also: [do_request()](Self::do_request())
230    ///
231    /// To deactivate other kinds of managed object you must compose the Revoke request manually and pass it to
232    /// [do_request()](Self::do_request()) directly.
233    #[maybe_async::maybe_async]
234    pub async fn revoke_key(&mut self, private_key_id: &str) -> NetResult<()> {
235        let request = RequestPayload::Revoke(
236            Some(UniqueIdentifier(private_key_id.to_owned())),
237            RevocationReason(
238                RevocationReasonCode::CessationOfOperation,
239                Option::<RevocationMessage>::None,
240            ),
241            Option::<CompromiseOccurrenceDate>::None,
242        );
243
244        // Execute the request and capture the response
245        let res = self.do_request_payload(request).await?.try_into()?;
246
247        let ResponsePayload::Revoke(_) = res else {
248            return Err(NetError::UnexpectedData(format!(
249                "Expected Revoke payload but response has {res}"
250            )));
251        };
252
253        Ok(())
254    }
255
256    /// Serialize a KMIP 1.0 [Destroy](https://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581228)
257    /// operation to destroy a given private key ID.
258    ///
259    /// See also: [do_request()](Self::do_request())
260    ///
261    /// To destroy other kinds of managed object you must compose the Destroy request manually and pass it to
262    /// [do_request()](Self::do_request()) directly.
263    #[maybe_async::maybe_async]
264    pub async fn destroy_key(&mut self, key_id: &str) -> NetResult<()> {
265        let request = RequestPayload::Destroy(Some(UniqueIdentifier(key_id.to_owned())));
266
267        // Execute the request and capture the response
268        let res = self.do_request_payload(request).await?.try_into()?;
269
270        let ResponsePayload::Destroy(_) = res else {
271            return Err(NetError::UnexpectedData(format!(
272                "Expected Destroy payload but response has {res}"
273            )));
274        };
275
276        Ok(())
277    }
278
279    /// Serialize a KMIP 1.0 [ModifyAttribute](http://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581222)
280    /// operation to rename a given key ID.
281    ///
282    /// See also: [do_request()](Self::do_request())
283    ///
284    /// To modify other attributes of managed objects you must compose the Modify Attribute request manually and pass
285    /// it to [do_request()](Self::do_request()) directly.
286    #[maybe_async::maybe_async]
287    pub async fn rename_key(&mut self, key_id: &str, new_name: String) -> NetResult<()> {
288        // Setup the request
289        let request = RequestPayload::ModifyAttribute(
290            Some(UniqueIdentifier(key_id.to_string())),
291            request::Attribute::Name(new_name),
292        );
293
294        // Execute the request and capture the response
295        let res = self.do_request_payload(request).await?.try_into()?;
296
297        let ResponsePayload::ModifyAttribute(_) = res else {
298            return Err(NetError::UnexpectedData(format!(
299                "Expected ModifyAttribute payload but response has {res}"
300            )));
301        };
302
303        Ok(())
304    }
305
306    /// Serialize a KMIP 1.0 [Get](http://docs.oasis-open.org/kmip/spec/v1.0/os/kmip-spec-1.0-os.html#_Toc262581218)
307    /// operation to get the details of a given key ID.
308    ///
309    /// See also: [do_request()](Self::do_request())
310    #[maybe_async::maybe_async]
311    pub async fn get_key(&mut self, key_id: &str) -> NetResult<GetResponsePayload> {
312        // Setup the request
313        let request = RequestPayload::Get(
314            Some(UniqueIdentifier(key_id.to_string())),
315            Option::<KeyFormatType>::None,
316            Option::<KeyCompressionType>::None,
317            Option::<KeyWrappingSpecification>::None,
318        );
319
320        // Execute the request and capture the response
321        let res = self.do_request_payload(request).await?.try_into()?;
322
323        let ResponsePayload::Get(payload) = res else {
324            return Err(NetError::UnexpectedData(format!(
325                "Expected Get payload but response has {res}"
326            )));
327        };
328
329        Ok(payload)
330    }
331}
332
333//--- Lower level client interface
334//
335// For sending requests and receiving responses.
336
337impl<T: ReadWrite> Client<T> {
338    /// Write request bytes to the given stream and read, deserialize and
339    /// sanity check the response.
340    ///
341    /// Tip: For cases when the response is expected to consist of only a
342    /// single batch item,`TryInto` can be used to simplify handling of the
343    /// result, e.g.:
344    ///
345    /// ```ignore
346    /// // Setup the request.
347    /// let wanted_info = vec![
348    ///     QueryFunction::QueryOperations,
349    ///     QueryFunction::QueryObjects,
350    ///     QueryFunction::QueryServerInformation,
351    /// ];
352    /// let request = RequestPayload::Query(wanted_info);
353    ///
354    /// // Execute the request and capture the response.
355    /// let res = client.do_request_payload(request).await?.try_into()?;
356    /// let ResponsePayload::Query(payload) = res else {
357    ///     return Err(NetError::UnexpectedData(format!(
358    ///         "Expected Query payload but response has {res}"
359    ///     )));
360    /// };
361    /// ```
362    ///
363    /// Note: Enforcing a timeout on this operation is the responsibility of
364    /// the caller.
365    #[maybe_async::maybe_async]
366    pub async fn do_request(&mut self, request: RequestMessage) -> NetResult<Vec<NetResult<response::BatchItem>>> {
367        trace!("Serializing request to KMIP wire bytes");
368        let len = self.write_buf.len();
369        assert!(len <= i32::MAX as usize);
370        let mut len = len as i32;
371
372        let mut stream = Self::get_mut_stream(&self.stream).await?;
373        let mut formatter;
374
375        // TODO: Enforce a timeout on sending the request?
376        let request_bytes = loop {
377            formatter = crate::ttlv::Formatter::new(&mut self.write_buf);
378            if request.format(&mut formatter).is_ok() {
379                let request_bytes = formatter.filled().as_flattened();
380                Self::write_to_stream(&mut stream, request_bytes).await?;
381                break request_bytes;
382            } else if len >= self.max_message_size {
383                // Buffer is already at the maximum possible size.
384                return Err(NetError::SerializeError(format!(
385                    "Message too large: {len} > {}",
386                    self.max_message_size
387                )));
388            } else {
389                // Retry with a larger buffer.
390                len = i32::max(self.max_message_size, len.saturating_mul(2));
391                self.write_buf.resize(len as usize, MaybeUninit::uninit());
392            }
393        };
394
395        trace!("Waiting for a response from the server");
396        let res = read_message_from_stream(
397            stream.deref_mut(),
398            &mut self.read_buf,
399            self.max_message_size,
400            ResponseMessage::fast_scan,
401            self.connection_error_count.clone(),
402        )
403        .await?;
404        trace!("KMIP server response received");
405
406        Self::post_process_response(res).await.map_err(|mut err| {
407            if let NetError::DeserializeError { req, .. } = &mut err {
408                *req = request_bytes.into();
409            }
410            err
411        })
412    }
413
414    /// Serialize the given request to the stream and deserialize the response.
415    ///
416    /// Automatically constructs the request message wrapper around the
417    /// payload including the [crate::types::request::RequestHeader] and
418    /// [crate::types::request::BatchItem].
419    ///
420    /// Only supports a single batch item.
421    ///
422    /// Sets the request operation to [RequestPayload::operation()].
423    ///
424    /// # Errors
425    ///
426    /// Will fail if there is a problem serializing the request, writing to or
427    /// reading from the stream, deserializing the response or if the response
428    /// does not indicate operation success or contains more than one batch
429    /// item.
430    #[maybe_async::maybe_async]
431    pub async fn do_request_payload(
432        &mut self,
433        payload: RequestPayload,
434    ) -> NetResult<Vec<NetResult<response::BatchItem>>> {
435        self.do_request(payload_to_request(
436            self.auth.clone(),
437            Some(MaximumResponseSize(self.max_message_size)),
438            payload,
439        )?)
440        .await
441    }
442
443    #[maybe_async::maybe_async]
444    pub async fn do_request_batch(
445        &mut self,
446        batch_items: Vec<BatchItem>,
447    ) -> NetResult<Vec<NetResult<response::BatchItem>>> {
448        self.do_request(batch_items_to_request(
449            self.auth.clone(),
450            Some(MaximumResponseSize(self.max_message_size)),
451            batch_items,
452        )?)
453        .await
454    }
455}
456
457//------------ Internals -----------------------------------------------------
458
459impl<T: ReadWrite> Client<T> {
460    #[cfg(feature = "tokio")]
461    async fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
462        Ok(stream.lock().await)
463    }
464
465    #[cfg(not(feature = "tokio"))]
466    fn get_mut_stream(stream: &Mutex<T>) -> NetResult<impl DerefMut<Target = T> + '_> {
467        Ok(stream.lock()?)
468    }
469
470    #[maybe_async::maybe_async]
471    async fn post_process_response(mut res: ResponseMessage) -> NetResult<Vec<NetResult<response::BatchItem>>> {
472        if res.header.batch_count >= 1 && !res.batch_items.is_empty() {
473            let res = res
474                .batch_items
475                .drain(..)
476                .map(|item| match item.result_status {
477                    ResultStatus::OperationFailed => {
478                        let message = item
479                            .result_message
480                            .unwrap_or_else(|| "No further information available".to_string());
481                        let reason = item
482                            .result_reason
483                            .map(|v| v.to_string())
484                            .unwrap_or_else(|| "Reason unknown".to_string());
485                        let operation = item
486                            .operation
487                            .map(|op| op.to_string())
488                            .unwrap_or_else(|| "unknown".to_string());
489                        let err = format!("Operation {operation} failed: {reason}: {message}");
490                        if matches!(item.result_reason, Some(ResultReason::ItemNotFound)) {
491                            Err(NetError::ItemNotFound(err))
492                        } else {
493                            Err(NetError::ServerError(err))
494                        }
495                    }
496                    ResultStatus::OperationPending => Err(NetError::InternalError(
497                        "Result status 'operation pending' is not supported".into(),
498                    )),
499                    ResultStatus::OperationUndone => Err(NetError::InternalError(
500                        "Result status 'operation undone' is not supported".into(),
501                    )),
502                    ResultStatus::Success => Ok(item),
503                })
504                .collect::<Vec<_>>();
505            Ok(res)
506        } else {
507            let err = format!(
508                "Expected at least one batch item in response but received {}",
509                res.batch_items.len()
510            );
511            Err(NetError::ServerError(err))
512        }
513    }
514
515    #[maybe_async::maybe_async]
516    async fn write_to_stream(stream: &mut T, bytes: &[u8]) -> NetResult<()> {
517        trace!(
518            "Writing {} bytes to the server: {}",
519            bytes.len(),
520            hex::encode_upper(bytes)
521        );
522        stream.write_all(bytes).await?;
523        Ok(())
524    }
525}
526
527impl<T: ReadWrite> Clone for Client<T> {
528    fn clone(&self) -> Self {
529        Self {
530            auth: self.auth.clone(),
531            max_message_size: self.max_message_size,
532            stream: self.stream.clone(),
533            connection_error_count: self.connection_error_count.clone(),
534            read_buf: vec![0u8; 8192],
535            write_buf: vec![MaybeUninit::uninit(); 8192],
536            cached_query_response_payload: self.cached_query_response_payload.clone(),
537        }
538    }
539}
540
541impl<T: ReadWrite> Client<T> {
542    /// Get the authentication settings used by this client.
543    pub fn auth(&self) -> Option<&Authentication> {
544        self.auth.as_ref()
545    }
546
547    /// Get the maximum message size in bytes permitted by this client.
548    pub fn max_message_size(&self) -> i32 {
549        self.max_message_size
550    }
551
552    /// Get the count of connection errors experienced by this Client.
553    pub fn connection_error_count(&self) -> usize {
554        self.connection_error_count.load(Ordering::SeqCst)
555    }
556}