vaultrs/
sys.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use crate::{
    api::{
        self,
        sys::{
            requests::{
                ReadHealthRequest, SealRequest, StartInitializationRequest,
                StartInitializationRequestBuilder, UnsealRequest,
            },
            responses::{ReadHealthResponse, StartInitializationResponse, UnsealResponse},
        },
    },
    client::Client,
    error::ClientError,
};

/// Represents the status of a Vault server.
#[derive(Debug)]
pub enum ServerStatus {
    OK,
    PERFSTANDBY,
    RECOVERY,
    SEALED,
    STANDBY,
    UNINITIALIZED,
    UNKNOWN,
}

/// Returns health information about the Vault server.
///
/// See [ReadHealthRequest]
pub async fn health(client: &impl Client) -> Result<ReadHealthResponse, ClientError> {
    let endpoint = ReadHealthRequest::builder().build().unwrap();
    api::exec_with_no_result(client, endpoint).await
}

/// Initialize a new Vault. The Vault must not have been previously initialized.
///
/// See [StartInitializationRequest]
pub async fn start_initialization(
    client: &impl Client,
    secret_shares: u64,
    secret_threshold: u64,
    opts: Option<&mut StartInitializationRequestBuilder>,
) -> Result<StartInitializationResponse, ClientError> {
    let mut t = StartInitializationRequest::builder();
    let endpoint = opts
        .unwrap_or(&mut t)
        .secret_shares(secret_shares)
        .secret_threshold(secret_threshold)
        .build()
        .unwrap();
    api::exec_with_no_result(client, endpoint).await
}

/// Seals the Vault server.
///
/// See [SealRequest]
pub async fn seal(client: &impl Client) -> Result<(), ClientError> {
    let endpoint = SealRequest::builder().build().unwrap();
    api::exec_with_empty(client, endpoint).await
}

/// Unseals the Vault server.
///
/// See [UnsealRequest]
pub async fn unseal(
    client: &impl Client,
    key: Option<String>,
    reset: Option<bool>,
    migrate: Option<bool>,
) -> Result<UnsealResponse, ClientError> {
    let endpoint = UnsealRequest::builder()
        .key(key)
        .reset(reset)
        .migrate(migrate)
        .build()
        .unwrap();
    api::exec_with_no_result(client, endpoint).await
}

/// Returns the status of the Vault server.
///
/// See [ReadHealthRequest]
pub async fn status(client: &impl Client) -> Result<ServerStatus, ClientError> {
    let result = health(client).await;
    match result {
        Ok(_) => Ok(ServerStatus::OK),
        Err(e) => match e {
            ClientError::RestClientError { source } => match source {
                rustify::errors::ClientError::ServerResponseError {
                    code: 429,
                    content: _,
                } => Ok(ServerStatus::STANDBY),
                rustify::errors::ClientError::ServerResponseError {
                    code: 472,
                    content: _,
                } => Ok(ServerStatus::RECOVERY),
                rustify::errors::ClientError::ServerResponseError {
                    code: 473,
                    content: _,
                } => Ok(ServerStatus::PERFSTANDBY),
                rustify::errors::ClientError::ServerResponseError {
                    code: 501,
                    content: _,
                } => Ok(ServerStatus::UNINITIALIZED),
                rustify::errors::ClientError::ServerResponseError {
                    code: 503,
                    content: _,
                } => Ok(ServerStatus::SEALED),
                _ => Err(ClientError::RestClientError { source }),
            },
            _ => Err(e),
        },
    }
}

pub mod auth {
    use std::collections::HashMap;

    use crate::api;
    use crate::api::sys::requests::{
        EnableAuthRequest, EnableAuthRequestBuilder, ListAuthsRequest,
    };
    use crate::api::sys::responses::AuthResponse;
    use crate::client::Client;
    use crate::error::ClientError;

    /// Enables an auth engine at the given path
    ///
    /// See [EnableAuthRequest]
    pub async fn enable(
        client: &impl Client,
        path: &str,
        engine_type: &str,
        opts: Option<&mut EnableAuthRequestBuilder>,
    ) -> Result<(), ClientError> {
        let mut t = EnableAuthRequest::builder();
        let endpoint = opts
            .unwrap_or(&mut t)
            .path(path)
            .engine_type(engine_type)
            .build()
            .unwrap();
        api::exec_with_empty(client, endpoint).await
    }

    /// Lists all mounted auth engines
    ///
    /// See [ListAuthsRequest]
    pub async fn list(client: &impl Client) -> Result<HashMap<String, AuthResponse>, ClientError> {
        let endpoint = ListAuthsRequest::builder().build().unwrap();
        api::exec_with_result(client, endpoint).await
    }
}

pub mod mount {
    use std::collections::HashMap;

    use crate::api;
    use crate::api::sys::requests::{
        DisableEngineRequest, EnableEngineRequest, EnableEngineRequestBuilder,
        GetConfigurationOfTheSecretEngineRequest, ListMountsRequest,
    };
    use crate::api::sys::responses::{GetConfigurationOfTheSecretEngineResponse, MountResponse};
    use crate::client::Client;
    use crate::error::ClientError;

