-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathconfig.rs
More file actions
418 lines (382 loc) · 13.1 KB
/
Copy pathconfig.rs
File metadata and controls
418 lines (382 loc) · 13.1 KB
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
use std::env;
use thiserror::Error;
use url::Url;
use crate::module::network::{network_from_env, validate_horizon_url};
/// Deployment environment. Controls log output format: JSON in production,
/// human-readable in development. Unrecognized values default to development.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Environment {
Development,
Production,
}
impl Environment {
fn from_env_str(value: &str) -> Self {
match value.trim().to_ascii_lowercase().as_str() {
"production" | "prod" => Self::Production,
_ => Self::Development,
}
}
}
#[derive(Debug, Clone)]
pub struct AppConfig {
pub port: u16,
pub stellar_horizon_url: String,
pub stellar_secret_key: Option<String>,
pub redis_url: String,
pub rate_limit_per_second: u32,
pub rate_limit_burst: u32,
pub stellar_max_retries: u32,
pub log_level: String,
pub environment: Environment,
pub webhook_urls: Vec<String>,
pub webhook_secret: Option<String>,
pub cache_verification_ttl: u64,
pub shutdown_timeout_secs: u64,
}
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("configuration validation failed:\n{0}")]
Validation(String),
}
impl AppConfig {
pub fn from_env() -> Result<Self, ConfigError> {
let mut errors = Vec::new();
let node_env = env::var("NODE_ENV").unwrap_or_else(|_| "development".to_string());
let is_production = node_env == "production";
// List of placeholder values that are not allowed in production
let placeholders = [
"your-stellar-secret-key",
"your-webhook-secret",
"changeme",
"test123",
];
// Helper to read env var with default and check for placeholders in production
fn get_env_or_default(
key: &str,
default: &str,
is_production: bool,
errors: &mut Vec<String>,
placeholders: &[&str],
) -> String {
let value = env::var(key).unwrap_or_else(|_| default.to_string());
if is_production && placeholders.contains(&value.as_str()) {
errors.push(format!(
"{} contains a placeholder value '{}' - please set a real production value",
key, value
));
}
value
}
// Basic string values with defaults
let port_raw =
get_env_or_default("PORT", "8080", is_production, &mut errors, &placeholders);
let stellar_horizon_url = get_env_or_default(
"STELLAR_HORIZON_URL",
"https://horizon-testnet.stellar.org",
is_production,
&mut errors,
&placeholders,
);
let redis_url = get_env_or_default(
"REDIS_URL",
"redis://127.0.0.1:6379",
is_production,
&mut errors,
&placeholders,
);
let log_level = get_env_or_default(
"LOG_LEVEL",
"info",
is_production,
&mut errors,
&placeholders,
);
let environment = Environment::from_env_str(&get_env_or_default(
"APP_ENV",
"development",
is_production,
&mut errors,
&placeholders,
));
let webhook_urls_raw = get_env_or_default(
"WEBHOOK_URLS",
"",
is_production,
&mut errors,
&placeholders,
);
let stellar_secret_key = match env::var("STELLAR_SECRET_KEY") {
Ok(key) => {
// Validate the secret key format (should be 56 chars starting with 'S')
if key.len() != 56 || !key.starts_with('S') {
errors.push(
"STELLAR_SECRET_KEY must be a 56-character string starting with 'S'"
.to_string(),
);
}
// Check for placeholder values in production
if is_production && placeholders.contains(&key.as_str()) {
errors.push(format!(
"STELLAR_SECRET_KEY contains a placeholder value '{}' - please set a real production value",
key
));
}
Some(key)
}
Err(_) => {
errors.push(
"STELLAR_SECRET_KEY is required but not set. Please set the environment variable."
.to_string(),
);
None
}
};
let webhook_secret = env::var("WEBHOOK_SECRET").ok().and_then(|key| {
if is_production && placeholders.contains(&key.as_str()) {
errors.push(format!(
"WEBHOOK_SECRET contains a placeholder value '{}' - please set a real production value",
key
));
None
} else {
Some(key)
}
});
// Numeric values with defaults
let rate_limit_per_second_raw = get_env_or_default(
"RATE_LIMIT_PER_SECOND",
"10",
is_production,
&mut errors,
&placeholders,
);
let rate_limit_burst_raw = get_env_or_default(
"RATE_LIMIT_BURST",
&rate_limit_per_second_raw,
is_production,
&mut errors,
&placeholders,
);
let stellar_max_retries_raw = get_env_or_default(
"STELLAR_MAX_RETRIES",
"3",
is_production,
&mut errors,
&placeholders,
);
let cache_verification_ttl_raw = get_env_or_default(
"CACHE_VERIFICATION_TTL",
"3600",
is_production,
&mut errors,
&placeholders,
);
let shutdown_timeout_raw = get_env_or_default(
"SHUTDOWN_TIMEOUT_SECS",
"30",
is_production,
&mut errors,
&placeholders,
);
// Parse and validate port
let port: u16 = match port_raw.parse() {
Ok(p) if p > 0 => p,
Ok(_) => {
errors.push("PORT must be between 1 and 65535".to_string());
8080
}
Err(_) => {
errors.push(format!("PORT must be a valid u16, got '{}'", port_raw));
8080
}
};
// Validate horizon URL
if Url::parse(&stellar_horizon_url).is_err() {
errors.push(format!(
"STELLAR_HORIZON_URL must be a valid URL, got '{}'",
stellar_horizon_url
));
} else if let Err(error) = network_from_env()
.and_then(|network| validate_horizon_url(&network, &stellar_horizon_url))
{
errors.push(error);
}
// Parse numeric values
let rate_limit_per_second: u32 = match rate_limit_per_second_raw.parse() {
Ok(v) if v > 0 => v,
Ok(_) => {
errors.push("RATE_LIMIT_PER_SECOND must be greater than 0".to_string());
10
}
Err(_) => {
errors.push(format!(
"RATE_LIMIT_PER_SECOND must be a valid u32, got '{}'",
rate_limit_per_second_raw
));
10
}
};
let rate_limit_burst: u32 = match rate_limit_burst_raw.parse() {
Ok(v) => v,
Err(_) => {
errors.push(format!(
"RATE_LIMIT_BURST must be a valid u32, got '{}'",
rate_limit_burst_raw
));
rate_limit_per_second
}
};
let stellar_max_retries: u32 = match stellar_max_retries_raw.parse() {
Ok(v) => v,
Err(_) => {
errors.push(format!(
"STELLAR_MAX_RETRIES must be a valid u32, got '{}'",
stellar_max_retries_raw
));
3
}
};
let cache_verification_ttl: u64 = match cache_verification_ttl_raw.parse() {
Ok(v) => v,
Err(_) => {
errors.push(format!(
"CACHE_VERIFICATION_TTL must be a valid u64, got '{}'",
cache_verification_ttl_raw
));
3600
}
};
let shutdown_timeout_secs: u64 = match shutdown_timeout_raw.parse() {
Ok(v) if v > 0 => v,
Ok(_) => {
errors.push("SHUTDOWN_TIMEOUT_SECS must be greater than 0".to_string());
30
}
Err(_) => {
errors.push(format!(
"SHUTDOWN_TIMEOUT_SECS must be a valid u64, got '{}'",
shutdown_timeout_raw
));
30
}
};
// Parse webhook URLs (comma-separated, ignore empty)
let webhook_urls: Vec<String> = webhook_urls_raw
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(String::from)
.collect();
if !errors.is_empty() {
let joined = errors.join("\n- ");
return Err(ConfigError::Validation(format!("- {}", joined)));
}
Ok(Self {
port,
stellar_horizon_url,
stellar_secret_key,
redis_url,
rate_limit_per_second,
rate_limit_burst,
stellar_max_retries,
log_level,
environment,
webhook_urls,
webhook_secret,
cache_verification_ttl,
shutdown_timeout_secs,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
fn clear_env() {
let keys = [
"PORT",
"STELLAR_HORIZON_URL",
"STELLAR_NETWORK",
"STELLAR_SECRET_KEY",
"REDIS_URL",
"RATE_LIMIT_PER_SECOND",
"RATE_LIMIT_BURST",
"STELLAR_MAX_RETRIES",
"LOG_LEVEL",
"APP_ENV",
"WEBHOOK_URLS",
"WEBHOOK_SECRET",
"CACHE_VERIFICATION_TTL",
"SHUTDOWN_TIMEOUT_SECS",
];
for key in keys {
env::remove_var(key);
}
}
#[test]
fn from_env_uses_defaults_when_missing() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env();
env::set_var(
"STELLAR_SECRET_KEY",
"SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
);
let cfg = AppConfig::from_env().expect("config should load with defaults");
assert_eq!(cfg.port, 8080);
assert_eq!(
cfg.stellar_horizon_url,
"https://horizon-testnet.stellar.org"
);
assert_eq!(cfg.redis_url, "redis://127.0.0.1:6379");
assert_eq!(cfg.rate_limit_per_second, 10);
assert_eq!(cfg.cache_verification_ttl, 3600);
assert_eq!(cfg.shutdown_timeout_secs, 30);
}
#[test]
fn from_env_invalid_values_report_errors() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env();
env::set_var("PORT", "0");
env::set_var("STELLAR_HORIZON_URL", "not-a-url");
env::set_var("RATE_LIMIT_PER_SECOND", "0");
let err = AppConfig::from_env().expect_err("config should fail");
let msg = err.to_string();
assert!(msg.contains("PORT must be between 1 and 65535"));
assert!(msg.contains("STELLAR_HORIZON_URL must be a valid URL"));
assert!(msg.contains("RATE_LIMIT_PER_SECOND must be greater than 0"));
}
#[test]
fn from_env_rejects_network_horizon_mismatch() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env();
env::set_var("STELLAR_NETWORK", "mainnet");
env::set_var("STELLAR_HORIZON_URL", "https://horizon-testnet.stellar.org");
env::set_var(
"STELLAR_SECRET_KEY",
"SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
);
let error = AppConfig::from_env().expect_err("mismatched network should fail startup");
assert!(error.to_string().contains("does not match"));
}
#[test]
fn from_env_parses_valid_config() {
let _guard = ENV_LOCK.lock().unwrap();
clear_env();
env::set_var("PORT", "9090");
env::set_var("STELLAR_HORIZON_URL", "https://example.com");
env::set_var("REDIS_URL", "redis://redis:6379");
env::set_var("RATE_LIMIT_PER_SECOND", "100");
env::set_var("WEBHOOK_URLS", "https://a.com, https://b.com");
env::set_var(
"STELLAR_SECRET_KEY",
"SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
);
let cfg = AppConfig::from_env().expect("config should load");
assert_eq!(cfg.port, 9090);
assert_eq!(cfg.stellar_horizon_url, "https://example.com");
assert_eq!(cfg.redis_url, "redis://redis:6379");
assert_eq!(cfg.rate_limit_per_second, 100);
assert_eq!(cfg.webhook_urls.len(), 2);
}
}