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
423
424
425
426
427
428
429
430
431
432
433
434
435//! Configuration loading from `~/.openfang/config.toml` with defaults.
//!
//! Supports config includes: the `include` field specifies additional TOML files
//! to load and deep-merge before the root config (root overrides includes).
use openfang_types::config::KernelConfig;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use tracing::info;
/// Maximum include nesting depth.
const MAX_INCLUDE_DEPTH: u32 = 10;
/// Load kernel configuration from a TOML file, with defaults.
///
/// If the config contains an `include` field, included files are loaded
/// and deep-merged first, then the root config overrides them.
pub fn load_config(path: Option<&Path>) -> KernelConfig {
let config_path = path
.map(|p| p.to_path_buf())
.unwrap_or_else(default_config_path);
if config_path.exists() {
match std::fs::read_to_string(&config_path) {
Ok(contents) => match toml::from_str::<toml::Value>(&contents) {
Ok(mut root_value) => {
// Process includes before deserializing
let config_dir = config_path
.parent()
.unwrap_or_else(|| Path::new("."))
.to_path_buf();
let mut visited = HashSet::new();
if let Ok(canonical) = std::fs::canonicalize(&config_path) {
visited.insert(canonical);
} else {
visited.insert(config_path.clone());
}
if let Err(e) =
resolve_config_includes(&mut root_value, &config_dir, &mut visited, 0)
{
tracing::warn!(
error = %e,
"Config include resolution failed, using root config only"
);
}
// Remove the `include` field before deserializing to avoid confusion
if let toml::Value::Table(ref mut tbl) = root_value {
tbl.remove("include");
}
match root_value.try_into::<KernelConfig>() {
Ok(config) => {
info!(path = %config_path.display(), "Loaded configuration");
return config;
}
Err(e) => {
tracing::warn!(
error = %e,
path = %config_path.display(),
"Failed to deserialize merged config, using defaults"
);
}
}
}
Err(e) => {
tracing::warn!(
error = %e,
path = %config_path.display(),
"Failed to parse config, using defaults"
);
}
},
Err(e) => {
tracing::warn!(
error = %e,
path = %config_path.display(),
"Failed to read config file, using defaults"
);
}
}
} else {
info!(
path = %config_path.display(),
"Config file not found, using defaults"
);
}
KernelConfig::default()
}
/// Resolve config includes by deep-merging included files into the root value.
///
/// Included files are loaded first and the root config overrides them.
/// Security: rejects absolute paths, `..` components, and circular references.
fn resolve_config_includes(
root_value: &mut toml::Value,
config_dir: &Path,
visited: &mut HashSet<PathBuf>,
depth: u32,
) -> Result<(), String> {
if depth > MAX_INCLUDE_DEPTH {
return Err(format!(
"Config include depth exceeded maximum of {MAX_INCLUDE_DEPTH}"
));
}
// Extract include list from the current value
let includes = match root_value {
toml::Value::Table(tbl) => {
if let Some(toml::Value::Array(arr)) = tbl.get("include") {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect::<Vec<_>>()
} else {
return Ok(());
}
}
_ => return Ok(()),
};
if includes.is_empty() {
return Ok(());
}
// Merge each include (earlier includes are overridden by later ones,
// and the root config overrides everything).
let mut merged_base = toml::Value::Table(toml::map::Map::new());
for include_path_str in &includes {
// SECURITY: reject absolute paths
let include_path = Path::new(include_path_str);
if include_path.is_absolute() {
return Err(format!(
"Config include rejects absolute path: {include_path_str}"
));
}
// SECURITY: reject `..` components
for component in include_path.components() {
if let std::path::Component::ParentDir = component {
return Err(format!(
"Config include rejects path traversal: {include_path_str}"
));
}
}
let resolved = config_dir.join(include_path);
// SECURITY: verify resolved path stays within config dir
let canonical = std::fs::canonicalize(&resolved).map_err(|e| {
format!(
"Config include '{}' cannot be resolved: {e}",
include_path_str
)
})?;
let canonical_dir = std::fs::canonicalize(config_dir)
.map_err(|e| format!("Config dir cannot be canonicalized: {e}"))?;
if !canonical.starts_with(&canonical_dir) {
return Err(format!(
"Config include '{}' escapes config directory",
include_path_str
));
}
// SECURITY: circular detection
if !visited.insert(canonical.clone()) {
return Err(format!(
"Circular config include detected: {include_path_str}"
));
}
info!(include = %include_path_str, "Loading config include");
let contents = std::fs::read_to_string(&canonical)
.map_err(|e| format!("Failed to read config include '{}': {e}", include_path_str))?;
let mut include_value: toml::Value = toml::from_str(&contents)
.map_err(|e| format!("Failed to parse config include '{}': {e}", include_path_str))?;
// Recursively resolve includes in the included file
let include_dir = canonical.parent().unwrap_or(config_dir).to_path_buf();
resolve_config_includes(&mut include_value, &include_dir, visited, depth + 1)?;
// Remove include field from the included file
if let toml::Value::Table(ref mut tbl) = include_value {
tbl.remove("include");
}
// Deep merge: include overrides the base built so far
deep_merge_toml(&mut merged_base, &include_value);
}
// Now deep merge: root overrides the merged includes
// Save root's current values (minus include), then merge root on top
let root_without_include = {
let mut v = root_value.clone();
if let toml::Value::Table(ref mut tbl) = v {
tbl.remove("include");
}
v
};
deep_merge_toml(&mut merged_base, &root_without_include);
*root_value = merged_base;
Ok(())
}
/// Deep-merge two TOML values. `overlay` values override `base` values.
/// For tables, recursively merge. For everything else, overlay wins.
pub fn deep_merge_toml(base: &mut toml::Value, overlay: &toml::Value) {
match (base, overlay) {
(toml::Value::Table(base_tbl), toml::Value::Table(overlay_tbl)) => {
for (key, overlay_val) in overlay_tbl {
if let Some(base_val) = base_tbl.get_mut(key) {
deep_merge_toml(base_val, overlay_val);
} else {
base_tbl.insert(key.clone(), overlay_val.clone());
}
}
}
(base, overlay) => {
*base = overlay.clone();
}
}
}
/// Get the default config file path.
pub fn default_config_path() -> PathBuf {
dirs::home_dir()
.unwrap_or_else(std::env::temp_dir)
.join(".openfang")
.join("config.toml")
}
/// Get the default OpenFang home directory.
pub fn openfang_home() -> PathBuf {
dirs::home_dir()
.unwrap_or_else(std::env::temp_dir)
.join(".openfang")
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn test_load_config_defaults() {
let config = load_config(None);
assert_eq!(config.log_level, "info");
}
#[test]
fn test_load_config_missing_file() {
let config = load_config(Some(Path::new("/nonexistent/config.toml")));
assert_eq!(config.log_level, "info");
}
#[test]
fn test_deep_merge_simple() {
let mut base: toml::Value = toml::from_str(
r#"
log_level = "debug"
api_listen = "0.0.0.0:4200"
"#,
)
.unwrap();
let overlay: toml::Value = toml::from_str(
r#"
log_level = "info"
network_enabled = true
"#,
)
.unwrap();
deep_merge_toml(&mut base, &overlay);
assert_eq!(base["log_level"].as_str(), Some("info"));
assert_eq!(base["api_listen"].as_str(), Some("0.0.0.0:4200"));
assert_eq!(base["network_enabled"].as_bool(), Some(true));
}
#[test]
fn test_deep_merge_nested_tables() {
let mut base: toml::Value = toml::from_str(
r#"
[memory]
decay_rate = 0.1
consolidation_threshold = 10000
"#,
)
.unwrap();
let overlay: toml::Value = toml::from_str(
r#"
[memory]
decay_rate = 0.5
"#,
)
.unwrap();
deep_merge_toml(&mut base, &overlay);
let mem = base["memory"].as_table().unwrap();
assert_eq!(mem["decay_rate"].as_float(), Some(0.5));
assert_eq!(mem["consolidation_threshold"].as_integer(), Some(10000));
}
#[test]
fn test_basic_include() {
let dir = tempfile::tempdir().unwrap();
let base_path = dir.path().join("base.toml");
let root_path = dir.path().join("config.toml");
// Base config
let mut f = std::fs::File::create(&base_path).unwrap();
writeln!(f, "log_level = \"debug\"").unwrap();
writeln!(f, "api_listen = \"0.0.0.0:9999\"").unwrap();
drop(f);
// Root config (includes base, overrides log_level)
let mut f = std::fs::File::create(&root_path).unwrap();
writeln!(f, "include = [\"base.toml\"]").unwrap();
writeln!(f, "log_level = \"warn\"").unwrap();
drop(f);
let config = load_config(Some(&root_path));
assert_eq!(config.log_level, "warn"); // root overrides
assert_eq!(config.api_listen, "0.0.0.0:9999"); // from base
}
#[test]
fn test_nested_include() {
let dir = tempfile::tempdir().unwrap();
let grandchild = dir.path().join("grandchild.toml");
let child = dir.path().join("child.toml");
let root = dir.path().join("config.toml");
let mut f = std::fs::File::create(&grandchild).unwrap();
writeln!(f, "log_level = \"trace\"").unwrap();
drop(f);
let mut f = std::fs::File::create(&child).unwrap();
writeln!(f, "include = [\"grandchild.toml\"]").unwrap();
writeln!(f, "log_level = \"debug\"").unwrap();
drop(f);
let mut f = std::fs::File::create(&root).unwrap();
writeln!(f, "include = [\"child.toml\"]").unwrap();
writeln!(f, "log_level = \"info\"").unwrap();
drop(f);
let config = load_config(Some(&root));
assert_eq!(config.log_level, "info"); // root wins
}
#[test]
fn test_circular_include_detected() {
let dir = tempfile::tempdir().unwrap();
let a_path = dir.path().join("a.toml");
let b_path = dir.path().join("b.toml");
let mut f = std::fs::File::create(&a_path).unwrap();
writeln!(f, "include = [\"b.toml\"]").unwrap();
writeln!(f, "log_level = \"info\"").unwrap();
drop(f);
let mut f = std::fs::File::create(&b_path).unwrap();
writeln!(f, "include = [\"a.toml\"]").unwrap();
drop(f);
// Should not panic โ circular detection triggers, falls back gracefully
let config = load_config(Some(&a_path));
// Falls back to defaults due to the circular error
assert!(!config.log_level.is_empty());
}
#[test]
fn test_path_traversal_blocked() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("config.toml");
let mut f = std::fs::File::create(&root).unwrap();
writeln!(f, "include = [\"../etc/passwd\"]").unwrap();
drop(f);
// Should not panic โ path traversal triggers error, falls back
let config = load_config(Some(&root));
assert_eq!(config.log_level, "info"); // defaults
}
#[test]
fn test_max_depth_exceeded() {
let dir = tempfile::tempdir().unwrap();
// Create a chain of 12 files (exceeds MAX_INCLUDE_DEPTH=10)
for i in (0..12).rev() {
let name = format!("level{i}.toml");
let path = dir.path().join(&name);
let mut f = std::fs::File::create(&path).unwrap();
if i < 11 {
let next = format!("level{}.toml", i + 1);
writeln!(f, "include = [\"{next}\"]").unwrap();
}
writeln!(f, "log_level = \"level{i}\"").unwrap();
drop(f);
}
let root = dir.path().join("level0.toml");
let config = load_config(Some(&root));
// Falls back due to depth limit โ but should not panic
assert!(!config.log_level.is_empty());
}
#[test]
fn test_absolute_path_rejected() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("config.toml");
let mut f = std::fs::File::create(&root).unwrap();
writeln!(f, "include = [\"/etc/shadow\"]").unwrap();
drop(f);
let config = load_config(Some(&root));
assert_eq!(config.log_level, "info"); // defaults
}
#[test]
fn test_no_includes_works() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("config.toml");
let mut f = std::fs::File::create(&root).unwrap();
writeln!(f, "log_level = \"trace\"").unwrap();
drop(f);
let config = load_config(Some(&root));
assert_eq!(config.log_level, "trace");
}
}