/
schemavalidator.go
64 lines (53 loc) 路 1.6 KB
/
schemavalidator.go
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
// +build go1.13
package forensicstore
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/qri-io/jsonschema"
"github.com/tidwall/gjson"
"github.com/forensicanalysis/stixgo"
)
func setupSchemaValidation() {
// unmarshal schemas
registry := jsonschema.GetSchemaRegistry()
for _, content := range stixgo.FS {
// convert to draft/2019-09
content = bytes.Replace(content, []byte(`"definitions"`), []byte(`"$defs"`), -1)
content = bytes.Replace(content, []byte(`"#/definitions/`), []byte(`"#/$defs/`), -1)
content = bytes.Replace(content,
[]byte(`"$schema": "http://json-schema.org/draft-07/schema#",`),
[]byte(`"$schema": "https://json-schema.org/draft/2019-09/schema#",`),
-1,
)
schema := &jsonschema.Schema{}
if err := json.Unmarshal(content, schema); err != nil {
panic(err)
}
id := string(*schema.JSONProp("$id").(*jsonschema.ID))
schema.Resolve(nil, id)
registry.Register(schema)
}
}
func validateSchema(element JSONElement) (flaws []string, err error) {
elementType := gjson.GetBytes(element, discriminator)
if !elementType.Exists() {
flaws = append(flaws, "element needs to have a type")
}
schema := jsonschema.GetSchemaRegistry().GetKnown(fmt.Sprintf(
"http://raw.githubusercontent.com/oasis-open/cti-stix2-json-schemas/stix2.1/schemas/observables/%s.json",
elementType.String(),
))
if schema == nil {
return nil, nil
}
errs, err := schema.ValidateBytes(context.Background(), element)
if err != nil {
return nil, err
}
for _, verr := range errs {
flaws = append(flaws, fmt.Sprintf("failed to validate element: %s", verr))
}
return flaws, nil
}