MCPcopy
hub / github.com/crowdsecurity/crowdsec / ValidateYAML

Function ValidateYAML

pkg/acquisition/schemaval_test.go:46–102  ·  view source on GitHub ↗

ValidateYAML validates configYAML against schemaPath.

(configYAML []byte, schemaPath string)

Source from the content-addressed store, hash-verified

44
45// ValidateYAML validates configYAML against schemaPath.
46func ValidateYAML(configYAML []byte, schemaPath string) error {
47 if schemaPath == "" {
48 return errors.New("no schema provided")
49 }
50
51 configJSON, err := yaml.YAMLToJSON(configYAML)
52 if err != nil {
53 return fmt.Errorf("config: YAML->JSON: %w", err)
54 }
55
56 configDoc, err := jsonschema.UnmarshalJSON(bytes.NewReader(configJSON))
57 if err != nil {
58 return fmt.Errorf("config: decode JSON: %w", err)
59 }
60
61 c := jsonschema.NewCompiler()
62 c.DefaultDraft(jsonschema.Draft2020)
63
64 schemaYAML, err := os.ReadFile(schemaPath)
65 if err != nil {
66 return fmt.Errorf("read schema %q: %w", schemaPath, err)
67 }
68
69 schemaJSON, err := yaml.YAMLToJSON(schemaYAML)
70 if err != nil {
71 return fmt.Errorf("schema %q: YAML->JSON: %w", schemaPath, err)
72 }
73
74 schemaDoc, err := jsonschema.UnmarshalJSON(bytes.NewReader(schemaJSON))
75 if err != nil {
76 return fmt.Errorf("schema %q: decode JSON: %w", schemaPath, err)
77 }
78
79 abs, err := filepath.Abs(schemaPath)
80 if err != nil {
81 return fmt.Errorf("abs %q: %w", schemaPath, err)
82 }
83
84 if err := c.AddResource(abs, schemaDoc); err != nil {
85 return fmt.Errorf("add schema resource %q: %w", abs, err)
86 }
87
88 sch, err := c.Compile(abs)
89 if err != nil {
90 return fmt.Errorf("compile schema %q: %w", abs, err)
91 }
92
93 if err := sch.Validate(configDoc); err != nil {
94 var ve *jsonschema.ValidationError
95 if errors.As(err, &ve) {
96 return compactSchemaErr(ve)
97 }
98 return err
99 }
100
101 return nil
102}

Callers 1

TestParseSourceConfigFunction · 0.85

Calls 5

compactSchemaErrFunction · 0.85
NewReaderMethod · 0.80
ValidateMethod · 0.65
UnmarshalJSONMethod · 0.45
CompileMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…