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
use errors::*;
use regex::{Captures, Regex};
use std::collections::{btree_map, BTreeMap};
use std::env;
use std::fs::File;
use std::iter::Iterator;
use std::io::{self, BufRead};
use std::path::Path;
fn interpolate_env(text: &str) -> Result<String> {
lazy_static! {
static ref RE: Regex =
Regex::new(r"(?x)
\$(?:
(?P<name>[a-zA-Z_][a-zA-Z0-9_]*)
|
\{(?P<name2>[a-zA-Z_][a-zA-Z0-9_]*)\}
)").unwrap();
}
let mut undefined_env_var = None;
let result = RE.replace_all(text, |caps: &Captures| {
let name = caps.name("name").or_else(|| caps.name("name2"))
.unwrap()
.as_str();
match env::var(name) {
Ok(s) => s.to_owned(),
Err(_) => {
undefined_env_var = Some(name.to_owned());
"".to_owned()
}
}
});
match undefined_env_var {
None => Ok(result.into_owned()),
Some(var) => Err(ErrorKind::UndefinedEnvironmentVariable(var).into()),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Location {
Path(String),
PathWithKey(String, String),
}
impl Location {
fn from_caps<'a>(caps: &Captures<'a>) -> Result<Location> {
let path_opt = caps.name("path").map(|m| m.as_str());
let key_opt = caps.name("key").map(|m| m.as_str());
match (path_opt, key_opt) {
(Some(path), None) => Ok(Location::Path(interpolate_env(path)?)),
(Some(path), Some(key)) => {
Ok(Location::PathWithKey(interpolate_env(path)?, key.to_owned()))
}
(_, _) => {
let all = caps.get(0).unwrap().as_str().to_owned();
Err(ErrorKind::Parse(all).into())
}
}
}
}
#[derive(Debug, Clone)]
pub struct Secretfile {
varmap: BTreeMap<String, Location>,
filemap: BTreeMap<String, Location>,
}
impl Secretfile {
fn read_internal(read: &mut io::Read) -> Result<Secretfile> {
lazy_static! {
static ref RE: Regex = Regex::new(r"(?x)
^(?:
# Blank line with optional comment.
\s*(?:\#.*)?
|
(?:
# VAR
(?P<var>[a-zA-Z_][a-zA-Z0-9_]*)
|
# >file
>(?P<file>\S+)
)
\s+
# path/to/secret:key
(?P<path>\S+?)(?::(?P<key>\S+))?
\s*
)$").unwrap();
}
let mut sf = Secretfile {
varmap: BTreeMap::new(),
filemap: BTreeMap::new(),
};
let buffer = io::BufReader::new(read);
for line_or_err in buffer.lines() {
let line = line_or_err?;
match RE.captures(&line) {
Some(ref caps) if caps.name("path").is_some() => {
let location = Location::from_caps(caps)?;
if caps.name("file").is_some() {
let file =
interpolate_env(caps.name("file").unwrap().as_str())?;
sf.filemap.insert(file, location);
} else if caps.name("var").is_some() {
let var = caps.name("var").unwrap().as_str().to_owned();
sf.varmap.insert(var, location);
}
}
Some(_) => {
}
_ => return Err(ErrorKind::Parse(line.to_owned()).into()),
}
}
Ok(sf)
}
pub fn read(read: &mut io::Read) -> Result<Secretfile> {
Secretfile::read_internal(read).chain_err(|| ErrorKind::Secretfile)
}
pub fn from_str<S: AsRef<str>>(s: S) -> Result<Secretfile> {
let mut cursor = io::Cursor::new(s.as_ref().as_bytes());
Secretfile::read(&mut cursor)
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Secretfile> {
let path = path.as_ref();
let mkerr = || ErrorKind::FileRead(path.to_owned());
let mut file = File::open(path).chain_err(&mkerr)?;
Secretfile::read(&mut file).chain_err(&mkerr)
}
pub fn default() -> Result<Secretfile> {
let mut path = env::current_dir().chain_err(|| ErrorKind::Secretfile)?;
path.push("Secretfile");
Secretfile::from_path(path)
}
pub fn vars(&self) -> SecretfileKeys {
SecretfileKeys { keys: self.varmap.keys() }
}
pub fn files(&self) -> SecretfileKeys {
SecretfileKeys { keys: self.filemap.keys() }
}
}
pub trait SecretfileLookup {
fn var(&self, name: &str) -> Option<&Location>;
fn file(&self, name: &str) -> Option<&Location>;
}
impl SecretfileLookup for Secretfile {
fn var(&self, name: &str) -> Option<&Location> {
self.varmap.get(name)
}
fn file(&self, name: &str) -> Option<&Location> {
self.filemap.get(name)
}
}
#[derive(Clone)]
pub struct SecretfileKeys<'a> {
keys: btree_map::Keys<'a, String, Location>,
}
impl<'a> Iterator for SecretfileKeys<'a> {
type Item = &'a String;
fn next(&mut self) -> Option<&'a String> {
self.keys.next()
}
}
#[test]
fn test_parse() {
let data = "\
# This is a comment.
FOO_USERNAME secret/$SECRET_NAME:username\n\
FOO_PASSWORD secret/${SECRET_NAME}:password\n\
# Try a Keywhiz-style secret, too.
FOO_USERNAME2 ${SECRET_NAME}_username\n\
# Credentials to copy to a file. Interpolation allowed on the left here.
>$SOMEDIR/.conf/key.pem secret/ssl:key_pem\n\
";
env::set_var("SECRET_NAME", "foo");
env::set_var("SOMEDIR", "/home/foo");
let secretfile = Secretfile::from_str(data).unwrap();
assert_eq!(&Location::PathWithKey("secret/foo".to_owned(), "username".to_owned()),
secretfile.var("FOO_USERNAME").unwrap());
assert_eq!(&Location::PathWithKey("secret/foo".to_owned(), "password".to_owned()),
secretfile.var("FOO_PASSWORD").unwrap());
assert_eq!(&Location::Path("foo_username".to_owned()),
secretfile.var("FOO_USERNAME2").unwrap());
assert_eq!(&Location::PathWithKey("secret/ssl".to_owned(), "key_pem".to_owned()),
secretfile.file("/home/foo/.conf/key.pem").unwrap());
assert_eq!(vec!["FOO_PASSWORD", "FOO_USERNAME", "FOO_USERNAME2"],
secretfile.vars().collect::<Vec<_>>());
assert_eq!(vec!["/home/foo/.conf/key.pem"],
secretfile.files().collect::<Vec<_>>());
}