Skip to main content

keyvault_agent_azure_key_vault_keys/
lib.rs

1use http::status::StatusCode;
2use keyvault_agent_azure_auth::Credential;
3use reqwest::{Client, Method, RequestBuilder, Response};
4use serde::de::DeserializeOwned;
5use std::sync::Mutex;
6use thiserror::Error;
7
8use crate::auth::*;
9use crate::models::*;
10
11pub mod auth;
12pub mod models;
13
14pub type Result<T> = std::result::Result<T, Error>;
15
16#[derive(Error, Debug)]
17pub enum Error {
18    #[error(transparent)]
19    SerdeJsonError(#[from] serde_json::error::Error),
20    #[error(transparent)]
21    ReqwestError(#[from] reqwest::Error),
22    #[error(transparent)]
23    AuthenticationError(#[from] keyvault_agent_azure_auth::Error),
24    #[error("{}: {}", .0.code, .0.message)]
25    KeyVaultError(models::KeyVaultError),
26    #[error("{0}")]
27    Unknown(String),
28}
29
30pub struct KeyClient {
31    authenticator: Mutex<KeyVaultAuthenticator>,
32    client: Client,
33}
34
35impl KeyClient {
36    const API_VERSION: &'static str = "7.0";
37    pub fn new(cred: Credential) -> KeyClient {
38        let client = Client::new();
39
40        KeyClient {
41            authenticator: Mutex::new(KeyVaultAuthenticator::new(cred)),
42            client,
43        }
44    }
45
46    pub async fn list_keys(&self, vault_uri: &str) -> Result<Vec<KeyListEntry>> {
47        self.list_keys_impl(format!(
48            "{vault_uri}/keys?api-version={api_version}",
49            vault_uri = &vault_uri,
50            api_version = KeyClient::API_VERSION
51        ))
52        .await
53    }
54
55    pub async fn list_key_versions(&self, key_uri: &str) -> Result<Vec<KeyListEntry>> {
56        self.list_keys_impl(format!(
57            "{key_uri}/versions?api-version={api_version}",
58            key_uri = &key_uri,
59            api_version = KeyClient::API_VERSION
60        ))
61        .await
62    }
63
64    async fn list_keys_impl(&self, list_uri: String) -> Result<Vec<KeyListEntry>> {
65        let mut list_uri = Some(list_uri);
66        let mut list_entries = Vec::new();
67
68        while let Some(next_link) = &list_uri {
69            let key_list: KeyList = self.request(|c| c.request(Method::GET, next_link)).await?;
70
71            list_entries.push(key_list.value);
72            list_uri = key_list.next_link;
73        }
74
75        Ok(list_entries.into_iter().flatten().collect())
76    }
77
78    pub async fn create_key(
79        &self,
80        vault_uri: &str,
81        options: CreateKeyOptions,
82    ) -> Result<KeyVaultKey> {
83        self.request(|c| {
84            c.post(&format!(
85                "{vault_uri}/keys/{key_name}/create?api-version={api_version}",
86                vault_uri = &vault_uri,
87                key_name = &options.name,
88                api_version = KeyClient::API_VERSION
89            ))
90            .json(&options)
91        })
92        .await
93    }
94
95    pub async fn delete_key(&self, key_uri: &str) -> Result<KeyVaultKey> {
96        self.request(|c| {
97            c.delete(&format!(
98                "{key_uri}?api-version={api_version}",
99                key_uri = &key_uri,
100                api_version = KeyClient::API_VERSION
101            ))
102        })
103        .await
104    }
105
106    pub async fn get_key(&self, key_name: &str) -> Result<KeyVaultKey> {
107        self.request(|c| {
108            c.request(
109                Method::GET,
110                &format!(
111                    "{key_name}?api-version={api_version}",
112                    key_name = &key_name,
113                    api_version = KeyClient::API_VERSION
114                ),
115            )
116        })
117        .await
118    }
119
120    pub async fn sign_digest(
121        &self,
122        key_name: &str,
123        alg: &str,
124        value: &[u8],
125    ) -> Result<KeyOperationResult> {
126        self.request(|c| {
127            c.post(&format!(
128                "{key_name}/sign?api-version={api_version}",
129                key_name = &key_name,
130                api_version = KeyClient::API_VERSION
131            ))
132            .json(&SignRequest {
133                alg: alg.to_string(),
134                value: value.to_vec(),
135            })
136        })
137        .await
138    }
139
140    pub async fn verify_digest(
141        &self,
142        key_name: &str,
143        alg: &str,
144        digest: &[u8],
145        value: &[u8],
146    ) -> Result<bool> {
147        let result: VerifyResult = self
148            .request(|c| {
149                c.post(&format!(
150                    "{key_name}/verify?api-version={api_version}",
151                    key_name = &key_name,
152                    api_version = KeyClient::API_VERSION
153                ))
154                .json(&VerifyRequest {
155                    alg: alg.to_string(),
156                    digest: digest.to_vec(),
157                    value: value.to_vec(),
158                })
159            })
160            .await?;
161
162        Ok(result.value)
163    }
164
165    pub async fn encrypt(
166        &self,
167        key_name: &str,
168        alg: &str,
169        value: &[u8],
170    ) -> Result<KeyOperationResult> {
171        self.request(|c| {
172            c.post(&format!(
173                "{key_name}/encrypt?api-version={api_version}",
174                key_name = &key_name,
175                api_version = KeyClient::API_VERSION
176            ))
177            .json(&EncryptRequest {
178                alg: alg.to_string(),
179                value: value.to_vec(),
180            })
181        })
182        .await
183    }
184
185    pub async fn decrypt(
186        &self,
187        key_name: &str,
188        alg: &str,
189        value: &[u8],
190    ) -> Result<KeyOperationResult> {
191        self.request(|c| {
192            c.post(&format!(
193                "{key_name}/decrypt?api-version={api_version}",
194                key_name = &key_name,
195                api_version = KeyClient::API_VERSION
196            ))
197            .json(&DecryptRequest {
198                alg: alg.to_string(),
199                value: value.to_vec(),
200            })
201        })
202        .await
203    }
204
205    pub async fn wrap(
206        &self,
207        key_name: &str,
208        alg: &str,
209        value: &[u8],
210    ) -> Result<KeyOperationResult> {
211        self.request(|c| {
212            c.post(&format!(
213                "{key_name}/wrap?api-version={api_version}",
214                key_name = &key_name,
215                api_version = KeyClient::API_VERSION
216            ))
217            .json(&WrapRequest {
218                alg: alg.to_string(),
219                value: value.to_vec(),
220            })
221        })
222        .await
223    }
224
225    pub async fn unwrap(
226        &self,
227        key_name: &str,
228        alg: &str,
229        value: &[u8],
230    ) -> Result<KeyOperationResult> {
231        self.request(|c| {
232            c.post(&format!(
233                "{key_name}/unwrap?api-version={api_version}",
234                key_name = &key_name,
235                api_version = KeyClient::API_VERSION
236            ))
237            .json(&UnwrapRequest {
238                alg: alg.to_string(),
239                value: value.to_vec(),
240            })
241        })
242        .await
243    }
244
245    pub async fn backup(&self, key_name: &str) -> Result<Vec<u8>> {
246        let backup: Backup = self
247            .request(|c| {
248                c.post(&format!(
249                    "{key_name}/backup?api-version={api_version}",
250                    key_name = &key_name,
251                    api_version = KeyClient::API_VERSION
252                ))
253                .json(&())
254            })
255            .await?;
256
257        Ok(backup.value)
258    }
259
260    pub async fn restore(&self, vault_name: &str, value: &[u8]) -> Result<KeyVaultKey> {
261        self.request(|c| {
262            c.post(&format!(
263                "{vault_name}/keys/restore?api-version={api_version}",
264                vault_name = &vault_name,
265                api_version = KeyClient::API_VERSION
266            ))
267            .json(&Backup {
268                value: value.to_vec(),
269            })
270        })
271        .await
272    }
273
274    pub async fn request<F, RespT>(&self, request_builder: F) -> Result<RespT>
275    where
276        F: Fn(&Client) -> RequestBuilder,
277        RespT: DeserializeOwned,
278    {
279        let mut response = self.request_impl(&request_builder).await?;
280
281        if response.status() == StatusCode::UNAUTHORIZED {
282            self.authenticator
283                .lock()
284                .unwrap()
285                .refresh_token(&response)
286                .await?;
287            response = self.request_impl(&request_builder).await?;
288        }
289
290        match response.status().as_u16() {
291            200..=299 => Ok(response.json().await?),
292            _ => Err(Error::KeyVaultError(
293                response.json::<models::KeyVaultErrorMessage>().await?.error,
294            )),
295        }
296    }
297
298    pub async fn request_impl<F>(&self, request_builder: F) -> Result<Response>
299    where
300        F: Fn(&Client) -> RequestBuilder,
301    {
302        let req = (request_builder)(&self.client);
303
304        let req = match self.authenticator.lock().unwrap().token() {
305            Some(token) => req.bearer_auth(token),
306            None => req,
307        };
308
309        Ok(req.send().await?)
310    }
311}
312
313pub struct BearerAuthenticateHeader {
314    authorization: String,
315    resource: String,
316}