Files

188 lines
4.8 KiB
Go

package audit
import (
"encoding/json"
"fmt"
"sort"
"strings"
"unicode/utf8"
)
// unsupportedSchemaKeywords are the keywords the validator understands; anything
// else in a schema is reported rather than silently ignored.
var supportedSchemaKeywords = map[string]bool{
"type": true, "required": true, "properties": true, "items": true,
"enum": true, "additionalProperties": true,
"description": true, "title": true, "$schema": true, "$id": true,
}
// validateValue checks value against a deliberately small JSON Schema subset:
// type, required, properties, items, enum, and additionalProperties:false.
//
// It returns the violations found, plus any keywords it could not evaluate. The
// second return is what keeps a partial check from being reported as a full one.
func validateValue(schema map[string]any, value any, path string) (problems, unsupported []string) {
for _, k := range sortedKeys(schema) {
if !supportedSchemaKeywords[k] {
unsupported = append(unsupported, fmt.Sprintf("%s: unsupported keyword %q", path, k))
}
}
if want, ok := schema["type"]; ok && !typeMatches(want, value) {
problems = append(problems, fmt.Sprintf("%s: expected type %s, got %s", path, describeAny(want), jsonTypeName(value)))
// A type mismatch makes the remaining keywords meaningless for this value.
return problems, unsupported
}
if enum, ok := schema["enum"].([]any); ok {
if !containsValue(enum, value) {
problems = append(problems, fmt.Sprintf("%s: value %s is not one of %s", path, describeAny(value), describeAny(enum)))
}
}
if required, ok := schema["required"].([]any); ok {
obj, isObj := value.(map[string]any)
if isObj {
for _, r := range required {
name, _ := r.(string)
if _, present := obj[name]; !present {
problems = append(problems, fmt.Sprintf("%s: required property %q is missing", path, name))
}
}
}
}
obj, isObj := value.(map[string]any)
if props, ok := schema["properties"].(map[string]any); ok && isObj {
for _, name := range sortedKeys(props) {
sub, ok := props[name].(map[string]any)
if !ok {
continue
}
if child, present := obj[name]; present {
p, u := validateValue(sub, child, path+"."+name)
problems = append(problems, p...)
unsupported = append(unsupported, u...)
}
}
if allow, ok := schema["additionalProperties"].(bool); ok && !allow {
for _, name := range sortedKeys(obj) {
if _, declared := props[name]; !declared {
problems = append(problems, fmt.Sprintf("%s: unexpected property %q (additionalProperties is false)", path, name))
}
}
}
}
if items, ok := schema["items"].(map[string]any); ok {
if arr, isArr := value.([]any); isArr {
for i, item := range arr {
p, u := validateValue(items, item, fmt.Sprintf("%s[%d]", path, i))
problems = append(problems, p...)
unsupported = append(unsupported, u...)
}
}
}
return problems, unsupported
}
func typeMatches(want, value any) bool {
if list, ok := want.([]any); ok {
for _, w := range list {
if typeMatches(w, value) {
return true
}
}
return false
}
name, ok := want.(string)
if !ok {
return true // malformed schema: reported elsewhere, not a value defect
}
got := jsonTypeName(value)
if got == name {
return true
}
// JSON Schema: an integer satisfies "number".
return got == "integer" && name == "number"
}
func jsonTypeName(value any) string {
switch v := value.(type) {
case nil:
return "null"
case bool:
return "boolean"
case string:
return "string"
case json.Number:
if _, err := v.Int64(); err == nil {
return "integer"
}
return "number"
case float64:
return "number"
case map[string]any:
return "object"
case []any:
return "array"
default:
return "unknown"
}
}
func containsValue(list []any, value any) bool {
for _, item := range list {
if equalValue(item, value) {
return true
}
}
return false
}
func equalValue(a, b any) bool {
if an, ok := a.(json.Number); ok {
if bn, ok := b.(json.Number); ok {
return an.String() == bn.String()
}
}
return fmt.Sprintf("%v", a) == fmt.Sprintf("%v", b)
}
// describeAny renders a schema or value fragment compactly for a finding.
func describeAny(v any) string {
raw, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf("%v", v)
}
s := string(raw)
if len(s) > 120 {
s = s[:117] + "..."
}
return s
}
func sortedKeys(m map[string]any) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// excerpt trims a quote for evidence without losing what triggered the rule, and
// without splitting a multi-byte character.
func excerpt(s string, max int) string {
s = strings.TrimSpace(s)
if len(s) <= max {
return s
}
cut := max
for cut > 0 && !utf8.RuneStart(s[cut]) {
cut--
}
return s[:cut] + "..."
}