vigor_agent 0.1.8

Client library for Vigor servers.
Documentation
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
#![deny(missing_docs,
    missing_debug_implementations, missing_copy_implementations,
    trivial_casts, trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces, unused_qualifications)]

//! # Vigor
//! This library contains a Vigor authentication agent to manage credentials and perform HTTP/HTTPS requests.
//!
//! A note regarding Ed25519: this client library supports Ed25519 authentication, however will only accept PEM-encoded keys.
//! Formats such as OpenSSH are not guaranteed to work.
//! The private key is expected to adhere to RFC 7468, PKCS8 and unencrypted.
//!
//! Minimal format verification is done on private key material. For all intended purposes, assume the library would foolishly accept random noise as a private key.
//! You are responsible for implementing safety checks for inappropriate private keys.
//!
//! Also keep in mind that this library is purely synchronous, for the purposes of simplicity and a less bloated dependency tree.
//! For use cases where blocking execution is inappropriate and/or inadaquete, it should be noted that synchronous code can be executed asynchronously, however not vice versa.
//! If all else fails, the rhetorical question "have you tried threading" should come to mind.
//!
//! ## Usage
//! Use `Vigor::new()` to start an agent instance, after importing.
//! See documentation for a full list of available methods.
//!
//! ```no_run
//! use vigor_agent;
//!
//! fn main() {
//!     // you're advised to apply error handling here, instead of just recklessly using .unwrap()
//!     let mut agent = vigor_agent::Vigor::new().unwrap();
//!     agent.init().unwrap();
//!     println!(agent.get("http://example.com/claims/", vigor_agent::AuthMode::Auto).unwrap());
//! }
//! ```
//!

use std::{fs, fmt, path::PathBuf, error};

extern crate dirs;
extern crate serde;
extern crate ureq;
extern crate pem_rfc7468;
extern crate ed25519_dalek;
extern crate hex;
use dirs::home_dir;
use ed25519_dalek::Signer;

/// Defines various kinds of errors, adding context to failures.
#[derive(Debug, Clone, Copy)]
pub enum ErrorKinds {
    /// Something attempted was fundamentally illegal due to being impossible to satisfy, or certain to fail.
    IllegalOperation,
    /// The provided Ed25519 private key is not valid and/or could not be loaded.
    InvalidKey,
    /// Could not find the user's home directory, and thus cannot access agent configuration.
    MissingHome,
    /// Unable to access or (de)serialize configuration file, despite knowing path.
    ConfigurationInaccessible,
    /// Request to Vigor server failed.
    RequestFailed,
    /// Structure of JSON response from Vigor server is invalid.
    ResponseInvalid,
    /// Unable to access either the provided Ed25519 private or public key.
    KeyInaccessible,
    /// Signature creation with the provided Ed25519 private key failed.
    SignatureFailed,
    /// `vigor_agent::AuthMode::Auto` was specified, and no available authentication mode could be resolved.
    /// At least one authentication mode is required to authenticate.
    AuthModeUnresolved
}

impl fmt::Display for ErrorKinds {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// This library's vender-specific error type.
///
/// The `kind` method provides `match`-able context to the error.
#[derive(Debug, Clone)]
pub struct Error {
    message: String,
    kind: ErrorKinds
}

impl Error {
    fn new(msg: &str, kind: ErrorKinds) -> Error {
        Error {
            message: msg.to_owned(),
            kind: kind
        }
    }

    /// Returns error's inner kind.
    ///
    /// Useful for case matching, to decide how to recover from a `vigor_agent::Error`.
    pub fn kind(&self) -> ErrorKinds {
        return self.kind;
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}. {}", self.kind, self.message)
    }
}

impl error::Error for Error {}

/// Configuration structure for Ed25519 authentication, used in `ConfigSchema` structures.
///
/// Can be used in serializing and deserializing configuration data, especially those residing inside `ConfigSchema` structures.
///
/// **This is not the main agent structure.** See `Vigor` instead, your agent is in another castle.
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct ConfigEd25519Schema {
    /// Path to the Ed25519 public key.
    pub public: String,
    /// Path to the Ed25519 private key.
    pub private: String,
    /// Whether Ed25519 authentication should be used.
    pub enabled: bool
}

/// Configuration structure, used in `Vigor` structures.
///
/// Can be used in serializing and deserializing configuration data, especially those residing inside `Vigor` structures.
///
/// **This is not the main agent structure.** See `Vigor` instead, your agent is in another castle.
#[derive(serde::Serialize, serde::Deserialize, Debug)]
pub struct ConfigSchema {
    /// User's name.
    pub preferred_username: String,
    /// User's email.
    pub email: String,
    /// Plain-text password, if empty password authentication will not be used.
    pub password: String,
    /// Ed25519 authentication configuration structure.
    pub ed25519: ConfigEd25519Schema
}

