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
use std::convert::From;
use std::fmt;
use std::str::FromStr;
use reqwest::header::{self, Scheme};
use {Error, ErrorKind, Result};
static FULL_PREFIX: &'static str = "ExtraHop apikey=";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiKey(String);
impl ApiKey {
pub fn new<S: Into<String>>(key: S) -> Self {
ApiKey(key.into().trim().to_string())
}
pub fn to_header(self) -> header::Authorization<ApiKey> {
header::Authorization(self)
}
}
impl Scheme for ApiKey {
fn scheme() -> Option<&'static str> {
Some(&FULL_PREFIX[..8])
}
fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}{}", &FULL_PREFIX[9..], self.0)
}
}
impl From<String> for ApiKey {
fn from(v: String) -> Self {
ApiKey::new(v.to_string())
}
}
impl<'a> From<&'a str> for ApiKey {
fn from(v: &str) -> Self {
ApiKey::new(v.to_string())
}
}
impl From<ApiKey> for header::Authorization<ApiKey> {
fn from(v: ApiKey) -> Self {
v.to_header()
}
}
impl FromStr for ApiKey {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
if s.starts_with(FULL_PREFIX) {
Ok(ApiKey::new(s.trim_left_matches(FULL_PREFIX)))
} else {
Err(ErrorKind::ApiKeyParseError.into())
}
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use ErrorKind;
use super::ApiKey;
#[test]
fn parse_header() {
let full_header = "ExtraHop apikey=1a2b3c4d5e";
let parsed = full_header.parse().expect("Parsing should handle a well-formed header body");
assert_eq!(ApiKey::new("1a2b3c4d5e"), parsed);
}
#[test]
fn parse_error() {
let bare_key = "1a2b3c4d5e";
let parse_err = ApiKey::from_str(bare_key).unwrap_err();
if let ErrorKind::ApiKeyParseError = *parse_err.kind() {
println!("{}", parse_err);
} else {
panic!("Error should have been an API key parse failure");
}
}
}