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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::api_model::*;
use crate::operations::*;
use headers::{ContentType, HeaderMap, HeaderMapExt, HeaderValue};
use serde::{Deserialize, Serialize};
use simple_hyper_client::blocking::Client as HttpClient;
use simple_hyper_client::hyper::header::AUTHORIZATION;
use simple_hyper_client::{Bytes, Method, StatusCode};
use uuid::Uuid;
use std::fmt;
use std::io::Read;
use std::marker::PhantomData;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
pub const DEFAULT_API_ENDPOINT: &'static str = "https://sdkms.fortanix.com";
pub type Result<T> = ::std::result::Result<T, Error>;
enum Auth {
Basic(String),
Bearer(String),
}
impl Auth {
fn from_api_key(api_key: &str) -> Self {
Auth::Basic(api_key.to_owned())
}
fn from_user_pass<T: fmt::Display>(username: T, password: &str) -> Self {
Auth::Basic(base64::encode(format!("{}:{}", username, password)))
}
fn format_header(&self) -> HeaderValue {
let value = match *self {
Auth::Basic(ref basic) => format!("Basic {}", basic),
Auth::Bearer(ref bearer) => format!("Bearer {}", bearer),
};
let bytes = Bytes::from(value);
HeaderValue::from_maybe_shared(bytes).expect("invalid characters in auth header")
}
}
pub struct SdkmsClientBuilder {
client: Option<HttpClient>,
api_endpoint: Option<String>,
auth: Option<Auth>,
}
impl SdkmsClientBuilder {
pub fn with_http_client(mut self, client: HttpClient) -> Self {
self.client = Some(client);
self
}
pub fn with_api_endpoint(mut self, api_endpoint: &str) -> Self {
self.api_endpoint = Some(api_endpoint.to_owned());
self
}
pub fn with_api_key(mut self, api_key: &str) -> Self {
self.auth = Some(Auth::from_api_key(api_key));
self
}
pub fn with_access_token(mut self, access_token: &str) -> Self {
self.auth = Some(Auth::Bearer(access_token.to_owned()));
self
}
pub fn build(self) -> Result<SdkmsClient> {
let client = match self.client {
Some(client) => client,
None => {
#[cfg(feature = "native-tls")]
{
use simple_hyper_client::HttpsConnector;
use tokio_native_tls::native_tls::TlsConnector;
let ssl = TlsConnector::new()?;
let connector = HttpsConnector::new(ssl.into());
HttpClient::with_connector(connector)
}
#[cfg(not(feature = "native-tls"))]
panic!("You should either provide an HTTP Client or compile this crate with native-tls feature");
}
};
Ok(SdkmsClient {
client,
api_endpoint: self
.api_endpoint
.unwrap_or_else(|| DEFAULT_API_ENDPOINT.to_owned()),
auth: self.auth,
last_used: AtomicU64::new(0),
auth_response: None,
})
}
}
pub struct SdkmsClient {
auth: Option<Auth>,
api_endpoint: String,
client: HttpClient,
last_used: AtomicU64,
auth_response: Option<AuthResponse>,
}
impl SdkmsClient {
pub fn builder() -> SdkmsClientBuilder {
SdkmsClientBuilder {
client: None,
api_endpoint: None,
auth: None,
}
}
fn authenticate(&self, auth: Option<&Auth>) -> Result<Self> {
let auth_response: AuthResponse = json_request_with_auth(
&self.client,
&self.api_endpoint,
Method::POST,
"/sys/v1/session/auth",
auth,
None::<&()>,
)?;
Ok(SdkmsClient {
client: self.client.clone(),
api_endpoint: self.api_endpoint.clone(),
auth: Some(Auth::Bearer(auth_response.access_token.clone())),
last_used: AtomicU64::new(now().0),
auth_response: Some(auth_response),
})
}
pub fn authenticate_with_api_key(&self, api_key: &str) -> Result<Self> {
self.authenticate(Some(Auth::from_api_key(api_key)).as_ref())
}
pub fn authenticate_with_cert(&self, app_id: Option<&Uuid>) -> Result<Self> {
self.authenticate(app_id.map(|id| Auth::from_user_pass(id, "")).as_ref())
}
pub fn authenticate_app(&self, app_id: &Uuid, app_secret: &str) -> Result<Self> {
self.authenticate(Some(Auth::from_user_pass(app_id, app_secret)).as_ref())
}
pub fn authenticate_user(&self, email: &str, password: &str) -> Result<Self> {
self.authenticate(Some(Auth::from_user_pass(email, password)).as_ref())
}
pub fn api_endpoint(&self) -> &str {
&self.api_endpoint
}
pub fn auth_response(&self) -> Option<&AuthResponse> {
self.auth_response.as_ref()
}
pub fn entity_id(&self) -> Option<Uuid> {
self.auth_response().map(|ar| ar.entity_id)
}
pub fn has_session(&self) -> bool {
match self.auth {
Some(Auth::Bearer(_)) => true,
_ => false,
}
}
fn json_request<E, D>(&self, method: Method, uri: &str, req: Option<&E>) -> Result<D>
where
E: Serialize,
D: for<'de> Deserialize<'de>,
{
let Self {
ref client,
ref api_endpoint,
ref auth,
..
} = *self;
let result = json_request_with_auth(client, api_endpoint, method, uri, auth.as_ref(), req)?;
self.last_used.store(now().0, Ordering::Relaxed);
Ok(result)
}
}
impl Drop for SdkmsClient {
fn drop(&mut self) {
let _ = self.terminate();
}
}
impl SdkmsClient {
pub fn terminate(&mut self) -> Result<()> {
if let Some(Auth::Bearer(_)) = self.auth {
self.json_request(Method::POST, "/sys/v1/session/terminate", None::<&()>)?;
self.auth = None;
}
Ok(())
}
pub fn invoke_plugin_nice<I, O>(&self, id: &Uuid, req: &I) -> Result<O>
where
I: Serialize,
O: for<'de> Deserialize<'de>,
{
let req = serde_json::to_value(req)?;
let output = self.execute::<OperationInvokePlugin>(&req, (id,), None)?;
Ok(serde_json::from_value(output)?)
}
pub fn execute<O: Operation>(
&self,
body: &O::Body,
p: <O::PathParams as TupleRef>::Ref,
q: Option<&O::QueryParams>,
) -> Result<O::Output> {
self.json_request(O::method(), &O::path(p, q), O::to_body(body).as_ref())
}
pub fn request_approval<O: Operation>(
&self,
body: &O::Body,
p: <O::PathParams as TupleRef>::Ref,
q: Option<&O::QueryParams>,
description: Option<String>,
) -> Result<PendingApproval<O>> {
let request = self.create_approval_request(&ApprovalRequestRequest {
operation: Some(O::path(p, q)),
method: Some(format!("{}", O::method())),
body: O::to_body(body),
description,
})?;
Ok(PendingApproval::from_request_id(request.request_id))
}
pub fn expires_in(&self) -> Option<u64> {
let expires_at = self.last_used.load(Ordering::Relaxed)
+ self.auth_response().map_or(0, |ar| ar.expires_in as u64);
expires_at.checked_sub(now().0)
}
}
pub struct PendingApproval<O: Operation>(Uuid, PhantomData<O>);
impl<O: Operation> fmt::Debug for PendingApproval<O> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, formatter)
}
}
impl<O: Operation> PendingApproval<O> {
pub fn from_request_id(request_id: Uuid) -> Self {
PendingApproval(request_id, PhantomData)
}
pub fn request_id(&self) -> Uuid {
self.0
}
pub fn get(&self, sdkms: &SdkmsClient) -> Result<ApprovalRequest> {
sdkms.get_approval_request(&self.0)
}
pub fn status(&self, sdkms: &SdkmsClient) -> Result<ApprovalStatus> {
Ok(self.get(sdkms)?.status)
}
pub fn result(&self, sdkms: &SdkmsClient) -> Result<Result<O::Output>> {
let result = sdkms.get_approval_request_result(&self.0)?;
Ok(if result.is_ok() {
serde_json::from_value::<O::Output>(result.body).map_err(Error::EncoderError)
} else {
let msg: String = serde_json::from_value(result.body).map_err(Error::EncoderError)?;
Err(Error::from_status(
StatusCode::from_u16(result.status).unwrap(),
msg,
))
})
}
}
impl<O: Operation> Clone for PendingApproval<O> {
fn clone(&self) -> Self {
PendingApproval(self.0, PhantomData)
}
}
fn now() -> Time {
Time(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("Invalid system time")
.as_secs(),
)
}
fn json_decode_reader<R: Read, T: for<'de> Deserialize<'de>>(rdr: &mut R) -> serde_json::Result<T> {
match serde_json::from_reader(rdr) {
Err(ref e) if e.is_eof() && e.line() == 1 && e.column() == 0 => {
serde_json::from_value(serde_json::Value::Null)
}
v => v,
}
}
fn json_request_with_auth<E, D>(
client: &HttpClient,
api_endpoint: &str,
method: Method,
path: &str,
auth: Option<&Auth>,
body: Option<&E>,
) -> Result<D>
where
E: Serialize,
D: for<'de> Deserialize<'de>,
{
let url = format!("{}{}", api_endpoint, path);
let mut req = client.request(method.clone(), &url)?;
let mut headers = HeaderMap::new();
if let Some(auth) = auth {
headers.insert(AUTHORIZATION, auth.format_header());
}
if let Some(request_body) = body {
headers.typed_insert(ContentType::json());
let body = serde_json::to_string(request_body).map_err(Error::EncoderError)?;
req = req.body(body);
}
req = req.headers(headers);
match req.send() {
Err(e) => {
info!("Error {} {}", method, url);
Err(Error::NetworkError(e))
}
Ok(ref mut res) if res.status().is_success() => {
info!("{} {} {}", res.status().as_u16(), method, url);
json_decode_reader(res.body_mut()).map_err(|err| Error::EncoderError(err))
}
Ok(ref mut res) => {
info!("{} {} {}", res.status().as_u16(), method, url);
let mut buffer = String::new();
res.body_mut()
.read_to_string(&mut buffer)
.map_err(|err| Error::IoError(err))?;
Err(Error::from_status(res.status(), buffer))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}
#[test]
fn client_is_send_and_sync() {
assert_send::<SdkmsClient>();
assert_sync::<SdkmsClient>();
assert_send::<SdkmsClientBuilder>();
assert_sync::<SdkmsClientBuilder>();
}
}