// definitions for transmission structs.
#[derive(serde::Serialize)]
struct Authentication {
    mode: String,
    answer: String
}

#[derive(serde::Deserialize)]
struct TokenResponse {
    jwt: String
}

#[derive(serde::Deserialize)]
struct ErrorResponse {
    error: String
}

/// Configuration and path information for agent structure. Includes implementations for agent logic.
///
/// Consume implemented methods for initialization, see `new` method.
pub struct Vigor {
    /// Configuration structure.
    pub config: ConfigSchema,
    /// Path to configuration file.
    pub path: PathBuf
}

impl fmt::Debug for Vigor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "path: \"{}\"", self.path.display().to_string())
    }
}

/// Represents mode to perform token retrieval with, specifically the authentication method.
///
/// The modes enumerated are to be passed onto agent methods that retrieve tokens, as arguments.
#[derive(Debug, Copy, Clone)]
pub enum AuthMode {
    /// Instruction to use Ed25519 key signatures to authenticate.
    Ed25519,
    /// Instruction to use password to authenticate.
    Password,
    /// Instruction to automatically select mode, by the following order.
    ///
    /// 1. Ed25519
    /// 2. Password
    ///
    /// If a mode is not available, the next mode will be used.
    Auto
}

impl Vigor {
    fn get_config_path() -> Result<PathBuf, Error> {
        match home_dir() {
            Some(mut home) => {
                home.push(".vigor");
                home.set_extension("conf");
                Ok(home)
            },
            None => Err(Error::new("Failed to get user's home directory for Vigor configuration file.", ErrorKinds::MissingHome))
        }
    }

