fundamentum_sdk_mqtt/security/fetcher.rs
1//! Security fetcher definitio
2use async_trait::async_trait;
3
4/// Security Fetcher Interface
5///
6/// This trait defines the interface for implementing a custom security fetcher, responsible for obtaining the
7/// private key from the specifications of the device. By implementing this trait, you can define a specific process
8/// for retrieving the private key securely, such as utilizing a Trusted Platform Module (TPM) or other dedicated
9/// security hardware.
10///
11/// # Asynchronous Fetching
12///
13/// The method `read_private_key` is asynchronous, indicated by the [`async_trait`](https://crates.io/crates/async-trait) attribute.
14/// It asynchronously returns a [`Vec`] of bytes (`u8`), representing the private key. Implementers of this trait can
15/// perform asynchronous operations, such as reading the key from a file, fetching it from a remote service, or using
16/// any other asynchronous mechanism.
17///
18/// # Errors
19///
20/// The `read_private_key` method may return an [`std::io::Error`] if any I/O operation fails during the fetching process.
21#[async_trait]
22pub trait SecurityFetcher {
23 /// Returns a [`Vec`] of bytes representing the private key from the implementation.
24 ///
25 /// # Errors
26 ///
27 /// During the fetching process, an [`std::io::Error`] can occur if any I/O operation fails.
28 async fn read_private_key(&self) -> Result<Vec<u8>, std::io::Error>;
29}
30
31/// Security Fetcher default read file implementation
32///
33/// This implementation of the `SecurityFetcher` allows to use a file to fetch the private key from your device.
34pub struct SecurityFileFetcher {
35 /// Private key's path
36 path: String,
37}
38
39impl SecurityFileFetcher {
40 /// Create basic Security that fetch a file
41 pub fn new<S: Into<String>>(path: S) -> Self {
42 Self { path: path.into() }
43 }
44
45 /// Create a boxed basic Security that fetch a file
46 pub fn new_boxed<S: Into<String>>(path: S) -> Box<Self> {
47 Box::new(Self::new(path))
48 }
49}
50
51#[async_trait]
52impl SecurityFetcher for SecurityFileFetcher {
53 async fn read_private_key(&self) -> Result<Vec<u8>, std::io::Error> {
54 use tokio::fs;
55 fs::read(self.path.clone()).await
56 }
57}