1use crate::config_check::Finding;
28use serde_json::Value;
29use std::collections::HashSet;
30use std::sync::OnceLock;
31
32const DESCRIPTORS: &str = include_str!("../data/stack-adapters.json");
33
34#[derive(Debug, Clone)]
35pub struct FieldSpec {
36 pub key: String,
37 pub kind: String,
39 pub secret: bool,
40 pub default: Option<String>,
41 pub choices: Vec<String>,
42 pub help: Option<String>,
43}
44
45#[derive(Debug, Clone)]
46pub struct ChunkSpec {
47 pub type_id: String,
48 pub label: String,
49 pub singleton: bool,
50 pub fields: Vec<FieldSpec>,
51}
52
53#[derive(Debug, Clone)]
54pub struct Starter {
55 pub type_id: String,
56 pub name: String,
57}
58
59#[derive(Debug, Clone)]
60pub struct Rule {
61 pub id: &'static str,
62 pub kind: String,
63 pub type_id: String,
64 pub field: Option<String>,
65 pub fields: Vec<String>,
66 pub when: Option<String>,
67 pub values: Vec<String>,
68 pub severity: &'static str,
69 pub message: String,
70}
71
72#[derive(Debug, Clone)]
73pub struct Adapter {
74 pub id: String,
75 pub label: String,
76 pub abbr: String,
77 pub description: String,
78 pub file: String,
79 pub chunks: Vec<ChunkSpec>,
80 pub starter: Vec<Starter>,
81 pub raw: bool,
84 pub output: Value,
85 pub rules: Vec<Rule>,
86}
87
88fn str_of(v: &Value, k: &str) -> String {
89 v.get(k).and_then(Value::as_str).unwrap_or("").to_string()
90}
91
92fn strs(v: &Value, k: &str) -> Vec<String> {
93 v.get(k)
94 .and_then(Value::as_array)
95 .map(|a| {
96 a.iter()
97 .filter_map(Value::as_str)
98 .map(String::from)
99 .collect()
100 })
101 .unwrap_or_default()
102}
103
104fn leak(s: String) -> &'static str {
107 Box::leak(s.into_boxed_str())
108}
109
110fn parse() -> Vec<Adapter> {
111 let doc: Value = serde_json::from_str(DESCRIPTORS).expect("stack-adapters.json is valid JSON");
112 doc["adapters"]
113 .as_array()
114 .expect("adapters is an array")
115 .iter()
116 .map(|a| {
117 let id = str_of(a, "id");
118 let chunks = a["chunks"]
119 .as_array()
120 .map(|cs| {
121 cs.iter()
122 .map(|c| ChunkSpec {
123 type_id: str_of(c, "type"),
124 label: str_of(c, "label"),
125 singleton: c["singleton"].as_bool().unwrap_or(false),
126 fields: c["fields"]
127 .as_array()
128 .map(|fs| {
129 fs.iter()
130 .map(|f| FieldSpec {
131 key: str_of(f, "key"),
132 kind: if f["kind"].is_string() {
133 str_of(f, "kind")
134 } else {
135 "text".into()
136 },
137 secret: f["secret"].as_bool().unwrap_or(false),
138 default: f["default"].as_str().map(String::from),
139 choices: strs(f, "choices"),
140 help: f["help"].as_str().map(String::from),
141 })
142 .collect()
143 })
144 .unwrap_or_default(),
145 })
146 .collect()
147 })
148 .unwrap_or_default();
149 let rules = a["rules"]
150 .as_array()
151 .map(|rs| {
152 rs.iter()
153 .map(|r| Rule {
154 id: leak(format!("stack-{id}-{}", str_of(r, "id"))),
155 kind: str_of(r, "kind"),
156 type_id: str_of(r, "type"),
157 field: r["field"].as_str().map(String::from),
158 fields: strs(r, "fields"),
159 when: r["when"].as_str().map(String::from),
160 values: strs(r, "values"),
161 severity: if str_of(r, "severity") == "error" {
162 "error"
163 } else {
164 "warning"
165 },
166 message: str_of(r, "message"),
167 })
168 .collect()
169 })
170 .unwrap_or_default();
171 Adapter {
172 label: str_of(a, "label"),
173 abbr: str_of(a, "abbr"),
174 description: str_of(a, "description"),
175 file: str_of(a, "file"),
176 starter: a["starter"]
177 .as_array()
178 .map(|ss| {
179 ss.iter()
180 .map(|s| Starter {
181 type_id: str_of(s, "type"),
182 name: str_of(s, "name"),
183 })
184 .collect()
185 })
186 .unwrap_or_default(),
187 raw: a["raw"].as_bool().unwrap_or(false),
188 output: a["output"].clone(),
189 chunks,
190 rules,
191 id,
192 }
193 })
194 .collect()
195}
196
197pub fn adapters() -> &'static [Adapter] {
198 static ALL: OnceLock<Vec<Adapter>> = OnceLock::new();
199 ALL.get_or_init(parse)
200}
201
202pub fn adapter(id: &str) -> Option<&'static Adapter> {
203 adapters().iter().find(|a| a.id == id)
204}
205
206pub fn chunk_types() -> Vec<&'static str> {
208 adapters()
209 .iter()
210 .flat_map(|a| a.chunks.iter().map(|c| c.type_id.as_str()))
211 .collect()
212}
213
214impl Adapter {
215 pub fn chunk_spec(&self, type_id: &str) -> Option<&ChunkSpec> {
216 self.chunks.iter().find(|c| c.type_id == type_id)
217 }
218}
219
220#[derive(Debug, Clone, PartialEq)]
223enum Y {
224 Str(String),
225 Bool(bool),
226 Int(i64),
227 List(Vec<Y>),
228 Map(Vec<(String, Y)>),
229}
230
231fn reserved(s: &str) -> bool {
234 matches!(
235 s.to_ascii_lowercase().as_str(),
236 "true" | "false" | "yes" | "no" | "on" | "off" | "y" | "n" | "null" | "~" | "nan" | "inf"
237 )
238}
239
240fn scalar(s: &str) -> String {
246 let bare = !s.is_empty()
247 && !reserved(s)
248 && s.chars()
249 .next()
250 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
251 && s.chars()
252 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'));
253 if bare {
254 s.to_string()
255 } else {
256 serde_json::to_string(s).unwrap_or_else(|_| format!("\"{s}\""))
257 }
258}
259
260fn write_map(out: &mut String, entries: &[(String, Y)], indent: usize) {
261 let pad = " ".repeat(indent);
262 for (k, v) in entries {
263 out.push_str(&pad);
264 out.push_str(&scalar(k));
265 out.push(':');
266 match v {
267 Y::Str(s) => {
268 out.push(' ');
269 out.push_str(&scalar(s));
270 out.push('\n');
271 }
272 Y::Bool(b) => out.push_str(&format!(" {b}\n")),
273 Y::Int(i) => out.push_str(&format!(" {i}\n")),
274 Y::Map(m) if m.is_empty() => out.push_str(" {}\n"),
275 Y::List(l) if l.is_empty() => out.push_str(" []\n"),
276 Y::Map(m) => {
277 out.push('\n');
278 write_map(out, m, indent + 2);
279 }
280 Y::List(l) => {
281 out.push('\n');
282 write_list(out, l, indent + 2);
283 }
284 }
285 }
286}
287
288fn write_list(out: &mut String, items: &[Y], indent: usize) {
289 let pad = " ".repeat(indent);
290 for item in items {
291 match item {
292 Y::Map(m) if !m.is_empty() => {
293 let mut inner = String::new();
295 write_map(&mut inner, m, indent + 2);
296 out.push_str(&pad);
297 out.push_str("- ");
298 out.push_str(&inner[indent + 2..]);
299 }
300 Y::List(l) if !l.is_empty() => {
301 out.push_str(&pad);
302 out.push_str("-\n");
303 write_list(out, l, indent + 2);
304 }
305 Y::Str(s) => out.push_str(&format!("{pad}- {}\n", scalar(s))),
306 Y::Bool(b) => out.push_str(&format!("{pad}- {b}\n")),
307 Y::Int(i) => out.push_str(&format!("{pad}- {i}\n")),
308 Y::Map(_) => out.push_str(&format!("{pad}- {{}}\n")),
309 Y::List(_) => out.push_str(&format!("{pad}- []\n")),
310 }
311 }
312}
313
314fn to_yaml(root: &Y) -> String {
315 if let Y::Str(s) = root {
317 return s.clone();
318 }
319 let mut out = String::from("# Generated by UnENVerse\n");
320 match root {
321 Y::Map(m) => write_map(&mut out, m, 0),
322 Y::List(l) => write_list(&mut out, l, 0),
323 _ => {}
324 }
325 out
326}
327
328pub type Resolve<'a> = &'a dyn Fn(&str, bool) -> String;
332
333struct Ctx<'a> {
334 adapter: &'a Adapter,
335 chunks: &'a [&'a Value],
336 resolve: Resolve<'a>,
337 cur: Option<(&'a Value, &'a ChunkSpec)>,
339}
340
341fn chunk_type(c: &Value) -> &str {
342 c.get("chunk_type").and_then(Value::as_str).unwrap_or("")
343}
344
345fn raw_field<'a>(chunk: &'a Value, key: &str) -> &'a str {
346 if key == "@name" {
347 return chunk.get("name").and_then(Value::as_str).unwrap_or("");
348 }
349 chunk
350 .get("fields")
351 .and_then(Value::as_array)
352 .and_then(|fs| {
353 fs.iter()
354 .find(|f| f.get("key").and_then(Value::as_str) == Some(key))
355 })
356 .and_then(|f| f.get("value"))
357 .and_then(Value::as_str)
358 .unwrap_or("")
359}
360
361fn is_secret(spec: &ChunkSpec, key: &str) -> bool {
362 spec.fields.iter().any(|f| f.key == key && f.secret)
363}
364
365impl Ctx<'_> {
366 fn field_text(&self, key: &str) -> String {
367 let Some((chunk, spec)) = self.cur else {
368 return String::new();
369 };
370 let raw = raw_field(chunk, key);
371 if raw.trim().is_empty() {
372 return String::new();
373 }
374 if key == "@name" {
375 return raw.to_string();
376 }
377 (self.resolve)(raw, is_secret(spec, key))
378 }
379
380 fn of_type(&self, type_id: &str) -> Vec<&Value> {
381 self.chunks
382 .iter()
383 .copied()
384 .filter(|c| chunk_type(c) == type_id)
385 .collect()
386 }
387
388 fn with<'b>(&'b self, chunk: &'b Value, spec: &'b ChunkSpec) -> Ctx<'b> {
389 Ctx {
390 adapter: self.adapter,
391 chunks: self.chunks,
392 resolve: self.resolve,
393 cur: Some((chunk, spec)),
394 }
395 }
396
397 fn each_chunk(&self, type_id: &str) -> Vec<Ctx<'_>> {
398 let Some(spec) = self.adapter.chunk_spec(type_id) else {
399 return Vec::new();
400 };
401 self.of_type(type_id)
402 .into_iter()
403 .map(|c| self.with(c, spec))
404 .collect()
405 }
406}
407
408fn split_list(s: &str) -> Vec<String> {
409 s.split(['\n', ','])
410 .map(str::trim)
411 .filter(|x| !x.is_empty())
412 .map(String::from)
413 .collect()
414}
415
416fn truthy(s: &str) -> Option<bool> {
417 match s.trim().to_ascii_lowercase().as_str() {
418 "true" | "yes" | "on" | "1" => Some(true),
419 "false" | "no" | "off" | "0" => Some(false),
420 _ => None,
421 }
422}
423
424fn keep(node: &Value) -> bool {
425 node.get("keep").and_then(Value::as_bool).unwrap_or(false)
426}
427
428fn eval(node: &Value, ctx: &Ctx) -> Option<Y> {
429 match node {
430 Value::String(s) => Some(Y::Str(s.clone())),
431 Value::Bool(b) => Some(Y::Bool(*b)),
432 Value::Number(n) => n.as_i64().map(Y::Int),
433 Value::Object(o) => {
434 if let Some(f) = o.get("f").and_then(Value::as_str) {
435 let text = ctx.field_text(f);
436 if text.is_empty() {
437 return None;
438 }
439 return match o.get("as").and_then(Value::as_str).unwrap_or("str") {
440 "list" => {
441 let items = split_list(&text);
442 (!items.is_empty())
443 .then(|| Y::List(items.into_iter().map(Y::Str).collect()))
444 }
445 "bool" => truthy(&text).map(Y::Bool),
446 "int" => Some(text.trim().parse::<i64>().map_or(Y::Str(text), Y::Int)),
447 _ => Some(Y::Str(match o.get("fmt").and_then(Value::as_str) {
448 Some(fmt) => fmt.replace("{}", &text),
449 None => text,
450 })),
451 };
452 }
453 if let Some(pairs) = o.get("map").and_then(Value::as_array) {
454 let entries: Vec<(String, Y)> = pairs
455 .iter()
456 .filter_map(|p| {
457 let p = p.as_array()?;
458 let key = p.first()?.as_str()?.to_string();
459 Some((key, eval(p.get(1)?, ctx)?))
460 })
461 .collect();
462 return (!entries.is_empty() || keep(node)).then_some(Y::Map(entries));
463 }
464 if let Some(items) = o.get("list").and_then(Value::as_array) {
465 let l: Vec<Y> = items.iter().filter_map(|n| eval(n, ctx)).collect();
466 return (!l.is_empty() || keep(node)).then_some(Y::List(l));
467 }
468 if let Some(t) = o.get("each").and_then(Value::as_str) {
469 let inner = o.get("node")?;
470 let l: Vec<Y> = ctx
471 .each_chunk(t)
472 .iter()
473 .filter_map(|c| eval(inner, c))
474 .collect();
475 return (!l.is_empty() || keep(node)).then_some(Y::List(l));
476 }
477 if let Some(t) = o.get("singleton").and_then(Value::as_str) {
478 let inner = o.get("node")?;
479 let first = ctx.each_chunk(t).into_iter().next()?;
480 return eval(inner, &first);
481 }
482 if let Some(g) = o.get("group") {
483 let of = g.get("of").and_then(Value::as_str)?;
484 let by = g.get("by").and_then(Value::as_str)?;
485 let default = g.get("default").and_then(Value::as_str).unwrap_or("");
486 let item = g.get("item")?;
487 let mut groups: Vec<(String, Vec<Y>)> = Vec::new();
488 for c in ctx.each_chunk(of) {
489 let name = match c.field_text(by) {
490 n if n.is_empty() => default.to_string(),
491 n => n,
492 };
493 let Some(y) = eval(item, &c) else {
494 continue;
495 };
496 match groups.iter_mut().find(|(n, _)| *n == name) {
497 Some((_, items)) => items.push(y),
498 None => groups.push((name, vec![y])),
499 }
500 }
501 let l: Vec<Y> = groups
502 .into_iter()
503 .map(|(n, items)| Y::Map(vec![(n, Y::List(items))]))
504 .collect();
505 return (!l.is_empty() || keep(node)).then_some(Y::List(l));
506 }
507 if let Some(p) = o.get("pairs") {
508 let t = p.get("of").and_then(Value::as_str)?;
510 let (key, value) = (p.get("key")?, p.get("value")?);
511 let entries: Vec<(String, Y)> = ctx
512 .each_chunk(t)
513 .iter()
514 .filter_map(|c| match (eval(key, c)?, eval(value, c)?) {
515 (Y::Str(k), v) => Some((k, v)),
516 _ => None,
517 })
518 .collect();
519 return (!entries.is_empty() || keep(node)).then_some(Y::Map(entries));
520 }
521 if let Some(e) = o.get("entry") {
522 let key = match eval(e.get("key")?, ctx)? {
523 Y::Str(s) => s,
524 _ => return None,
525 };
526 let value = e
527 .get("value")
528 .and_then(|v| eval(v, ctx))
529 .unwrap_or(Y::Map(Vec::new()));
530 return Some(Y::Map(vec![(key, value)]));
531 }
532 if let Some(fields) = o.get("when").and_then(Value::as_array) {
533 let any = fields
534 .iter()
535 .filter_map(Value::as_str)
536 .any(|f| !ctx.field_text(f).is_empty());
537 return if any { eval(o.get("node")?, ctx) } else { None };
538 }
539 None
540 }
541 _ => None,
542 }
543}
544
545pub fn render(adapter: &Adapter, project: &Value, resolve: Resolve) -> String {
547 let chunks: Vec<&Value> = project
548 .get("chunks")
549 .and_then(Value::as_array)
550 .map(|cs| {
551 cs.iter()
552 .filter(|c| !c.get("disabled").and_then(Value::as_bool).unwrap_or(false))
553 .collect()
554 })
555 .unwrap_or_default();
556 let ctx = Ctx {
557 adapter,
558 chunks: &chunks,
559 resolve,
560 cur: None,
561 };
562 match eval(&adapter.output, &ctx) {
563 Some(root) => to_yaml(&root),
564 None if adapter.raw => String::new(),
565 None => "# Generated by UnENVerse\n".to_string(),
566 }
567}
568
569pub fn starter_chunks(adapter: &Adapter, new_id: &dyn Fn() -> String) -> Vec<Value> {
571 adapter
572 .starter
573 .iter()
574 .filter_map(|s| {
575 let spec = adapter.chunk_spec(&s.type_id)?;
576 Some(new_chunk(spec, &s.name, new_id()))
577 })
578 .collect()
579}
580
581pub fn new_chunk(spec: &ChunkSpec, name: &str, id: String) -> Value {
583 serde_json::json!({
584 "id": id,
585 "name": name,
586 "chunk_type": spec.type_id,
587 "fields": spec.fields.iter().map(|f| serde_json::json!({
588 "key": f.key,
589 "value": f.default.clone().unwrap_or_default(),
590 "field_type": if f.secret { "secret" } else if f.kind == "list" { "list" } else { "var" },
591 })).collect::<Vec<_>>(),
592 })
593}
594
595fn finding(rule: &Rule, chunk: &Value, field: &str, related: Vec<String>) -> Finding {
598 let name = chunk.get("name").and_then(Value::as_str).unwrap_or("");
599 Finding {
600 rule: rule.id,
601 severity: rule.severity,
602 chunk_id: chunk
603 .get("id")
604 .and_then(Value::as_str)
605 .unwrap_or("")
606 .to_string(),
607 chunk_name: name.to_string(),
608 chunk_type: chunk_type(chunk).to_string(),
609 field: field.to_string(),
610 message: rule
613 .message
614 .replace("{name}", name)
615 .replace("{field}", field),
616 related,
617 }
618}
619
620fn set(chunk: &Value, key: &str) -> bool {
621 !raw_field(chunk, key).trim().is_empty()
622}
623
624pub fn check(adapter: &Adapter, project: &Value, vault_names: &[String]) -> Vec<Finding> {
627 let chunks: Vec<&Value> = project
628 .get("chunks")
629 .and_then(Value::as_array)
630 .map(|cs| {
631 cs.iter()
632 .filter(|c| !c.get("disabled").and_then(Value::as_bool).unwrap_or(false))
633 .collect()
634 })
635 .unwrap_or_default();
636 let mut out = Vec::new();
637 for rule in &adapter.rules {
638 let of: Vec<&Value> = chunks
639 .iter()
640 .copied()
641 .filter(|c| chunk_type(c) == rule.type_id)
642 .collect();
643 match rule.kind.as_str() {
644 "unique" => {
645 let field = rule.field.as_deref().unwrap_or("@name");
646 let mut seen: Vec<&str> = Vec::new();
647 for c in &of {
648 let v = raw_field(c, field).trim();
649 if v.is_empty() {
650 continue;
651 }
652 if seen.contains(&v) {
653 out.push(finding(rule, c, field, vec![]));
654 } else {
655 seen.push(v);
656 }
657 }
658 }
659 "required" => {
660 let field = rule.field.as_deref().unwrap_or("");
661 for c in &of {
662 if !set(c, field) {
663 out.push(finding(rule, c, field, vec![]));
664 }
665 }
666 }
667 "exclusive" => {
668 for c in &of {
669 if rule.fields.iter().all(|f| set(c, f)) {
670 out.push(finding(rule, c, &rule.fields.join(" and "), vec![]));
671 }
672 }
673 }
674 "together" => {
675 for c in &of {
676 let n = rule.fields.iter().filter(|f| set(c, f)).count();
677 if n > 0 && n < rule.fields.len() {
678 out.push(finding(rule, c, &rule.fields.join(" and "), vec![]));
679 }
680 }
681 }
682 "choices" => {
683 let field = rule.field.as_deref().unwrap_or("");
684 for c in &of {
685 let v = raw_field(c, field).trim();
686 if !v.is_empty() && !v.starts_with("${") && !rule.values.iter().any(|x| x == v)
688 {
689 out.push(finding(rule, c, field, vec![]));
690 }
691 }
692 }
693 "needs_one_of" => {
694 let when = rule.when.as_deref().unwrap_or("");
695 for c in &of {
696 if set(c, when) && !rule.fields.iter().any(|f| set(c, f)) {
697 out.push(finding(rule, c, &rule.fields.join(" or "), vec![]));
698 }
699 }
700 }
701 _ => {}
702 }
703 }
704
705 let known: Vec<String> = vault_names.iter().map(|n| norm(n)).collect();
708 let mut reported: HashSet<String> = HashSet::new();
709 for c in &chunks {
710 if adapter.chunk_spec(chunk_type(c)).is_none() {
711 continue;
712 }
713 let Some(fields) = c.get("fields").and_then(Value::as_array) else {
714 continue;
715 };
716 for f in fields {
717 let raw = f.get("value").and_then(Value::as_str).unwrap_or("").trim();
718 let Some(name) = raw.strip_prefix("${").and_then(|r| r.strip_suffix('}')) else {
719 continue;
720 };
721 if name.starts_with("chunk:") || name.starts_with("bundle:") {
722 continue; }
724 let head = norm(name.split('/').next().unwrap_or(name));
725 let resolves = known
726 .iter()
727 .any(|p| !p.is_empty() && (head == *p || head.starts_with(&format!("{p}_"))));
728 let key = f.get("key").and_then(Value::as_str).unwrap_or("");
729 if !resolves && reported.insert(format!("{}|{key}|{name}", chunk_type(c))) {
730 out.push(Finding {
731 rule: leak(format!("stack-{}-unresolved-ref", adapter.id)),
732 severity: "warning",
733 chunk_id: c
734 .get("id")
735 .and_then(Value::as_str)
736 .unwrap_or("")
737 .to_string(),
738 chunk_name: c
739 .get("name")
740 .and_then(Value::as_str)
741 .unwrap_or("")
742 .to_string(),
743 chunk_type: chunk_type(c).to_string(),
744 field: key.to_string(),
745 message: format!("`{key}` reads `${{{name}}}`, which is not a vault entry"),
746 related: vec![],
747 });
748 }
749 }
750 }
751 out
752}
753
754fn norm(s: &str) -> String {
755 s.trim()
756 .to_lowercase()
757 .chars()
758 .map(|c| if c.is_alphanumeric() { c } else { '_' })
759 .collect()
760}
761
762#[cfg(test)]
763mod tests {
764 use super::*;
765 use serde_json::json;
766
767 fn chunk(t: &str, name: &str, fields: &[(&str, &str)]) -> Value {
768 json!({
769 "id": format!("id-{name}"), "name": name, "chunk_type": t,
770 "fields": fields.iter().map(|(k, v)| json!({"key": k, "value": v})).collect::<Vec<_>>()
771 })
772 }
773
774 fn project(ptype: &str, chunks: Vec<Value>) -> Value {
775 json!({"id": "p", "name": "p", "project_type": ptype, "chunks": chunks})
776 }
777
778 fn plain(raw: &str, _secret: bool) -> String {
779 raw.to_string()
780 }
781
782 fn render_plain(id: &str, p: &Value) -> String {
783 render(adapter(id).unwrap(), p, &plain)
784 }
785
786 #[test]
787 fn the_descriptors_are_internally_consistent() {
788 assert_eq!(
789 adapters().iter().map(|a| a.id.as_str()).collect::<Vec<_>>(),
790 vec![
791 "prometheus",
792 "grafana",
793 "homepage",
794 "homeassistant",
795 "compose-secret"
796 ]
797 );
798 let mut ids = HashSet::new();
799 let mut types = HashSet::new();
800 for a in adapters() {
801 assert!(ids.insert(&a.id), "duplicate adapter {}", a.id);
802 assert!(!a.file.is_empty() && !a.label.is_empty() && !a.abbr.is_empty());
803 for c in &a.chunks {
804 assert!(
805 types.insert(&c.type_id),
806 "chunk type {} is in two adapters",
807 c.type_id
808 );
809 assert!(c.type_id.starts_with(match a.id.as_str() {
810 "prometheus" => "prom_",
811 "grafana" => "grafana_",
812 "homeassistant" => "homeassistant_",
813 "compose-secret" => "compose_secret_",
814 _ => "homepage_",
815 }));
816 let keys: HashSet<_> = c.fields.iter().map(|f| &f.key).collect();
817 assert_eq!(
818 keys.len(),
819 c.fields.len(),
820 "duplicate field in {}",
821 c.type_id
822 );
823 }
824 for s in &a.starter {
825 assert!(
826 a.chunk_spec(&s.type_id).is_some(),
827 "starter names unknown chunk {}",
828 s.type_id
829 );
830 }
831 for r in &a.rules {
833 let spec = a
834 .chunk_spec(&r.type_id)
835 .unwrap_or_else(|| panic!("rule {} names unknown chunk {}", r.id, r.type_id));
836 let mut named: Vec<&str> = r.fields.iter().map(String::as_str).collect();
837 named.extend(r.field.as_deref());
838 named.extend(r.when.as_deref());
839 for f in named {
840 assert!(
841 f == "@name" || spec.fields.iter().any(|x| x.key == f),
842 "rule {} names unknown field {f}",
843 r.id
844 );
845 }
846 assert!(
847 [
848 "unique",
849 "required",
850 "exclusive",
851 "together",
852 "choices",
853 "needs_one_of"
854 ]
855 .contains(&r.kind.as_str()),
856 "rule kind {}",
857 r.kind
858 );
859 }
860 }
861 }
862
863 #[test]
864 fn every_field_the_output_reads_exists_in_the_chunk_it_reads_from() {
865 fn walk(n: &Value, chunk: Option<&str>, a: &Adapter, bad: &mut Vec<String>) {
867 match n {
868 Value::Object(o) => {
869 if let Some(f) = o.get("f").and_then(Value::as_str) {
870 let ok = chunk
871 .and_then(|c| a.chunk_spec(c))
872 .is_some_and(|s| f == "@name" || s.fields.iter().any(|x| x.key == f));
873 if !ok {
874 bad.push(format!("{}: field '{f}' not in {chunk:?}", a.id));
875 }
876 }
877 if let Some(fs) = o.get("when").and_then(Value::as_array) {
878 for f in fs.iter().filter_map(Value::as_str) {
879 let ok = chunk
880 .and_then(|c| a.chunk_spec(c))
881 .is_some_and(|s| s.fields.iter().any(|x| x.key == f));
882 if !ok {
883 bad.push(format!("{}: when '{f}' not in {chunk:?}", a.id));
884 }
885 }
886 }
887 let inner = o
888 .get("each")
889 .or_else(|| o.get("singleton"))
890 .and_then(Value::as_str)
891 .or_else(|| {
892 o.get("group")
893 .and_then(|g| g.get("of"))
894 .and_then(Value::as_str)
895 })
896 .or_else(|| o.get("of").and_then(Value::as_str))
898 .or(chunk);
899 if let Some(g) = o.get("group") {
900 if let Some(by) = g.get("by").and_then(Value::as_str) {
901 let of = g.get("of").and_then(Value::as_str);
902 let ok = of
903 .and_then(|c| a.chunk_spec(c))
904 .is_some_and(|s| s.fields.iter().any(|x| x.key == by));
905 if !ok {
906 bad.push(format!("{}: group by '{by}' not in {of:?}", a.id));
907 }
908 }
909 }
910 for (k, v) in o {
911 if k == "f" || k == "when" {
912 continue;
913 }
914 walk(v, inner, a, bad);
915 }
916 }
917 Value::Array(arr) => arr.iter().for_each(|v| walk(v, chunk, a, bad)),
918 _ => {}
919 }
920 }
921 for a in adapters() {
922 let mut bad = Vec::new();
923 walk(&a.output, None, a, &mut bad);
924 assert!(bad.is_empty(), "{bad:?}");
925 }
926 }
927
928 #[test]
929 fn a_prometheus_project_renders_a_prometheus_file() {
930 let p = project(
931 "prometheus",
932 vec![
933 chunk(
934 "prom_global",
935 "global",
936 &[("scrape_interval", "30s"), ("evaluation_interval", "15s")],
937 ),
938 chunk(
939 "prom_scrape",
940 "node",
941 &[("targets", "a:9100\nb:9100"), ("metrics_path", "/metrics")],
942 ),
943 chunk(
944 "prom_scrape",
945 "app",
946 &[
947 ("targets", "app:8080"),
948 ("scheme", "https"),
949 ("username", "scraper"),
950 ("password", "s3cret"),
951 ("ca_file", "/etc/ca.pem"),
952 ],
953 ),
954 chunk(
955 "prom_scrape",
956 "api",
957 &[("targets", "api:8080"), ("bearer_token", "tok")],
958 ),
959 chunk(
960 "prom_remote_write",
961 "cloud",
962 &[
963 ("url", "https://prom.example/api/v1/write"),
964 ("username", "u"),
965 ("password", "p"),
966 ],
967 ),
968 ],
969 );
970 assert_eq!(
971 render_plain("prometheus", &p),
972 "# Generated by UnENVerse
973global:
974 scrape_interval: \"30s\"
975 evaluation_interval: \"15s\"
976scrape_configs:
977 - job_name: node
978 metrics_path: \"/metrics\"
979 static_configs:
980 - targets:
981 - \"a:9100\"
982 - \"b:9100\"
983 - job_name: app
984 scheme: https
985 basic_auth:
986 username: scraper
987 password: s3cret
988 tls_config:
989 ca_file: \"/etc/ca.pem\"
990 static_configs:
991 - targets:
992 - \"app:8080\"
993 - job_name: api
994 authorization:
995 type: Bearer
996 credentials: tok
997 static_configs:
998 - targets:
999 - \"api:8080\"
1000remote_write:
1001 - url: \"https://prom.example/api/v1/write\"
1002 basic_auth:
1003 username: u
1004 password: p
1005"
1006 );
1007 }
1008
1009 #[test]
1010 fn an_empty_scrape_list_is_written_not_dropped_and_empty_sections_vanish() {
1011 let p = project("prometheus", vec![]);
1012 assert_eq!(
1013 render_plain("prometheus", &p),
1014 "# Generated by UnENVerse\nscrape_configs: []\n"
1015 );
1016 let only_global = project(
1017 "prometheus",
1018 vec![chunk("prom_global", "g", &[("scrape_interval", "1m")])],
1019 );
1020 assert!(render_plain("prometheus", &only_global)
1021 .starts_with("# Generated by UnENVerse\nglobal:\n scrape_interval: \"1m\"\n"));
1022 }
1023
1024 #[test]
1025 fn a_disabled_chunk_is_left_out() {
1026 let mut off = chunk("prom_scrape", "paused", &[("targets", "x:1")]);
1027 off["disabled"] = json!(true);
1028 let p = project(
1029 "prometheus",
1030 vec![off, chunk("prom_scrape", "active", &[("targets", "y:2")])],
1031 );
1032 let out = render_plain("prometheus", &p);
1033 assert!(out.contains("job_name: active") && !out.contains("paused"));
1034 }
1035
1036 #[test]
1037 fn strings_that_yaml_would_read_as_something_else_are_quoted() {
1038 let p = project(
1039 "prometheus",
1040 vec![chunk(
1041 "prom_scrape",
1042 "j",
1043 &[
1044 ("targets", "h:1"),
1045 ("username", "true"),
1046 ("password", "123456"),
1047 ],
1048 )],
1049 );
1050 let out = render_plain("prometheus", &p);
1051 assert!(out.contains("username: \"true\""), "{out}");
1052 assert!(out.contains("password: \"123456\""), "{out}");
1053 for (s, want) in [
1054 ("plain", "plain"),
1055 ("with-dash_and.dot", "with-dash_and.dot"),
1056 ("", "\"\""),
1057 ("null", "\"null\""),
1058 ("No", "\"No\""),
1059 ("~", "\"~\""),
1060 ("0x1F", "\"0x1F\""),
1061 ("1e3", "\"1e3\""),
1062 ("a: b", "\"a: b\""),
1063 ("- x", "\"- x\""),
1064 ("# c", "\"# c\""),
1065 ("line\nbreak", "\"line\\nbreak\""),
1066 ("quo\"te", "\"quo\\\"te\""),
1067 ("ünï", "\"ünï\""),
1068 ] {
1069 assert_eq!(scalar(s), want, "{s:?}");
1070 }
1071 }
1072
1073 #[test]
1074 fn the_resolver_decides_what_a_reference_becomes_and_is_told_which_fields_are_secret() {
1075 let p = project(
1076 "prometheus",
1077 vec![chunk(
1078 "prom_scrape",
1079 "j",
1080 &[
1081 ("targets", "h:1"),
1082 ("username", "u"),
1083 ("password", "${Prom/password}"),
1084 ],
1085 )],
1086 );
1087 let seen = std::cell::RefCell::new(Vec::new());
1088 let r = |raw: &str, secret: bool| {
1089 seen.borrow_mut().push((raw.to_string(), secret));
1090 if raw.starts_with("${") {
1091 "RESOLVED".into()
1092 } else {
1093 raw.to_string()
1094 }
1095 };
1096 let out = render(adapter("prometheus").unwrap(), &p, &r);
1097 assert!(out.contains("password: RESOLVED"), "{out}");
1098 let seen = seen.borrow();
1099 assert!(seen.contains(&("${Prom/password}".to_string(), true)));
1100 assert!(
1101 seen.contains(&("u".to_string(), false)),
1102 "username is not secret"
1103 );
1104 }
1105
1106 #[test]
1107 fn grafana_datasources_carry_credentials_in_secure_json_data() {
1108 let p = project(
1109 "grafana",
1110 vec![
1111 chunk(
1112 "grafana_datasource",
1113 "Prometheus",
1114 &[
1115 ("type", "prometheus"),
1116 ("url", "http://prometheus:9090"),
1117 ("access", "proxy"),
1118 ("is_default", "true"),
1119 ("api_token", "tok"),
1120 ],
1121 ),
1122 chunk(
1123 "grafana_datasource",
1124 "pg",
1125 &[
1126 ("type", "postgres"),
1127 ("url", "db:5432"),
1128 ("user", "grafana"),
1129 ("password", "pw"),
1130 ("database", "app"),
1131 ],
1132 ),
1133 ],
1134 );
1135 assert_eq!(
1136 render_plain("grafana", &p),
1137 "# Generated by UnENVerse
1138apiVersion: 1
1139datasources:
1140 - name: Prometheus
1141 type: prometheus
1142 access: proxy
1143 url: \"http://prometheus:9090\"
1144 isDefault: true
1145 jsonData:
1146 httpHeaderName1: Authorization
1147 secureJsonData:
1148 httpHeaderValue1: \"Bearer tok\"
1149 - name: pg
1150 type: postgres
1151 url: \"db:5432\"
1152 user: grafana
1153 database: app
1154 secureJsonData:
1155 password: pw
1156"
1157 );
1158 }
1159
1160 #[test]
1161 fn homepage_groups_services_in_first_seen_order_and_attaches_widget_credentials() {
1162 let p = project(
1163 "homepage",
1164 vec![
1165 chunk(
1166 "homepage_service",
1167 "Jellyfin",
1168 &[
1169 ("group", "Media"),
1170 ("href", "http://jf:8096"),
1171 ("icon", "jellyfin.png"),
1172 ("widget_type", "jellyfin"),
1173 ("widget_url", "http://jf:8096"),
1174 ("widget_key", "k1"),
1175 ],
1176 ),
1177 chunk(
1178 "homepage_service",
1179 "Pi-hole",
1180 &[("group", "Network"), ("href", "http://pi.hole/admin")],
1181 ),
1182 chunk(
1183 "homepage_service",
1184 "Sonarr",
1185 &[
1186 ("group", "Media"),
1187 ("widget_type", "sonarr"),
1188 ("widget_url", "http://sonarr:8989"),
1189 ("widget_key", "k2"),
1190 ],
1191 ),
1192 chunk("homepage_service", "Loose", &[("group", "")]),
1193 ],
1194 );
1195 assert_eq!(
1196 render_plain("homepage", &p),
1197 "# Generated by UnENVerse
1198- Media:
1199 - Jellyfin:
1200 icon: jellyfin.png
1201 href: \"http://jf:8096\"
1202 widget:
1203 type: jellyfin
1204 url: \"http://jf:8096\"
1205 key: k1
1206 - Sonarr:
1207 widget:
1208 type: sonarr
1209 url: \"http://sonarr:8989\"
1210 key: k2
1211- Network:
1212 - Pi-hole:
1213 href: \"http://pi.hole/admin\"
1214- Services:
1215 - Loose: {}
1216"
1217 );
1218 }
1219
1220 #[test]
1221 fn starter_chunks_carry_the_descriptors_defaults() {
1222 let a = adapter("prometheus").unwrap();
1223 let n = std::cell::Cell::new(0);
1224 let chunks = starter_chunks(a, &|| {
1225 n.set(n.get() + 1);
1226 format!("id{}", n.get())
1227 });
1228 assert_eq!(chunks.len(), 2);
1229 assert_eq!(chunks[0]["chunk_type"], "prom_global");
1230 let targets = chunks[1]["fields"]
1231 .as_array()
1232 .unwrap()
1233 .iter()
1234 .find(|f| f["key"] == "targets")
1235 .unwrap();
1236 assert_eq!(targets["value"], "localhost:9090");
1237 assert_eq!(targets["field_type"], "list");
1238 let pw = chunks[1]["fields"]
1239 .as_array()
1240 .unwrap()
1241 .iter()
1242 .find(|f| f["key"] == "password")
1243 .unwrap();
1244 assert_eq!(pw["field_type"], "secret");
1245 }
1246
1247 fn rules_of(a: &str, p: &Value, names: &[&str]) -> Vec<(String, String)> {
1248 let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
1249 check(adapter(a).unwrap(), p, &names)
1250 .into_iter()
1251 .map(|f| (f.rule.to_string(), f.chunk_name))
1252 .collect()
1253 }
1254
1255 #[test]
1256 fn each_prometheus_rule_fires_on_its_case_and_stays_silent_on_a_clean_file() {
1257 let clean = project(
1258 "prometheus",
1259 vec![chunk(
1260 "prom_scrape",
1261 "a",
1262 &[
1263 ("targets", "x:1"),
1264 ("scheme", "https"),
1265 ("username", "u"),
1266 ("password", "p"),
1267 ],
1268 )],
1269 );
1270 assert!(rules_of("prometheus", &clean, &[]).is_empty());
1271 let dup = project(
1272 "prometheus",
1273 vec![
1274 chunk("prom_scrape", "a", &[("targets", "x:1")]),
1275 chunk("prom_scrape", "a", &[("targets", "y:1")]),
1276 ],
1277 );
1278 assert_eq!(
1279 rules_of("prometheus", &dup, &[]),
1280 vec![("stack-prometheus-duplicate-job".into(), "a".into())]
1281 );
1282 let none = project(
1283 "prometheus",
1284 vec![chunk("prom_scrape", "a", &[("targets", " ")])],
1285 );
1286 assert_eq!(
1287 rules_of("prometheus", &none, &[])[0].0,
1288 "stack-prometheus-job-without-targets"
1289 );
1290 let both = project(
1291 "prometheus",
1292 vec![chunk(
1293 "prom_scrape",
1294 "a",
1295 &[
1296 ("targets", "x:1"),
1297 ("username", "u"),
1298 ("password", "p"),
1299 ("bearer_token", "t"),
1300 ],
1301 )],
1302 );
1303 assert_eq!(
1304 rules_of("prometheus", &both, &[])[0].0,
1305 "stack-prometheus-auth-conflict"
1306 );
1307 let half = project(
1308 "prometheus",
1309 vec![chunk(
1310 "prom_scrape",
1311 "a",
1312 &[("targets", "x:1"), ("username", "u")],
1313 )],
1314 );
1315 assert_eq!(
1316 rules_of("prometheus", &half, &[])[0].0,
1317 "stack-prometheus-basic-auth-incomplete"
1318 );
1319 let scheme = project(
1320 "prometheus",
1321 vec![chunk(
1322 "prom_scrape",
1323 "a",
1324 &[("targets", "x:1"), ("scheme", "ftp")],
1325 )],
1326 );
1327 assert_eq!(
1328 rules_of("prometheus", &scheme, &[])[0].0,
1329 "stack-prometheus-bad-scheme"
1330 );
1331 let rw = project(
1332 "prometheus",
1333 vec![chunk("prom_remote_write", "r", &[("url", "")])],
1334 );
1335 assert_eq!(
1336 rules_of("prometheus", &rw, &[])[0].0,
1337 "stack-prometheus-remote-write-without-url"
1338 );
1339 }
1340
1341 #[test]
1342 fn homepage_and_grafana_rules() {
1343 let dup = project(
1344 "homepage",
1345 vec![
1346 chunk("homepage_service", "A", &[]),
1347 chunk("homepage_service", "A", &[]),
1348 ],
1349 );
1350 assert_eq!(
1351 rules_of("homepage", &dup, &[])[0].0,
1352 "stack-homepage-duplicate-service"
1353 );
1354 let w = project(
1355 "homepage",
1356 vec![chunk(
1357 "homepage_service",
1358 "A",
1359 &[("widget_type", "sonarr"), ("widget_url", "http://x")],
1360 )],
1361 );
1362 assert_eq!(
1363 rules_of("homepage", &w, &[])[0].0,
1364 "stack-homepage-widget-without-credential"
1365 );
1366 let ok = project(
1367 "homepage",
1368 vec![chunk(
1369 "homepage_service",
1370 "A",
1371 &[
1372 ("widget_type", "sonarr"),
1373 ("widget_url", "http://x"),
1374 ("widget_key", "k"),
1375 ],
1376 )],
1377 );
1378 assert!(rules_of("homepage", &ok, &[]).is_empty());
1379 let half = project(
1380 "homepage",
1381 vec![chunk(
1382 "homepage_service",
1383 "A",
1384 &[("widget_type", "sonarr"), ("widget_key", "k")],
1385 )],
1386 );
1387 assert_eq!(
1388 rules_of("homepage", &half, &[])[0].0,
1389 "stack-homepage-widget-without-url"
1390 );
1391 let g = project(
1392 "grafana",
1393 vec![chunk(
1394 "grafana_datasource",
1395 "d",
1396 &[("type", ""), ("access", "weird")],
1397 )],
1398 );
1399 let got: Vec<String> = rules_of("grafana", &g, &[])
1400 .into_iter()
1401 .map(|r| r.0)
1402 .collect();
1403 assert!(got.contains(&"stack-grafana-datasource-without-type".to_string()));
1404 assert!(got.contains(&"stack-grafana-bad-access".to_string()));
1405 }
1406
1407 #[test]
1408 fn a_reference_to_nothing_in_the_vault_is_flagged_once_and_a_real_one_is_not() {
1409 let p = project(
1410 "prometheus",
1411 vec![chunk(
1412 "prom_scrape",
1413 "a",
1414 &[
1415 ("targets", "x:1"),
1416 ("username", "u"),
1417 ("password", "${Ghost/password}"),
1418 ],
1419 )],
1420 );
1421 let found = rules_of("prometheus", &p, &["Prometheus"]);
1422 assert_eq!(
1423 found,
1424 vec![("stack-prometheus-unresolved-ref".into(), "a".into())]
1425 );
1426 assert!(rules_of("prometheus", &p, &["Ghost"]).is_empty());
1427 let keyed = project(
1428 "prometheus",
1429 vec![chunk(
1430 "prom_scrape",
1431 "a",
1432 &[
1433 ("targets", "x:1"),
1434 ("username", "u"),
1435 ("password", "${Ghost_Admin}"),
1436 ],
1437 )],
1438 );
1439 assert!(
1440 rules_of("prometheus", &keyed, &["Ghost"]).is_empty(),
1441 "PROVIDER_KEYID still names the provider"
1442 );
1443 let chunkref = project(
1444 "prometheus",
1445 vec![chunk(
1446 "prom_scrape",
1447 "a",
1448 &[
1449 ("targets", "x:1"),
1450 ("username", "u"),
1451 ("password", "${chunk:other/pw}"),
1452 ],
1453 )],
1454 );
1455 assert!(rules_of("prometheus", &chunkref, &[]).is_empty());
1456 }
1457
1458 #[test]
1459 fn a_finding_never_carries_a_field_value() {
1460 let p = project(
1461 "prometheus",
1462 vec![chunk(
1463 "prom_scrape",
1464 "a",
1465 &[
1466 ("targets", "x:1"),
1467 ("username", "alice"),
1468 ("password", "hunter2-SECRET"),
1469 ("bearer_token", "tok-SECRET"),
1470 ],
1471 )],
1472 );
1473 for f in check(adapter("prometheus").unwrap(), &p, &[]) {
1474 let all = format!("{} {} {}", f.message, f.field, f.related.join(" "));
1475 assert!(!all.contains("SECRET") && !all.contains("alice"), "{all}");
1476 }
1477 }
1478
1479 #[test]
1480 fn home_assistant_writes_one_line_per_secret_and_skips_an_empty_or_disabled_one() {
1481 let mut off = chunk("homeassistant_secret", "off", &[("value", "hidden-value")]);
1482 off["disabled"] = json!(true);
1483 let p = project(
1484 "homeassistant",
1485 vec![
1486 chunk("homeassistant_secret", "api_token", &[("value", "abc_123")]),
1487 chunk("homeassistant_secret", "empty", &[("value", "")]),
1488 chunk("homeassistant_secret", "pin", &[("value", "123456")]),
1489 chunk(
1490 "homeassistant_secret",
1491 "url",
1492 &[("value", "http://x:1/a b")],
1493 ),
1494 off,
1495 ],
1496 );
1497 assert_eq!(
1498 render_plain("homeassistant", &p),
1499 "# Generated by UnENVerse\napi_token: abc_123\npin: \"123456\"\nurl: \"http://x:1/a b\"\n"
1500 );
1501 assert_eq!(
1503 render_plain("homeassistant", &project("homeassistant", vec![])),
1504 "# Generated by UnENVerse\n"
1505 );
1506 }
1507
1508 #[test]
1509 fn a_secret_name_is_quoted_when_yaml_would_read_it_as_something_else() {
1510 let p = project(
1511 "homeassistant",
1512 vec![chunk("homeassistant_secret", "yes", &[("value", "v")])],
1513 );
1514 assert_eq!(
1515 render_plain("homeassistant", &p),
1516 "# Generated by UnENVerse\n\"yes\": v\n"
1517 );
1518 }
1519
1520 #[test]
1521 fn a_compose_secret_is_exactly_its_value_and_empty_when_it_has_none() {
1522 let with = |v: &str| {
1523 project(
1524 "compose-secret",
1525 vec![chunk("compose_secret_value", "db", &[("value", v)])],
1526 )
1527 };
1528 assert_eq!(
1530 render_plain("compose-secret", &with("p@ss: w0rd #1")),
1531 "p@ss: w0rd #1"
1532 );
1533 assert_eq!(render_plain("compose-secret", &with("")), "");
1535 assert_eq!(
1536 render_plain("compose-secret", &project("compose-secret", vec![])),
1537 ""
1538 );
1539 assert_eq!(
1540 rules_of("compose-secret", &with(""), &[])[0].0,
1541 "stack-compose-secret-empty-secret"
1542 );
1543 assert!(rules_of("compose-secret", &with("x"), &[]).is_empty());
1544 }
1545
1546 #[test]
1547 fn a_pairs_node_whose_key_is_not_text_adds_no_line() {
1548 let a =
1550 json!({"pairs": {"of": "homeassistant_secret", "key": {"list": ["x"]}, "value": "v"}});
1551 let p = project(
1552 "homeassistant",
1553 vec![chunk("homeassistant_secret", "n", &[("value", "v")])],
1554 );
1555 let chunks: Vec<&Value> = p["chunks"].as_array().unwrap().iter().collect();
1556 let ctx = Ctx {
1557 adapter: adapter("homeassistant").unwrap(),
1558 chunks: &chunks,
1559 resolve: &plain,
1560 cur: None,
1561 };
1562 assert_eq!(eval(&a, &ctx), None);
1563 let keep_it = json!({"pairs": {"of": "homeassistant_secret", "key": {"list": ["x"]}, "value": "v"}, "keep": true});
1564 assert_eq!(eval(&keep_it, &ctx), Some(Y::Map(vec![])));
1565 }
1566}