-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathconfig.rs
More file actions
368 lines (312 loc) · 10.8 KB
/
Copy pathconfig.rs
File metadata and controls
368 lines (312 loc) · 10.8 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
//! Configuration management
//!
//! This module handles loading, saving, and migrating the rc configuration file.
//! The configuration file is stored in TOML format at ~/.config/rc/config.toml.
//!
//! PROTECTED FILE: Changes to schema_version require migration support.
use std::io::Write;
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use crate::alias::Alias;
use crate::error::{Error, Result};
/// Current configuration schema version
///
/// IMPORTANT: Bumping this version requires:
/// 1. Adding a migration in migrations/
/// 2. Updating migration tests
/// 3. Marking the change as BREAKING
pub const SCHEMA_VERSION: u32 = 1;
/// Default output format
const DEFAULT_OUTPUT: &str = "human";
/// Default color setting
const DEFAULT_COLOR: &str = "auto";
/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// Schema version for migration support
pub schema_version: u32,
/// Default settings
#[serde(default)]
pub defaults: Defaults,
/// Configured aliases
#[serde(default)]
pub aliases: Vec<Alias>,
}
/// Default settings for CLI behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Defaults {
/// Output format: "human" or "json"
#[serde(default = "default_output")]
pub output: String,
/// Color mode: "auto", "always", or "never"
#[serde(default = "default_color")]
pub color: String,
/// Show progress bars
#[serde(default = "default_true")]
pub progress: bool,
}
fn default_output() -> String {
DEFAULT_OUTPUT.to_string()
}
fn default_color() -> String {
DEFAULT_COLOR.to_string()
}
fn default_true() -> bool {
true
}
impl Default for Defaults {
fn default() -> Self {
Self {
output: default_output(),
color: default_color(),
progress: true,
}
}
}
impl Default for Config {
fn default() -> Self {
Self {
schema_version: SCHEMA_VERSION,
defaults: Defaults::default(),
aliases: Vec::new(),
}
}
}
/// Configuration manager handles loading and saving config
#[derive(Debug)]
pub struct ConfigManager {
config_path: PathBuf,
}
impl ConfigManager {
/// Create a new ConfigManager with the default config path
///
/// The config directory can be overridden by setting the `RC_CONFIG_DIR`
/// environment variable. This is useful for testing and containerized deployments.
pub fn new() -> Result<Self> {
let config_dir = if let Ok(dir) = std::env::var("RC_CONFIG_DIR") {
PathBuf::from(dir)
} else {
dirs::config_dir()
.ok_or_else(|| Error::Config("Could not determine config directory".into()))?
.join("rc")
};
let config_path = config_dir.join("config.toml");
Ok(Self { config_path })
}
/// Create a ConfigManager with a custom path (useful for testing)
pub fn with_path(path: PathBuf) -> Self {
Self { config_path: path }
}
/// Get the configuration file path
pub fn config_path(&self) -> &PathBuf {
&self.config_path
}
/// Load configuration from disk
///
/// If the configuration file doesn't exist, returns a default configuration.
/// If the schema version doesn't match, attempts migration.
pub fn load(&self) -> Result<Config> {
if !self.config_path.exists() {
return Ok(Config::default());
}
let content = std::fs::read_to_string(&self.config_path)?;
let mut config: Config = toml::from_str(&content)?;
// Check schema version and migrate if necessary
if config.schema_version < SCHEMA_VERSION {
config = self.migrate(config)?;
} else if config.schema_version > SCHEMA_VERSION {
return Err(Error::Config(format!(
"Configuration file version {} is newer than supported version {}. Please upgrade rc.",
config.schema_version, SCHEMA_VERSION
)));
}
Ok(config)
}
/// Save configuration to disk
///
/// Creates parent directories if they don't exist.
/// Sets Unix file permissions to 600 (owner read/write only) before writing.
pub fn save(&self, config: &Config) -> Result<()> {
// Ensure parent directory exists
if let Some(parent) = self.config_path.parent() {
std::fs::create_dir_all(parent)?;
}
let content = toml::to_string_pretty(config)?;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&self.config_path)?;
// Existing files keep their mode when opened, so protect the opened file
// before truncating or writing credentials, and stop if that fails.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
}
file.set_len(0)?;
file.write_all(content.as_bytes())?;
Ok(())
}
/// Migrate configuration from older schema version
fn migrate(&self, config: Config) -> Result<Config> {
let mut config = config;
// Add migration logic here when schema version is bumped
// Example:
// if config.schema_version == 1 {
// config = migrate_v1_to_v2(config)?;
// }
config.schema_version = SCHEMA_VERSION;
Ok(config)
}
}
impl Default for ConfigManager {
fn default() -> Self {
Self::new().expect("Failed to create default ConfigManager")
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
fn temp_config_manager() -> (ConfigManager, TempDir) {
let temp_dir = TempDir::new().unwrap();
let config_path = temp_dir.path().join("config.toml");
let manager = ConfigManager::with_path(config_path);
(manager, temp_dir)
}
#[test]
fn test_default_config() {
let config = Config::default();
assert_eq!(config.schema_version, SCHEMA_VERSION);
assert_eq!(config.defaults.output, "human");
assert_eq!(config.defaults.color, "auto");
assert!(config.defaults.progress);
assert!(config.aliases.is_empty());
}
#[test]
fn test_load_nonexistent_returns_default() {
let (manager, _temp_dir) = temp_config_manager();
let config = manager.load().unwrap();
assert_eq!(config.schema_version, SCHEMA_VERSION);
}
#[test]
fn test_save_and_load() {
let (manager, _temp_dir) = temp_config_manager();
let mut config = Config::default();
config.aliases.push(Alias {
name: "test".to_string(),
endpoint: "http://localhost:9000".to_string(),
access_key: "accesskey".to_string(),
secret_key: "secretkey".to_string(),
anonymous: false,
client_cert: None,
client_key: None,
region: "us-east-1".to_string(),
signature: "v4".to_string(),
bucket_lookup: "auto".to_string(),
insecure: false,
ca_bundle: None,
retry: None,
timeout: None,
});
manager.save(&config).unwrap();
let loaded = manager.load().unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(manager.config_path())
.unwrap()
.permissions()
.mode();
assert_eq!(mode & 0o777, 0o600);
}
assert_eq!(loaded.aliases.len(), 1);
assert_eq!(loaded.aliases[0].name, "test");
}
#[test]
fn test_save_replaces_longer_config() {
let (manager, _temp_dir) = temp_config_manager();
let mut config = Config::default();
config.defaults.output = "a".repeat(1024);
manager.save(&config).unwrap();
let config = Config::default();
manager.save(&config).unwrap();
assert_eq!(
std::fs::read_to_string(manager.config_path()).unwrap(),
toml::to_string_pretty(&config).unwrap()
);
}
#[cfg(unix)]
#[test]
fn test_save_permissions_before_write() {
use std::os::unix::fs::PermissionsExt;
use std::process::Command;
const CHILD_CONFIG_PATH: &str = "RC_TEST_SAVE_PERMISSIONS_PATH";
if let Some(path) = std::env::var_os(CHILD_CONFIG_PATH) {
let manager = ConfigManager::with_path(PathBuf::from(path));
manager.save(&Config::default()).unwrap();
return;
}
for existing in [false, true] {
let (manager, _temp_dir) = temp_config_manager();
if existing {
std::fs::write(manager.config_path(), "old config").unwrap();
std::fs::set_permissions(
manager.config_path(),
std::fs::Permissions::from_mode(0o666),
)
.unwrap();
}
// Fail the first write in a child process, before a post-write chmod
// could run. Keep the umask and file-size limit out of other tests.
let output = Command::new("sh")
.args([
"-c",
"umask 000 && ulimit -c 0 && ulimit -f 0 && exec \"$@\"",
"sh",
])
.arg(std::env::current_exe().unwrap())
.args([
"--exact",
"config::tests::test_save_permissions_before_write",
])
.env(CHILD_CONFIG_PATH, manager.config_path())
.output()
.unwrap();
assert!(
!output.status.success(),
"the file-size limit must reject writes"
);
let metadata = std::fs::metadata(manager.config_path()).unwrap();
assert_eq!(metadata.len(), 0);
assert_eq!(
metadata.permissions().mode() & 0o777,
0o600,
"config must already be private when writing fails (existing: {existing})"
);
}
}
#[test]
fn test_schema_version_too_new() {
let (manager, _temp_dir) = temp_config_manager();
let content = format!(
r#"
schema_version = {}
"#,
SCHEMA_VERSION + 1
);
std::fs::write(manager.config_path(), content).unwrap();
let result = manager.load();
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("newer than supported")
);
}
}