    /// Enables a secret engine at the given path
    ///
    /// See [EnableEngineRequest]
    pub async fn enable(
        client: &impl Client,
        path: &str,
        engine_type: &str,
        opts: Option<&mut EnableEngineRequestBuilder>,
    ) -> Result<(), ClientError> {
        let mut t = EnableEngineRequest::builder();
        let endpoint = opts
            .unwrap_or(&mut t)
            .path(path)
            .engine_type(engine_type)
            .build()
            .unwrap();
        api::exec_with_empty(client, endpoint).await
    }

    /// Disable a secret engine at the given path
    ///
    /// See [DisableEngineRequest]
    #[instrument(skip(client), err)]
    pub async fn disable(client: &impl Client, path: &str) -> Result<(), ClientError> {
        let endpoint = DisableEngineRequest::builder().path(path).build().unwrap();
        api::exec_with_empty(client, endpoint).await
    }

    /// This endpoint returns the configuration of a specific secret engine.
    ///
    /// See [GetConfigurationOfTheSecretEngineRequest]
    #[instrument(skip(client), err)]
    pub async fn get_configuration_of_a_secret_engine(
        client: &impl Client,
        path: &str,
    ) -> Result<GetConfigurationOfTheSecretEngineResponse, ClientError> {
        let endpoint = GetConfigurationOfTheSecretEngineRequest::builder()
            .path(path)
            .build()
            .unwrap();
        api::exec_with_result(client, endpoint).await
    }

    /// Lists all mounted secret engines
    ///
    /// See [ListMountsRequest]
    pub async fn list(client: &impl Client) -> Result<HashMap<String, MountResponse>, ClientError> {
        let endpoint = ListMountsRequest::builder().build().unwrap();
        api::exec_with_result(client, endpoint).await
    }
}

pub mod policy {
    use crate::{
        api::{
            self,
            sys::{
                requests::{
                    CreatePolicyRequest, DeletePolicyRequest, ListPoliciesRequest,
                    ReadPolicyRequest,
                },
                responses::{ListPoliciesResponse, ReadPolicyResponse},
            },
        },
        client::Client,
        error::ClientError,
    };

    /// Deletes the given policy.
    ///
    /// See [DeletePolicyRequest]
    pub async fn delete(client: &impl Client, name: &str) -> Result<(), ClientError> {
        let endpoint = DeletePolicyRequest::builder().name(name).build().unwrap();
        api::exec_with_empty(client, endpoint).await
    }

    /// Lists all configured policies.
    ///
    /// See [ListPoliciesRequest]
    pub async fn list(client: &impl Client) -> Result<ListPoliciesResponse, ClientError> {
        let endpoint = ListPoliciesRequest::builder().build().unwrap();
        api::exec_with_result(client, endpoint).await
    }

    /// Reads the given policy.
    ///
    /// See [ReadPolicyRequest]
    pub async fn read(client: &impl Client, name: &str) -> Result<ReadPolicyResponse, ClientError> {
        let endpoint = ReadPolicyRequest::builder().name(name).build().unwrap();
        api::exec_with_result(client, endpoint).await
    }

    /// Sets the given policy.
    ///
    /// See [CreatePolicyRequest]
    pub async fn set(client: &impl Client, name: &str, policy: &str) -> Result<(), ClientError> {
        let endpoint = CreatePolicyRequest::builder()
            .name(name)
            .policy(policy)
            .build()
            .unwrap();
        api::exec_with_empty(client, endpoint).await
    }
}

pub mod wrapping {
    use serde::de::DeserializeOwned;

    use crate::{
        api::{
            self,
            sys::{
                requests::{UnwrapRequest, WrappingLookupRequest},
                responses::WrappingLookupResponse,
            },
        },
        client::Client,
        error::ClientError,
    };

    /// Looks up information about a token wrapping response
    ///
    /// See [WrappingLookupResponse]
    pub async fn lookup(
        client: &impl Client,
        token: &str,
    ) -> Result<WrappingLookupResponse, ClientError> {
        let endpoint = WrappingLookupRequest::builder()
            .token(token)
            .build()
            .unwrap();
        api::exec_with_result(client, endpoint).await
    }

    /// Unwraps a token wrapped response
    ///
    /// See [UnwrapRequest]
    pub async fn unwrap<D: DeserializeOwned>(
        client: &impl Client,
        token: Option<&str>,
    ) -> Result<D, ClientError> {
        let endpoint = UnwrapRequest {
            token: token.map(|v| v.to_string()),
        };
        let res = api::exec_with_result(client, endpoint).await?;
        serde_json::value::from_value(res).map_err(|e| ClientError::JsonParseError { source: e })
    }
}

pub mod tools {
    use crate::{
        api::{
            self,
            sys::{
                requests::{RandomRequest, RandomRequestBuilder},
                responses::RandomResponse,
            },
        },
        client::Client,
        error::ClientError,
    };

    /// Returns high-quality random bytes of the specified length.
    ///
    /// See [RandomResponse]
    #[instrument(skip(client, opts), err)]
    pub async fn random(
        client: &impl Client,
        opts: Option<&mut RandomRequestBuilder>,
    ) -> Result<RandomResponse, ClientError> {
        let mut t = RandomRequest::builder();
        let endpoint = opts.unwrap_or(&mut t).build().unwrap();
        api::exec_with_result(client, endpoint).await
    }
}