    /// Reads configuration from disk.
    /// Does not check to see if path to configuration file exists.
    pub fn read(&mut self) -> Result<(), Error> {
        match fs::read_to_string(&self.path) {
            Ok(data) => {
                let output: Result<ConfigSchema, serde_json::Error> = serde_json::from_str(&data);
                match output {
                    Ok(config) => {
                        self.config = config;
                        Ok(())
                    },
                    Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::ConfigurationInaccessible))
                }
            },
            Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::ConfigurationInaccessible))
        }
    }

    /// Writes configuration to disk.
    pub fn write(&self) -> Result<(), Error> {
        match fs::write(&self.path, serde_json::to_string(&self.config).unwrap()) {
            Ok(_) => {
                Ok(())
            },
            Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::ConfigurationInaccessible))
        }
    }

    /// Runs initialization for Vigor agent.
    ///
    /// If configuration does not exist, `write` method is called.
    /// If configuration does exist, `read` method is called.
    pub fn init(&mut self) -> Result<(), Error> {
        if !self.path.exists() {
            match Vigor::write(self) {
                Ok(_) => Ok(()),
                Err(error) => Err(error)
            }
        } else {
            match Vigor::read(self) {
                Ok(_) => Ok(()),
                Err(error) => Err(error)
            }
        }
    }

    /// Creates a new `Vigor` agent.
    ///
    /// The default configuration structure as JSON appears as follows:
    ///
    /// ```text
    /// {
    ///     "preferred_username": "nobody",
    ///     "email": "nobody@localhost",
    ///     "password": "hunter2",
    ///     "ed25519": {
    ///         "public": "/path/to/your/keys/vigor.pem.pub",
    ///         "private": "/path/to/your/keys/vigor.pem",
    ///         "enabled": false
    ///     }
    /// }
    /// ```
    ///
    /// # Examples
    ///
    /// To initialize a new instance:
    ///
    /// ```no_run
    /// let mut agent = vigor_agent::Vigor::new().unwrap();
    /// agent.init().unwrap();
    /// ```
    pub fn new() -> Result<Vigor, Error> {
        match Vigor::get_config_path() {
            Ok(config_path) => {
                Ok(Vigor {
                    config: ConfigSchema {
                        preferred_username: "nobody".to_owned(),
                        email: "nobody@localhost".to_owned(),
                        password: "hunter2".to_owned(), // i'm not funny.
                        ed25519: ConfigEd25519Schema {
                            public: "/path/to/your/keys/vigor.pem.pub".to_owned(),
                            private: "/path/to/your/keys/vigor.pem".to_owned(),
                            enabled: false
                        }
                    },
                    path: config_path
                })
            },
            Err(error) => Err(error)
        }
    }

    fn host_finalize(&self, host: &str) -> String {
        let mut url = PathBuf::from(host);
        url.push(&self.config.preferred_username);
        url.display().to_string()
    }

    fn process_request_response(response: Result<ureq::Response, ureq::Error>) -> Result<ureq::Response, Error> {
        match response {
            Ok(response) => Ok(response),
            Err(ureq::Error::Status(code, response)) => {
                match response.into_json::<ErrorResponse>() {
                    Ok(payload) => {
                        Err(Error::new(&format!("Code {}. {}", code.to_string(), payload.error), ErrorKinds::RequestFailed))
                    },
                    Err(error) => Err(Error::new(&format!("Code {}. Response invalid, unable to decode further details for cause of error. {}", code.to_string(), error.to_string()), ErrorKinds::ResponseInvalid))
                }
            }
            Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::RequestFailed))
        }
    }

    fn form_account_payload(&self, share_email: bool, use_password: bool, use_ed25519: bool) -> Result<serde_json::Map<String, serde_json::Value>, Error> {
        let mut payload = serde_json::Map::new();
        if share_email {
            payload.insert("email".to_owned(), serde_json::Value::String(self.config.email.to_owned()));
        }
        if use_password {
            match Vigor::get_authentication_password(self) {
                Ok(password) => {
                    payload.insert("password".to_owned(), serde_json::Value::String(password));
                },
                Err(error) => {
                    return Err(error);
                }
            }
        }
        if use_ed25519 {
            match fs::read_to_string(&self.config.ed25519.public) {
                Ok(data) => {
                    payload.insert("ed25519key".to_owned(), serde_json::Value::String(data));
                }
                Err(error) => {
                    return Err(Error::new(&error.to_string(), ErrorKinds::KeyInaccessible))
                }
            }
        }
        Ok(payload)
    }

    /// Performs account creation to a Vigor host.
    ///
    /// This method expects three booleans after the host argument for whether email, password, and/or Ed25519 should be shared, respectively.
    /// At least one authentication method must be shared.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # let mut agent = vigor_agent::Vigor::new().unwrap();
    /// # agent.init().unwrap();
    /// // assuming you already have an instance called "agent"
    /// agent.put("http://example.com/claims/", true, true, true).unwrap();
    /// ```
    pub fn put(&self, host: &str, share_email: bool, use_password: bool, use_ed25519: bool) -> Result<(), Error> {
        if !use_password && !use_ed25519 {
            return Err(Error::new("At least one authentication method must exist on the new account.", ErrorKinds::IllegalOperation))
        }
        match Vigor::form_account_payload(self, share_email, use_password, use_ed25519) {
            Ok(payload) => {
                match Vigor::process_request_response(ureq::put(&Vigor::host_finalize(self, &host)).send_json(payload)) {
                    Ok(_) => Ok(()),
                    Err(error) => Err(error)
                }
            },
            Err(error) => Err(error)
        }
    }

    fn get_authentication_ed25519(&self) -> Result<String, Error> {
        match fs::read_to_string(&self.config.ed25519.private) {
            Ok(data) => {
                match pem_rfc7468::decode_vec(data.as_bytes()) {
                    Ok(data) => {
                        let raw = data.1;
                        if raw.len() < 32  {
                            return Err(Error::new("Ed25519 private key is not at least 32 bytes.", ErrorKinds::InvalidKey));
                        }
                        let key_as_bytes = &raw[(raw.len() - 32)..]; // drop excess bytes (i.e. ID bytes)
                        match ed25519_dalek::SecretKey::from_bytes(&key_as_bytes) {
                            Ok(secret_key) => {
                                let public_key: ed25519_dalek::PublicKey = (&secret_key).into();
                                let keypair = ed25519_dalek::Keypair {public: public_key, secret: secret_key};
                                match keypair.try_sign("SIGNME".as_bytes()) {
                                    Ok(signature) => {
                                        Ok(hex::encode(signature.to_bytes()))
                                    },
                                    Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::SignatureFailed))
                                }
                            },
                            Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::InvalidKey))
                        }
                    },
                    Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::InvalidKey))
                }
            }
            Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::KeyInaccessible))
        }
    }

    fn get_authentication_password(&self) -> Result<String, Error> {
        if self.config.password.is_empty() {
            return Err(Error::new("Password cannot be of zero length.", ErrorKinds::IllegalOperation))
        } else {
            return Ok(self.config.password.to_owned())
        }
    }

    fn form_authentication_ed25519(&self) -> Result<Authentication, Error> {
        match Vigor::get_authentication_ed25519(self) {
            Ok(answer) => {
                Ok(Authentication {mode: "ed25519".to_owned(), answer: answer})
            },
            Err(error) => Err(error)
        }
    }

    fn form_authentication_password(&self) -> Result<Authentication, Error> {
        match Vigor::get_authentication_password(self) {
            Ok(answer) => {
                Ok(Authentication {mode: "password".to_owned(), answer: answer})
            },
            Err(error) => Err(error)
        }
    }

    fn form_authentication(&self, mode: AuthMode) -> Result<Authentication, Error> {
        match mode {
            AuthMode::Ed25519 => {
                Vigor::form_authentication_ed25519(self)
            },
            AuthMode::Password => {
                Vigor::form_authentication_password(self)
            },
            AuthMode::Auto => {
                if self.config.ed25519.enabled {
                    match Vigor::form_authentication_ed25519(self) {
                        Ok(payload) => {
                            return Ok(payload)
                        },
                        Err(_) => {}
                    };
                }
                match Vigor::form_authentication_password(self) {
                    Ok(payload) => {
                        return Ok(payload)
                    },
                    Err(_) => {
                        return Err(Error::new("No authentication modes available that aren't disabled or erroneous.", ErrorKinds::AuthModeUnresolved));
                    }
                };
            }
        }
    }

    /// Performs token retrieval to a Vigor host.
    ///
    /// # Examples
    /// ```no_run
    /// # let mut agent = vigor_agent::Vigor::new().unwrap();
    /// # agent.init().unwrap();
    /// // assuming you already have an instance called "agent"
    /// agent.get("http://example.com/claims/", vigor_agent::AuthMode::Auto).unwrap();
    /// ```
    pub fn get(&self, host: &str, mode: AuthMode) -> Result<String, Error> {
        match Vigor::form_authentication(self, mode) {
            Ok(payload) => {
                match Vigor::process_request_response(ureq::get(&Vigor::host_finalize(self, &host)).send_json(payload)) {
                    Ok(response) => {
                        match response.into_json::<TokenResponse>() {
                            Ok(payload) => Ok(payload.jwt),
                            Err(error) => Err(Error::new(&error.to_string(), ErrorKinds::ResponseInvalid))
                        }
                    },
                    Err(error) => Err(error)
                }
            },
            Err(error) => Err(error)
        }
    }


    /// Performs account deletion to a Vigor host.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # let mut agent = vigor_agent::Vigor::new().unwrap();
    /// # agent.init().unwrap();
    /// // assuming you already have an instance called "agent"
    /// agent.delete("http://example.com/claims/", vigor_agent::AuthMode::Auto).unwrap();
    /// ```
    pub fn delete(&self, host: &str, mode: AuthMode) -> Result<(), Error> {
        match Vigor::form_authentication(self, mode) {
            Ok(payload) => {
                match Vigor::process_request_response(ureq::delete(&Vigor::host_finalize(self, &host)).send_json(payload)) {
                    Ok(_) => Ok(()),
                    Err(error) => Err(error)
                }
            },
            Err(error) => Err(error)
        }
    }

    /// Performs account modification to a Vigor host.
    ///
    /// This method expects three booleans after the host argument for whether email, password, and/or Ed25519 should be updated, respectively.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # let mut agent = vigor_agent::Vigor::new().unwrap();
    /// # agent.init().unwrap();
    /// // assuming you already have an instance called "agent"
    /// agent.patch("http://example.com/claims/", vigor_agent::AuthMode::Auto, true, true, true).unwrap();
    /// ```
    pub fn patch(&self, host: &str, mode: AuthMode, share_email: bool, use_password: bool, use_ed25519: bool) -> Result<(), Error> {
        if !share_email && !use_password && !use_ed25519 {
            return Err(Error::new("At least one account property needs to be updated.", ErrorKinds::IllegalOperation));
        }
        match Vigor::form_authentication(self, mode) {
            Ok(payload) => {
                let mut payload_mod: serde_json::Map<String, serde_json::Value> = serde_json::to_value(payload).unwrap().as_object().unwrap().clone();
                match Vigor::form_account_payload(self, share_email, use_password, use_ed25519) {
                    Ok(changes) => {
                        payload_mod.insert("new".to_string(), serde_json::Value::Object(changes));
                        match Vigor::process_request_response(ureq::patch(&Vigor::host_finalize(self, &host)).send_json(&payload_mod)) {
                            Ok(_) => Ok(()),
                            Err(error) => Err(error)
                        }
                    },
                    Err(error) => Err(error)
                }
            },
            Err(error) => Err(error)
        }
    }
}