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
use std::{
fmt::{Debug, Display},
marker::PhantomData,
path::PathBuf,
};
use coins_bip39::{Mnemonic, Wordlist};
use k256::SecretKey;
use schemars::JsonSchema;
use secrecy::{ExposeSecret, SecretString};
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};
use url::Url;
use crate::{interpolation::try_interpolate, ConfigError, Result};
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
#[serde(deny_unknown_fields)]
pub(crate) enum SecretKind {
EnvVar {
env: String,
},
File {
file: PathBuf,
},
PlainText {
#[serde(serialize_with = "ser_secret", deserialize_with = "de_secret")]
#[schemars(with = "String")]
secret: SecretString,
},
}
pub(crate) const CUBIST_REDACTED: &str = "***CUBIST REDACTED SECRET***";
fn de_secret<'a, D>(deserializer: D) -> Result<SecretString, D::Error>
where
D: Deserializer<'a>,
{
let s = String::deserialize(deserializer)?;
Ok(SecretString::new(s))
}
fn ser_secret<S>(_key: &SecretString, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(CUBIST_REDACTED)
}
impl SecretKind {
pub fn load(&self) -> Result<SecretString> {
let sec = match self {
Self::PlainText { secret } => secret.clone(),
Self::EnvVar { env } => dotenv::var(&env)
.map_err(|e| ConfigError::SecretReadFromEnv(env.clone(), e))?
.into(),
Self::File { file } => std::fs::read_to_string(file)
.map_err(|e| ConfigError::SecretReadFromFile(file.clone(), e))?
.into(),
};
Ok(sec)
}
}
pub trait ValidateSecret<T> {
fn validate(val: &str) -> Option<String>;
}
#[derive(Clone, Debug, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Secret<T = String>
where
T: ValidateSecret<T>,
{
#[serde(flatten)]
pub(crate) inner: SecretKind,
#[serde(skip)]
phantom: PhantomData<T>,
}
impl<T: ValidateSecret<T>> Secret<T> {
fn new(inner: SecretKind) -> Self {
Self {
inner,
phantom: Default::default(),
}
}
pub fn load(&self) -> Result<SecretString> {
self.inner.load()
}
}
pub(crate) const INVALID_MNEMONIC_ERR: &str = "Invalid BIP39 mnemonic";
pub(crate) const INVALID_PRIVATE_KEY_HEX_ERR: &str =
"Invalid private key; expected hex string without leading '0x'";
pub(crate) const INVALID_PRIVATE_KEY_ERR: &str = "Invalid K-256 secret key";
impl ValidateSecret<String> for String {
fn validate(_val: &str) -> Option<String> {
None
}
}
impl ValidateSecret<SecretKey> for SecretKey {
fn validate(val: &str) -> Option<String> {
match hex::decode(val) {
Ok(decoded) => match SecretKey::from_be_bytes(&decoded) {
Ok(_) => None,
Err(e) => Some(format!("{INVALID_PRIVATE_KEY_ERR}: {e}")),
},
Err(e) => Some(format!("{INVALID_PRIVATE_KEY_HEX_ERR}: {e}")),
}
}
}
impl<T: Wordlist> ValidateSecret<Mnemonic<T>> for Mnemonic<T> {
fn validate(val: &str) -> Option<String> {
match Mnemonic::<T>::new_from_phrase(val) {
Ok(_) => None,
Err(e) => Some(format!("{INVALID_MNEMONIC_ERR}: {e}")),
}
}
}
impl<'de, T: ValidateSecret<T>> Deserialize<'de> for Secret<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let inner: SecretKind = SecretKind::deserialize(deserializer)?;
match inner.load() {
Ok(val) => match T::validate(val.expose_secret()) {
None => Ok(Secret::new(inner)),
Some(e) => Err(Error::custom(e)),
},
Err(_) => Ok(Secret::new(inner)),
}
}
}
impl<T: ValidateSecret<T>> JsonSchema for Secret<T> {
fn schema_name() -> String {
<SecretKind as JsonSchema>::schema_name()
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
<SecretKind as JsonSchema>::json_schema(gen)
}
}
impl<T: ValidateSecret<T>> From<SecretKind> for Secret<T> {
fn from(s: SecretKind) -> Self {
Self {
inner: s,
phantom: Default::default(),
}
}
}
impl From<String> for SecretKind {
fn from(s: String) -> Self {
SecretKind::PlainText {
secret: SecretString::new(s),
}
}
}
impl<T: ValidateSecret<T>> From<String> for Secret<T> {
fn from(s: String) -> Self {
SecretKind::from(s).into()
}
}
#[derive(Clone, Debug)]
pub struct SecretUrl {
url: Url,
}
impl Display for SecretUrl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let url_str = self.url.to_string();
let decoded = percent_encoding::percent_decode_str(&url_str).decode_utf8_lossy();
Display::fmt(&decoded, f)
}
}
impl From<Url> for SecretUrl {
fn from(url: Url) -> Self {
Self { url }
}
}
impl TryFrom<&str> for SecretUrl {
type Error = url::ParseError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Ok(Url::parse(value)?.into())
}
}
impl SecretUrl {
pub fn port(&self) -> Option<u16> {
self.url.port()
}
pub fn load(&self) -> Result<SecretString> {
let ustr = self.url.as_str();
let percent_decode = true;
try_interpolate(ustr, percent_decode)
}
pub fn scheme(&self) -> &str {
self.url.scheme()
}
pub fn expose_url(&self) -> Result<Url> {
self.expose_url_and_update(None, None, None)
}
pub fn expose_url_and_update(
&self,
set_scheme: Option<&str>,
set_port: Option<u16>,
set_path: Option<&str>,
) -> Result<Url> {
let secret = self.load()?;
let mut exposed = Url::parse(secret.expose_secret())
.map_err(|_| ConfigError::UrlInterpolate(self.url.to_string()))?;
if let Some(scheme) = set_scheme {
exposed
.set_scheme(scheme)
.map_err(|_| ConfigError::UrlInvalidScheme(scheme.to_owned()))?;
}
if set_port.is_some() {
exposed.set_port(set_port).expect("Invalid port number");
}
if let Some(path) = set_path {
exposed.set_path(path);
}
Ok(exposed)
}
}
impl<'de> Deserialize<'de> for SecretUrl {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let url = url::Url::deserialize(deserializer)
.map_err(|e| serde::de::Error::custom(format!("{e}")))?;
Ok(Self { url })
}
}
impl Serialize for SecretUrl {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.url.serialize(serializer)
}
}
impl JsonSchema for SecretUrl {
fn schema_name() -> String {
<url::Url as JsonSchema>::schema_name()
}
fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
<url::Url as JsonSchema>::json_schema(gen)
}
}
#[cfg(test)]
mod test {
use crate::secret::{SecretKind, CUBIST_REDACTED};
use super::Secret;
use secrecy::ExposeSecret;
use serde_json::json;
#[test]
fn test_secret_debug() {
let val = "qwerty";
let sec: SecretKind = val.to_string().into();
assert!(matches!(sec, SecretKind::PlainText { .. }));
let dbg = format!("{sec:?}");
assert!(!dbg.contains(val));
assert_eq!(
"PlainText { secret: Secret([REDACTED alloc::string::String]) }",
dbg
);
}
#[test]
fn test_secret_clone() {
let val = "qwerty";
let sec1: SecretKind = val.to_string().into();
assert!(matches!(sec1, SecretKind::PlainText { .. }));
let sec2 = sec1.clone();
let loaded1 = sec1.load().unwrap();
let loaded2 = sec2.load().unwrap();
assert_eq!(loaded1.expose_secret(), loaded2.expose_secret());
assert_eq!(val, loaded2.expose_secret());
}
#[test]
fn load_secret_from_plain_text() {
let val = "qwerty";
let sec: SecretKind = val.to_string().into();
assert!(matches!(sec, SecretKind::PlainText { .. }));
let loaded = sec.load().unwrap();
assert_eq!(val, loaded.expose_secret());
}
#[test]
fn load_secret_from_env_var() {
let env_var = "load_secret_from_env_var_test";
let sec = SecretKind::EnvVar {
env: env_var.into(),
};
let val = "qwerty";
std::env::set_var(env_var, val);
let loaded = sec.load().unwrap();
assert_eq!(val, loaded.expose_secret());
}
#[test]
fn load_secret_from_file() {
let tmp = tempfile::tempdir().unwrap();
let file = tmp.path().join("test");
let val = "qwerty";
std::fs::write(&file, val).unwrap();
let sec = SecretKind::File { file };
let loaded = sec.load().unwrap();
assert_eq!(val, loaded.expose_secret());
}
#[test]
fn secret_serde() {
let val = "qwerty";
let json = json!({ "secret": val });
let sec: Secret = serde_json::from_value(json).unwrap();
let loaded = sec.load().unwrap();
assert_eq!(val, loaded.expose_secret());
let ser: serde_json::Value = serde_json::to_value(&sec).unwrap();
let secret_val = ser.get("secret").unwrap();
assert!(!secret_val.to_string().contains(val));
assert_eq!(&json!(CUBIST_REDACTED), secret_val);
}
}