1use std::collections::BTreeMap;
5use std::path::PathBuf;
6
7use serde_yaml_ng::{Mapping, Value};
8
9use crate::platform;
10
11pub const DEFAULT_CONFIG_YAML: &str = "enabled: false\npriority: 0\n";
13
14#[derive(Debug, Clone, PartialEq)]
15pub struct RuntimeConfig {
16 pub enabled: bool,
17 pub dir: PathBuf,
18 pub items: BTreeMap<String, ItemConfig>,
20}
21
22#[derive(Debug, Clone, PartialEq)]
23pub struct ItemConfig {
24 pub id: String,
25 pub enabled: bool,
26 pub priority: i64,
27 pub version: String,
29 pub config_yaml: Vec<u8>,
32}
33
34impl ItemConfig {
35 pub fn default_for(id: &str) -> Self {
37 Self {
38 id: id.to_owned(),
39 enabled: false,
40 priority: 0,
41 version: String::new(),
42 config_yaml: DEFAULT_CONFIG_YAML.as_bytes().to_vec(),
43 }
44 }
45}
46
47pub fn yaml_bool(v: &Value) -> Option<bool> {
50 match v {
51 Value::Bool(b) => Some(*b),
52 Value::String(s) => cpa_core::config::go_bool(s),
53 Value::Tagged(t) => cpa_core::config::go_bool(&yaml_string(&t.value)),
56 _ => None,
57 }
58}
59
60pub fn yaml_int(v: &Value) -> Option<i64> {
63 match v {
64 Value::Tagged(_) => None,
66 other => cpa_core::config::go_int(other),
67 }
68}
69
70pub fn check_json_item(fields: &[(String, crate::gojson::Node)]) -> Result<(), String> {
75 use crate::gojson::Node as J;
76 let get = |key: &str| fields.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v);
77 let int_literal = |n: &str| n.parse::<i64>().is_ok();
79 let describe = |v: &J| {
81 let (tag, text) = match v {
82 J::String(s) => ("!!str", s.as_str()),
83 J::Bool(true) => ("!!bool", "true"),
84 J::Bool(false) => ("!!bool", "false"),
85 J::Number(n) if int_literal(n) => ("!!int", n.as_str()),
86 J::Number(n) => ("!!float", n.as_str()),
87 J::Array(_) => return "!!seq".to_owned(),
88 J::Object(_) => return "!!map".to_owned(),
89 J::Null => return "!!null".to_owned(),
90 };
91 let text = if text.len() > 10 {
92 format!("{}...", go_lossy(&text.as_bytes()[..7]))
93 } else {
94 text.to_owned()
95 };
96 format!("{tag} `{text}`")
97 };
98 let fail = |field: &str, v: &J, into: &str| {
99 Err(format!(
100 "parse plugin {field}: yaml: unmarshal errors:\n line 0: cannot unmarshal {} into {into}",
101 describe(v)
102 ))
103 };
104 if let Some(v) = get("enabled") {
105 let ok = match v {
106 J::Null | J::Bool(_) => true,
107 J::String(s) => yaml_bool(&Value::String(s.clone())).is_some(),
108 _ => false,
109 };
110 if !ok {
111 return fail("enabled", v, "bool");
112 }
113 }
114 if let Some(v) = get("priority") {
115 let ok = match v {
116 J::Null => true,
117 J::Number(n) => {
118 int_literal(n)
119 || n.parse::<f64>()
120 .ok()
121 .and_then(|f| cpa_core::config::go_int(&Value::from(f)))
122 .is_some()
123 }
124 _ => false,
125 };
126 if !ok {
127 return fail("priority", v, "int");
128 }
129 }
130 Ok(())
131}
132
133fn go_lossy(bytes: &[u8]) -> String {
136 let mut out = String::new();
137 let mut rest = bytes;
138 while !rest.is_empty() {
139 match std::str::from_utf8(rest) {
140 Ok(s) => {
141 out.push_str(s);
142 break;
143 }
144 Err(e) => {
145 let (valid, bad) = rest.split_at(e.valid_up_to());
146 out.push_str(std::str::from_utf8(valid).expect("valid prefix"));
147 out.push('\u{fffd}');
148 rest = &bad[1..];
149 }
150 }
151 }
152 out
153}
154
155pub fn yaml_string(v: &Value) -> String {
157 match v {
158 Value::String(s) => s.clone(),
159 Value::Bool(b) => b.to_string(),
160 Value::Number(n) => n.to_string(),
161 Value::Tagged(t) => yaml_string(&t.value),
162 _ => String::new(),
163 }
164}
165
166fn get<'a>(v: &'a Value, key: &str) -> Option<&'a Value> {
167 v.as_mapping()?.get(key)
168}
169
170pub fn resolve_dir(dir: &str) -> Result<PathBuf, String> {
173 let dir = dir.trim();
174 let dir = if dir.is_empty() { "plugins" } else { dir };
175 if let Some(rest) = dir.strip_prefix('~') {
176 let home = std::env::var_os("HOME")
177 .filter(|h| !h.is_empty())
178 .ok_or_else(|| "resolve plugins directory: $HOME is not defined".to_owned())?;
179 let rest = rest.trim_start_matches(['/', '\\']);
180 let home = PathBuf::from(home);
181 if rest.is_empty() {
182 return Ok(platform::clean(&home));
183 }
184 return Ok(platform::clean(&home.join(rest.replace('\\', "/"))));
185 }
186 Ok(platform::clean(std::path::Path::new(dir)))
187}
188
189pub fn store_sources(document: &Value) -> Vec<String> {
194 match get(document, "plugins").and_then(|p| get(p, "store-sources")) {
195 Some(Value::Sequence(items)) => items
196 .iter()
197 .map(|item| yaml_string(item).trim().to_owned())
198 .filter(|s| !s.is_empty())
199 .collect(),
200 _ => Vec::new(),
201 }
202}
203
204pub fn store_auth(document: &Value) -> Vec<crate::store::AuthConfig> {
207 let Some(Value::Sequence(items)) = get(document, "plugins").and_then(|p| get(p, "store-auth")) else {
208 return Vec::new();
209 };
210 let rules: Vec<_> = items
211 .iter()
212 .filter(|item| item.is_mapping())
213 .map(|item| {
214 let text = |key: &str| get(item, key).map(yaml_string).unwrap_or_default();
215 crate::store::AuthConfig {
216 matches: text("match"),
217 apply_to: match get(item, "apply-to") {
218 Some(Value::Sequence(values)) => values.iter().map(yaml_string).collect(),
219 _ => Vec::new(),
220 },
221 auth_type: text("type"),
222 token_env: text("token-env"),
223 username_env: text("username-env"),
224 password_env: text("password-env"),
225 header_name: text("header-name"),
226 header_value_env: text("header-value-env"),
227 allow_insecure: get(item, "allow-insecure").and_then(yaml_bool).unwrap_or(false),
228 }
229 })
230 .collect();
231 crate::store::normalize_auth_configs(&rules)
232}
233
234pub fn configured_dir(document: &Value) -> String {
236 get(document, "plugins")
237 .and_then(|p| get(p, "dir"))
238 .map(yaml_string)
239 .unwrap_or_default()
240}
241
242pub fn runtime_config(document: &Value, raw: &Value) -> Result<RuntimeConfig, String> {
244 let mut out = RuntimeConfig {
245 enabled: false,
246 dir: PathBuf::from("plugins"),
247 items: BTreeMap::new(),
248 };
249 let Some(plugins) = get(document, "plugins") else {
250 return Ok(out);
251 };
252 out.enabled = get(plugins, "enabled").and_then(yaml_bool).unwrap_or(false);
253 if !out.enabled {
254 return Ok(out);
255 }
256 out.dir = resolve_dir(&configured_dir(document))?;
257 if let Some(Value::Mapping(configs)) = get(plugins, "configs") {
258 for (key, node) in configs {
259 let id = yaml_string(key);
260 out.items.insert(id.clone(), item_config(&id, node, raw.get(key)));
261 }
262 }
263 Ok(out)
264}
265
266pub fn item_config(id: &str, node: &Value, raw: Option<&Value>) -> ItemConfig {
270 let mut enabled = false;
271 let mut priority = 0;
272 if let Value::Mapping(map) = node {
273 if let Some(v) = map.get("enabled") {
274 enabled = yaml_bool(v).unwrap_or(false);
277 }
278 if let Some(v) = map.get("priority") {
279 priority = yaml_int(v).unwrap_or(0);
280 }
281 }
282 ItemConfig {
283 id: id.to_owned(),
284 enabled,
285 priority,
286 version: desired_version(node),
287 config_yaml: config_yaml(node, raw, enabled, priority),
288 }
289}
290
291fn desired_version(node: &Value) -> String {
293 let Some(store) = get(node, "store") else {
294 return String::new();
295 };
296 let scalar = |key| {
297 get(store, key)
298 .map(|v| yaml_string(v).trim().to_owned())
299 .unwrap_or_default()
300 };
301 let version = normalize_version(&scalar("version"));
302 if !version.is_empty() {
303 return version;
304 }
305 normalize_version(&scalar("release-tag"))
306}
307
308pub fn normalize_version(version: &str) -> String {
310 let mut version = version.trim();
311 if version.len() > 1 && (version.starts_with('v') || version.starts_with('V')) {
312 version = &version[1..];
313 }
314 if platform::valid_version(version) {
315 version.to_owned()
316 } else {
317 String::new()
318 }
319}
320
321fn config_yaml(node: &Value, raw: Option<&Value>, enabled: bool, priority: i64) -> Vec<u8> {
328 let rendered = match node {
329 Value::Null => {
330 let mut map = Mapping::new();
331 map.insert("enabled".into(), enabled.into());
332 map.insert("priority".into(), priority.into());
333 Value::Mapping(map)
334 }
335 Value::Mapping(map) => {
336 let mut map = map.clone();
337 if !map.contains_key("enabled") {
338 map.insert("enabled".into(), enabled.into());
339 }
340 if !map.contains_key("priority") {
341 map.insert("priority".into(), priority.into());
342 }
343 Value::Mapping(map)
344 }
345 other => other.clone(),
346 };
347 let mut text = String::new();
348 emit(&mut text, &rendered, raw, 0);
349 let trimmed = text.trim();
350 if trimmed.is_empty() {
351 return DEFAULT_CONFIG_YAML.as_bytes().to_vec();
352 }
353 let mut out = trimmed.as_bytes().to_vec();
354 out.push(b'\n');
355 out
356}
357
358fn emit(out: &mut String, node: &Value, raw: Option<&Value>, indent: usize) {
362 let pad = " ".repeat(indent);
363 match node {
364 Value::Mapping(map) if !map.is_empty() => {
365 let raw = raw.and_then(Value::as_mapping);
366 for (key, value) in map {
367 let key_text = match key {
368 Value::String(k) if plain_word(k) => k.clone(),
369 _ => scalar(key, None),
370 };
371 out.push_str(&pad);
372 if key_text.chars().count() > 1024 {
374 out.push_str("? ");
375 out.push_str(&key_text);
376 out.push('\n');
377 out.push_str(&pad);
378 } else {
379 out.push_str(&key_text);
380 }
381 out.push(':');
382 child(out, value, raw.and_then(|r| r.get(key)), indent);
383 }
384 }
385 Value::Sequence(items) if !items.is_empty() => {
386 let raw = raw.and_then(Value::as_sequence);
387 for (i, item) in items.iter().enumerate() {
388 out.push_str(&pad);
389 out.push('-');
390 child(out, item, raw.and_then(|r| r.get(i)), indent);
391 }
392 }
393 Value::Tagged(tagged) if matches!(tagged.value, Value::Mapping(_) | Value::Sequence(_)) => {
394 out.push_str(&pad);
395 out.push_str(&tagged.tag.to_string());
396 out.push('\n');
397 let raw = raw.map(|r| match r {
398 Value::Tagged(t) => &t.value,
399 other => other,
400 });
401 emit(out, &tagged.value, raw, indent + 2);
402 }
403 other => {
404 out.push_str(&pad);
405 out.push_str(&scalar(other, raw));
406 out.push('\n');
407 }
408 }
409}
410
411fn child(out: &mut String, value: &Value, raw: Option<&Value>, indent: usize) {
413 let collection =
414 |v: &Value| matches!(v, Value::Mapping(m) if !m.is_empty()) || matches!(v, Value::Sequence(s) if !s.is_empty());
415 match value {
416 v if collection(v) => {
417 out.push('\n');
418 emit(out, value, raw, indent + 2);
419 }
420 Value::Tagged(t) if collection(&t.value) => {
421 out.push('\n');
422 emit(out, value, raw, indent + 2);
423 }
424 _ => {
425 out.push(' ');
426 out.push_str(&scalar(value, raw));
427 out.push('\n');
428 }
429 }
430}
431
432fn plain_word(s: &str) -> bool {
434 const WORDS: &[&str] = &["y", "n", "yes", "no", "on", "off", "true", "false", "null"];
435 s.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
436 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
437 && !WORDS.iter().any(|w| s.eq_ignore_ascii_case(w))
438}
439
440fn scalar(value: &Value, raw: Option<&Value>) -> String {
441 use cpa_core::config::yaml_double_quoted as quoted;
442 match (value, raw) {
443 (_, Some(Value::Tagged(t))) if t.tag == cpa_core::config::PLAIN_SCALAR => match &t.value {
444 Value::String(text) if text.contains(['\n', '\r', '\u{85}', '\u{2028}', '\u{2029}']) => quoted(text),
446 Value::String(text) => text.clone(),
447 other => scalar(other, None),
448 },
449 (Value::String(s), _) => quoted(s),
450 (Value::Mapping(_), _) => "{}".to_owned(),
451 (Value::Sequence(_), _) => "[]".to_owned(),
452 _ => serde_yaml_ng::to_string(value)
453 .unwrap_or_default()
454 .trim_end()
455 .to_owned(),
456 }
457}
458
459pub fn desired_versions(items: &BTreeMap<String, ItemConfig>) -> BTreeMap<String, String> {
461 items
462 .iter()
463 .filter(|(id, item)| !id.trim().is_empty() && !item.version.trim().is_empty())
464 .map(|(id, item)| (id.trim().to_owned(), item.version.trim().to_owned()))
465 .collect()
466}
467
468#[cfg(test)]
469mod tests {
470 use super::*;
471
472 #[test]
475 fn locally_tagged_pins_load_and_pin() {
476 for yaml in [
477 "plugins:\n configs:\n x:\n store:\n version: !keep 1.2.3\n",
478 "pin: &v !keep 1.2.3\nplugins:\n configs:\n x:\n store:\n version: *v\n",
479 "plugins:\n configs:\n x:\n store:\n release-tag: !!str v1.2.3\n",
480 "plugins:\n configs:\n x:\n store:\n version: !<!!str> 1.2.3\n",
481 "pin: &v v1.2.3\nplugins:\n configs:\n x:\n store:\n release-tag: *v\n",
482 "plugins:\n configs:\n x:\n store:\n release-tag: ! v1.2.3\n",
483 "pin: &v ! v1.2.3\nplugins:\n configs:\n x:\n store:\n release-tag: *v\n",
484 "base: &b !keep {version: 1.2.3}\nplugins:\n configs:\n x:\n store:\n <<: *b\n",
486 "plugins:\n configs:\n x:\n store:\n <<: !keep {version: 1.2.3}\n",
487 ] {
488 let cfg = cpa_core::config::Config::parse(yaml).unwrap_or_else(|e| panic!("{yaml}: {e:#}"));
489 let item = item_config("x", &cfg.document["plugins"]["configs"]["x"], None);
490 assert_eq!(item.version, "1.2.3", "{yaml}");
491 }
492 }
493
494 #[test]
497 fn json_item_checks_follow_go() {
498 let line = |f: &str, rest: &str| {
499 format!("parse plugin {f}: yaml: unmarshal errors:\n line 0: cannot unmarshal {rest}")
500 };
501 for (body, want) in [
502 (r#"{"enabled":"yes"}"#, None),
503 (r#"{"enabled":"on","priority":2}"#, None),
504 (r#"{"enabled":null,"priority":null}"#, None),
505 (r#"{"priority":5.7}"#, None),
506 (r#"{"priority":-2.9}"#, None),
507 (r#"{"priority":1e3}"#, None),
508 (
509 r#"{"enabled":"maybe"}"#,
510 Some(line("enabled", "!!str `maybe` into bool")),
511 ),
512 (r#"{"enabled":"true"}"#, Some(line("enabled", "!!str `true` into bool"))),
513 (
514 r#"{"enabled":"abcdefghijklmnop"}"#,
515 Some(line("enabled", "!!str `abcdefg...` into bool")),
516 ),
517 (r#"{"enabled":1}"#, Some(line("enabled", "!!int `1` into bool"))),
518 (r#"{"enabled":0.5}"#, Some(line("enabled", "!!float `0.5` into bool"))),
519 (r#"{"enabled":[true]}"#, Some(line("enabled", "!!seq into bool"))),
520 (r#"{"enabled":{"a":1}}"#, Some(line("enabled", "!!map into bool"))),
521 (r#"{"priority":"5"}"#, Some(line("priority", "!!str `5` into int"))),
522 (r#"{"priority":true}"#, Some(line("priority", "!!bool `true` into int"))),
523 (
524 r#"{"priority":1.5e300}"#,
525 Some(line("priority", "!!float `1.5e300` into int")),
526 ),
527 (
528 r#"{"priority":99999999999999999999}"#,
529 Some(line("priority", "!!float `9999999...` into int")),
530 ),
531 (r#"{"enabled":1,"enabled":true}"#, None),
532 (
534 r#"{"enabled":"éééééé"}"#,
535 Some(line("enabled", "!!str `ééé\u{fffd}...` into bool")),
536 ),
537 ] {
538 let node = crate::gojson::parse(body.as_bytes()).unwrap();
539 let crate::gojson::Node::Object(fields) = &node else {
540 panic!("object");
541 };
542 assert_eq!(check_json_item(fields).err(), want, "{body}");
543 }
544 let yaml = |s: &str| serde_yaml_ng::from_str::<Value>(s).unwrap();
545 assert_eq!(yaml_int(&yaml("5.7")), Some(5));
546 assert_eq!(yaml_int(&yaml("!!int 5")), Some(5));
547 assert_eq!(yaml_int(&yaml("!foo 123")), None);
548 assert_eq!(yaml_bool(&yaml("!foo yes")), Some(true));
549 assert_eq!(yaml_bool(&yaml("!foo true")), None);
550 assert_eq!(yaml_bool(&yaml("!!str off")), Some(false));
551 }
552
553 fn doc(text: &str) -> Value {
554 serde_yaml_ng::from_str(text).unwrap()
555 }
556
557 #[test]
560 fn items_follow_go() {
561 let rc = runtime_config(
562 &doc(
563 "plugins:\n enabled: true\n dir: /p\n configs:\n a:\n mode: fast\n b:\n enabled: yes\n priority: 7\n store:\n release-tag: v1.2.3\n c:\n",
564 ),
565 &Value::Null,
566 )
567 .unwrap();
568 assert!(rc.enabled);
569 assert_eq!(rc.dir, PathBuf::from("/p"));
570 let a = &rc.items["a"];
571 assert!(!a.enabled);
572 assert_eq!(
573 String::from_utf8_lossy(&a.config_yaml),
574 "mode: \"fast\"\nenabled: false\npriority: 0\n"
575 );
576 let b = &rc.items["b"];
577 assert!(b.enabled);
578 assert_eq!(b.priority, 7);
579 assert_eq!(b.version, "1.2.3");
580 assert_eq!(String::from_utf8_lossy(&rc.items["c"].config_yaml), DEFAULT_CONFIG_YAML);
581 }
582
583 #[test]
589 fn plugins_get_their_scalars_as_written() {
590 let cfg = cpa_core::config::Config::parse(
591 "plugins:\n enabled: true\n configs:\n p:\n threshold: 1.50\n name: 1e3\n hex: 0x1F\n oct: 007\n flag: True\n list: [1.50, 'q', -0]\n nested:\n s: \"x: y\"\n q: '1.50'\n tagged: !!float 1\n lines: /first\n\n second\n",
592 )
593 .unwrap();
594 let rc = runtime_config(&cfg.document, &cfg.plugin_configs).unwrap();
595 assert_eq!(
596 String::from_utf8_lossy(&rc.items["p"].config_yaml),
597 "threshold: 1.50\nname: 1e3\nhex: 0x1F\noct: 007\nflag: True\nlist:\n - 1.50\n - \"q\"\n - -0\nnested:\n s: \"x: y\"\n q: \"1.50\"\ntagged: !!float 1\nlines: \"/first\\nsecond\"\nenabled: false\npriority: 0\n"
598 );
599 }
600
601 #[test]
606 fn plugin_config_yaml_reads_as_go() {
607 let k = "k".repeat(1100);
608 let cfg = cpa_core::config::Config::parse(&format!("plugins:\n enabled: true\n configs:\n p:\n a: !!float 1.50\n b: !!int 0x1F\n c: !!bool True\n d: !!float 1\n e: !!float -0\n f: !!float \"1.50\"\n g: \"x\\ny\\N\"\n h: \"x\\n\\L y\"\n i: \"x\\n\\x7f\"\n j: \"1 \\L 2\"\n k: '1_000'\n l: '2001-12-14'\n m: !keep 1_000\n n: !!str 1_000\n o: !!binary MV8wMDA=\n anc: {{&k 1.50: v}}\n q: *k\n ? {k}\n : v\n plain: 1.50\n multi: /first\n\n second\n oct: 007\n word: yes\n ff: \"x\\uFFFEy\\uFFFFz\"\n fb: !!binary eO+/vnk=\n ts: !!timestamp 2001-12-14\n")).unwrap();
609 let rc = runtime_config(&cfg.document, &cfg.plugin_configs).unwrap();
610 assert_eq!(
611 String::from_utf8_lossy(&rc.items["p"].config_yaml),
612 format!(
613 "a: !!float 1.50\nb: !!int 0x1F\nc: !!bool True\nd: !!float 1\ne: !!float -0\nf: !!float \"1.50\"\ng: \"x\\ny\\x85\"\nh: \"x\\n\\L y\"\ni: \"x\\n\\x7F\"\nj: \"1 \\L 2\"\nk: \"1_000\"\nl: \"2001-12-14\"\nm: \"1_000\"\n\"n\": \"1_000\"\no: \"1_000\"\nanc:\n 1.5: \"v\"\nq: 1.50\n? {k}\n: \"v\"\nplain: 1.50\nmulti: \"/first\\nsecond\"\noct: 007\nword: yes\nff: \"x\\uFFFEy\\uFFFFz\"\nfb: \"x\\uFFFEy\"\nts: !!timestamp 2001-12-14\nenabled: false\npriority: 0\n"
614 )
615 );
616 }
617
618 #[test]
619 fn disabled_section_keeps_defaults() {
620 let rc = runtime_config(
621 &doc("plugins:\n enabled: false\n configs:\n a: {}\n"),
622 &Value::Null,
623 )
624 .unwrap();
625 assert!(!rc.enabled);
626 assert!(rc.items.is_empty());
627 assert_eq!(rc.dir, PathBuf::from("plugins"));
628 assert!(!runtime_config(&doc("port: 1\n"), &Value::Null).unwrap().enabled);
629 }
630
631 #[test]
632 fn dir_resolution_matches_go() {
633 assert_eq!(resolve_dir("").unwrap(), PathBuf::from("plugins"));
634 assert_eq!(resolve_dir(" ./a/../b/ ").unwrap(), PathBuf::from("b"));
635 let home = std::env::var("HOME").unwrap();
636 assert_eq!(resolve_dir("~/x\\y").unwrap(), PathBuf::from(format!("{home}/x/y")));
637 assert_eq!(normalize_version("V2.0"), "2.0");
638 assert_eq!(normalize_version("v"), "");
639 assert_eq!(normalize_version("vv1"), "");
640 }
641}