diff --git a/pkg/effector/params/schema.go b/pkg/effector/params/schema.go new file mode 100644 index 00000000..494ac52e --- /dev/null +++ b/pkg/effector/params/schema.go @@ -0,0 +1,509 @@ +// Package params implements effector action parameters shared by the CCF API and agent +// (docs/effectors/action-parameters.md): the JSON Schema subset a plugin declares for a +// capability's parameters, validation of a parameter object against it, the operator's locks, +// and the merge the agent does before calling the plugin. +// +// Both sides import this package so the API never accepts parameters the agent then refuses. +// The validator is hand-written for the subset; it does no I/O and has no dependencies +// outside the standard library. +package params + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "maps" + "math" + "slices" + "strings" +) + +const ( + // MaxNesting is how deep objects nest below the root object. + MaxNesting = 3 + // DefaultMaxLength is a string field's maxLength when the schema sets none. + DefaultMaxLength = 4096 + // FormatTemplate is the only supported string format: a template the plugin renders. + FormatTemplate = "template" + // LockAll in an operator's locked list locks every parameter. + LockAll = "*" + // VariablesKeyword lists the variables a template field can use. + VariablesKeyword = "x-ccf-variables" + // OrderKeyword, on an object, lists its properties in the order a form shows them. + // Properties it doesn't list come after, by name. JSON objects (and jsonb) don't keep + // key order, so a schema that cares says it here. + OrderKeyword = "x-ccf-order" + // DependsOnKeyword, on a field, names a sibling boolean property: a form shows the + // field only while that property is true. Values are still validated either way. + DependsOnKeyword = "x-ccf-depends-on" +) + +// Types of the subset. +const ( + TypeObject = "object" + TypeString = "string" + TypeBoolean = "boolean" + TypeInteger = "integer" + TypeArray = "array" +) + +// ErrInvalidSchema wraps every SchemaError. +var ErrInvalidSchema = errors.New("invalid parameter schema") + +// SchemaError is a schema outside the supported subset, at a dotted property path ("" is the +// root). +type SchemaError struct { + Path string + Message string +} + +func (e *SchemaError) Error() string { + path := e.Path + if path == "" { + path = "(root)" + } + return fmt.Sprintf("%s: %s: %s", ErrInvalidSchema, path, e.Message) +} + +// Unwrap makes errors.Is(err, ErrInvalidSchema) true. +func (e *SchemaError) Unwrap() error { return ErrInvalidSchema } + +// Variable is a variable a template field can use (`x-ccf-variables`). +type Variable struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` +} + +// Schema is a parsed parameter schema node. Parse only returns nodes inside the subset. +type Schema struct { + Type string + Title string + Description string + // Default is the field's default (JSON-decoded: numbers are float64), when HasDefault. + Default any + HasDefault bool + + // Object. + Properties map[string]*Schema + + // String. + Enum []string + MaxLength *int + Format string + Variables []Variable + + // Integer. + Minimum, Maximum *int64 + + // Array: Items is a string node with an enum. + Items *Schema + + // Form hints: Order (objects) and DependsOn (any field but an object). + Order []string + DependsOn string +} + +// IsEmpty reports whether raw holds no schema (absent or JSON null): the action declares no +// parameters. +func IsEmpty(raw []byte) bool { + t := bytes.TrimSpace(raw) + return len(t) == 0 || bytes.Equal(t, []byte("null")) +} + +// ValidateSchema checks that a parameter schema stays inside the supported subset. An empty +// schema (no parameters) is valid. The error is a *SchemaError naming the path. +func ValidateSchema(schema []byte) error { + _, err := Parse(schema) + return err +} + +// Parse parses and checks a parameter schema. It returns nil, nil for an empty schema. +func Parse(raw []byte) (*Schema, error) { + if IsEmpty(raw) { + return nil, nil + } + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + var v any + if err := dec.Decode(&v); err != nil { + return nil, &SchemaError{Message: "not valid JSON: " + err.Error()} + } + if dec.More() { + return nil, &SchemaError{Message: "not a single JSON value"} + } + m, ok := v.(map[string]any) + if !ok { + return nil, &SchemaError{Message: "must be a JSON object"} + } + if t, _ := m["type"].(string); t != TypeObject { + return nil, &SchemaError{Message: `the root must have type "object"`} + } + return parseNode("", m, 0, true) +} + +var commonKeys = []string{"type", "title", "description", "default"} + +var keysByType = map[string][]string{ + TypeObject: {"properties", "additionalProperties", OrderKeyword}, + TypeString: {"enum", "maxLength", "format", VariablesKeyword, DependsOnKeyword}, + TypeBoolean: {DependsOnKeyword}, + TypeInteger: {"minimum", "maximum", DependsOnKeyword}, + TypeArray: {"items", DependsOnKeyword}, +} + +func parseNode(path string, m map[string]any, depth int, root bool) (*Schema, error) { + fail := func(format string, args ...any) (*Schema, error) { + return nil, &SchemaError{Path: path, Message: fmt.Sprintf(format, args...)} + } + rawType, present := m["type"] + if !present { + return fail(`"type" is required`) + } + typ, ok := rawType.(string) + if !ok { + return fail(`"type" must be a single string`) + } + extra, ok := keysByType[typ] + if !ok { + return fail("type %q isn't supported (object, string, boolean, integer, array)", typ) + } + for _, k := range slices.Sorted(maps.Keys(m)) { + if slices.Contains(commonKeys, k) || slices.Contains(extra, k) || (root && k == "$schema") { + continue + } + return fail("keyword %q isn't supported for type %s", k, typ) + } + s := &Schema{Type: typ} + var err error + if raw, ok := m[DependsOnKeyword]; ok { + name, ok := raw.(string) + if !ok || name == "" { + return fail("%q must be the name of a sibling boolean property", DependsOnKeyword) + } + s.DependsOn = name + } + if s.Title, err = optString(m, "title"); err != nil { + return fail("%s", err) + } + if s.Description, err = optString(m, "description"); err != nil { + return fail("%s", err) + } + + switch typ { + case TypeObject: + if depth > MaxNesting { + return fail("objects nest at most %d levels below the root", MaxNesting) + } + if ap, ok := m["additionalProperties"]; ok && ap != false { + return fail(`"additionalProperties" can only be false (unknown properties are always rejected)`) + } + s.Properties = map[string]*Schema{} + if rawProps, ok := m["properties"]; ok { + props, ok := rawProps.(map[string]any) + if !ok { + return fail(`"properties" must be an object`) + } + for _, name := range slices.Sorted(maps.Keys(props)) { + childPath := join(path, name) + if name == "" || name == LockAll || strings.ContainsAny(name, ".[]") { + return nil, &SchemaError{Path: childPath, Message: `a property name must be non-empty and contain no ".", "[", "]", nor be "*"`} + } + pm, ok := props[name].(map[string]any) + if !ok { + return nil, &SchemaError{Path: childPath, Message: "must be a schema object"} + } + child, err := parseNode(childPath, pm, depth+1, false) + if err != nil { + return nil, err + } + s.Properties[name] = child + } + } + for _, name := range slices.Sorted(maps.Keys(s.Properties)) { + child := s.Properties[name] + if child.DependsOn == "" { + continue + } + dep, ok := s.Properties[child.DependsOn] + if !ok || dep.Type != TypeBoolean || child.DependsOn == name { + return nil, &SchemaError{Path: join(path, name), Message: fmt.Sprintf("%q must name a sibling boolean property", DependsOnKeyword)} + } + } + if raw, ok := m[OrderKeyword]; ok { + list, ok := raw.([]any) + if !ok { + return fail("%q must be an array of property names", OrderKeyword) + } + seen := map[string]bool{} + for i, v := range list { + name, ok := v.(string) + if !ok || s.Properties[name] == nil || seen[name] { + return fail("%s[%d] must name a property of this object, once", OrderKeyword, i) + } + seen[name] = true + s.Order = append(s.Order, name) + } + } + case TypeString: + if raw, ok := m["enum"]; ok { + enum, err := stringEnum(raw) + if err != nil { + return fail("%s", err) + } + s.Enum = enum + } + if raw, ok := m["maxLength"]; ok { + n, ok := integer(raw) + if !ok || n < 0 || n > math.MaxInt32 { + return fail(`"maxLength" must be a non-negative integer`) + } + l := int(n) + s.MaxLength = &l + } + if raw, ok := m["format"]; ok { + if f, _ := raw.(string); f != FormatTemplate { + return fail(`"format" can only be %q`, FormatTemplate) + } + s.Format = FormatTemplate + } + if raw, ok := m[VariablesKeyword]; ok { + if s.Format != FormatTemplate { + return fail("%q is only allowed on a field with format %q", VariablesKeyword, FormatTemplate) + } + vars, err := variables(raw) + if err != nil { + return fail("%s", err) + } + s.Variables = vars + } + case TypeInteger: + for _, k := range []string{"minimum", "maximum"} { + raw, ok := m[k] + if !ok { + continue + } + n, ok := integer(raw) + if !ok { + return fail("%q must be an integer", k) + } + if k == "minimum" { + s.Minimum = &n + } else { + s.Maximum = &n + } + } + if s.Minimum != nil && s.Maximum != nil && *s.Minimum > *s.Maximum { + return fail(`"minimum" is greater than "maximum"`) + } + case TypeArray: + raw, ok := m["items"] + if !ok { + return fail(`an array needs "items" of type string with an enum`) + } + im, ok := raw.(map[string]any) + if !ok { + return fail(`"items" must be a schema object`) + } + itemPath := path + "[]" + for _, k := range slices.Sorted(maps.Keys(im)) { + if !slices.Contains([]string{"type", "enum", "title", "description"}, k) { + return nil, &SchemaError{Path: itemPath, Message: fmt.Sprintf("keyword %q isn't supported on array items", k)} + } + } + if t, _ := im["type"].(string); t != TypeString { + return nil, &SchemaError{Path: itemPath, Message: "array items must be of type string with an enum"} + } + rawEnum, ok := im["enum"] + if !ok { + return nil, &SchemaError{Path: itemPath, Message: "array items need an enum"} + } + enum, err := stringEnum(rawEnum) + if err != nil { + return nil, &SchemaError{Path: itemPath, Message: err.Error()} + } + items := &Schema{Type: TypeString, Enum: enum} + if items.Title, err = optString(im, "title"); err != nil { + return nil, &SchemaError{Path: itemPath, Message: err.Error()} + } + if items.Description, err = optString(im, "description"); err != nil { + return nil, &SchemaError{Path: itemPath, Message: err.Error()} + } + s.Items = items + } + + if raw, ok := m["default"]; ok { + def := normalize(raw) + if errs := s.validate("", def); len(errs) > 0 { + return fail(`"default" doesn't match the field: %s`, errs[0].Error()) + } + s.Default, s.HasDefault = def, true + } + return s, nil +} + +func optString(m map[string]any, key string) (string, error) { + raw, ok := m[key] + if !ok { + return "", nil + } + s, ok := raw.(string) + if !ok { + return "", fmt.Errorf("%q must be a string", key) + } + return s, nil +} + +func stringEnum(raw any) ([]string, error) { + list, ok := raw.([]any) + if !ok || len(list) == 0 { + return nil, errors.New(`"enum" must be a non-empty array of strings`) + } + out := make([]string, 0, len(list)) + for _, v := range list { + s, ok := v.(string) + if !ok { + return nil, errors.New(`"enum" must be a non-empty array of strings`) + } + if slices.Contains(out, s) { + return nil, fmt.Errorf(`"enum" lists %q twice`, s) + } + out = append(out, s) + } + return out, nil +} + +func variables(raw any) ([]Variable, error) { + list, ok := raw.([]any) + if !ok { + return nil, fmt.Errorf("%q must be an array of {name, description}", VariablesKeyword) + } + out := make([]Variable, 0, len(list)) + for i, v := range list { + vm, ok := v.(map[string]any) + if !ok { + return nil, fmt.Errorf("%s[%d] must be an object {name, description}", VariablesKeyword, i) + } + for k := range vm { + if k != "name" && k != "description" { + return nil, fmt.Errorf("%s[%d]: key %q isn't supported (name, description)", VariablesKeyword, i, k) + } + } + name, _ := vm["name"].(string) + if strings.TrimSpace(name) == "" { + return nil, fmt.Errorf("%s[%d].name must be a non-empty string", VariablesKeyword, i) + } + desc, err := optString(vm, "description") + if err != nil { + return nil, fmt.Errorf("%s[%d]: %w", VariablesKeyword, i, err) + } + out = append(out, Variable{Name: name, Description: desc}) + } + return out, nil +} + +// integer converts a JSON number (json.Number, float64 or any Go integer) with an integral +// value to int64. +func integer(v any) (int64, bool) { + switch n := v.(type) { + case json.Number: + if i, err := n.Int64(); err == nil { + return i, true + } + f, err := n.Float64() + if err != nil { + return 0, false + } + return floatInt(f) + case float64: + return floatInt(n) + case float32: + return floatInt(float64(n)) + case int: + return int64(n), true + case int8: + return int64(n), true + case int16: + return int64(n), true + case int32: + return int64(n), true + case int64: + return n, true + case uint: + return int64(n), n <= math.MaxInt64 + case uint8: + return int64(n), true + case uint16: + return int64(n), true + case uint32: + return int64(n), true + case uint64: + return int64(n), n <= math.MaxInt64 + } + return 0, false +} + +func floatInt(f float64) (int64, bool) { + // float64(math.MaxInt64) rounds up to 2^63, which int64 can't hold: compare with 2^63. + if math.IsNaN(f) || math.IsInf(f, 0) || f != math.Trunc(f) || f >= 0x1p63 || f < -0x1p63 { + return 0, false + } + return int64(f), true +} + +// normalize converts json.Number values (from parsing with UseNumber) to float64, so defaults +// look like values decoded by encoding/json. +func normalize(v any) any { + switch t := v.(type) { + case json.Number: + f, err := t.Float64() + if err != nil { + return t.String() + } + return f + case map[string]any: + out := make(map[string]any, len(t)) + for k, val := range t { + out[k] = normalize(val) + } + return out + case []any: + out := make([]any, len(t)) + for i, val := range t { + out[i] = normalize(val) + } + return out + } + return v +} + +func join(path, key string) string { + if path == "" { + return key + } + return path + "." + key +} + +// Lookup finds the node at a dotted property path, or nil. +func (s *Schema) Lookup(path string) *Schema { + if s == nil || path == "" { + return s + } + node := s + for _, part := range strings.Split(path, ".") { + if node.Type != TypeObject { + return nil + } + next, ok := node.Properties[part] + if !ok { + return nil + } + node = next + } + return node +} + +// HasPath reports whether a dotted property path names a field of the schema. +func (s *Schema) HasPath(path string) bool { + return path != "" && s.Lookup(path) != nil +} diff --git a/pkg/effector/params/schema_test.go b/pkg/effector/params/schema_test.go new file mode 100644 index 00000000..fc9f2089 --- /dev/null +++ b/pkg/effector/params/schema_test.go @@ -0,0 +1,164 @@ +package params + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// slackSchema is the kind of schema a notify plugin declares: an enum layout, a template per +// transition under `on`, toggles, integers and a multi-select. +const slackSchema = `{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "additionalProperties": false, + "properties": { + "layout": {"type": "string", "enum": ["short", "detailed"], "default": "detailed", "title": "Layout"}, + "mention": {"type": "boolean", "default": false}, + "max-subjects": {"type": "integer", "minimum": 1, "maximum": 50, "default": 10}, + "fields": {"type": "array", "items": {"type": "string", "enum": ["status", "labels", "url"]}, "default": ["status"]}, + "title": {"type": "string", "maxLength": 20}, + "on": { + "type": "object", + "properties": { + "activated": { + "type": "object", + "properties": { + "text": { + "type": "string", "format": "template", "default": "Failing: {{.Subject.Title}}", + "x-ccf-variables": [{"name": ".Subject.Title", "description": "The subject's title"}] + }, + "post": {"type": "boolean", "default": true} + } + }, + "repeated": { + "type": "object", + "properties": {"text": {"type": "string", "format": "template"}} + } + } + } + } +}` + +func TestValidateSchemaAccepts(t *testing.T) { + cases := map[string]string{ + "slack": slackSchema, + "empty": ``, + "null": `null`, + "bare object": `{"type": "object"}`, + "three levels": `{"type":"object","properties":{"a":{"type":"object","properties":{"b":{"type":"object","properties":{"c":{"type":"object","properties":{"x":{"type":"string"}}}}}}}}}`, + "integer range": `{"type":"object","properties":{"n":{"type":"integer","minimum":-5,"maximum":5,"default":0}}}`, + "maxLength 0": `{"type":"object","properties":{"s":{"type":"string","maxLength":0}}}`, + "object default": `{"type":"object","properties":{"o":{"type":"object","properties":{"a":{"type":"string"}},"default":{"a":"x"}}}}`, + } + for name, schema := range cases { + t.Run(name, func(t *testing.T) { + assert.NoError(t, ValidateSchema([]byte(schema))) + }) + } +} + +func TestValidateSchemaRejects(t *testing.T) { + cases := []struct { + name string + schema string + path string + want string + }{ + {"not json", `{`, "", "not valid JSON"}, + {"not an object", `[]`, "", "must be a JSON object"}, + {"root not object", `{"type":"string"}`, "", `root must have type "object"`}, + {"ref", `{"type":"object","properties":{"a":{"$ref":"#/defs/x"}}}`, "a", `"type" is required`}, + {"ref with type", `{"type":"object","properties":{"a":{"type":"string","$ref":"#/defs/x"}}}`, "a", `keyword "$ref" isn't supported`}, + {"oneOf", `{"type":"object","oneOf":[]}`, "", `keyword "oneOf"`}, + {"pattern", `{"type":"object","properties":{"s":{"type":"string","pattern":"^a"}}}`, "s", `keyword "pattern"`}, + {"format other", `{"type":"object","properties":{"s":{"type":"string","format":"email"}}}`, "s", `"format" can only be "template"`}, + {"type list", `{"type":"object","properties":{"s":{"type":["string","null"]}}}`, "s", "single string"}, + {"number type", `{"type":"object","properties":{"n":{"type":"number"}}}`, "n", `type "number" isn't supported`}, + {"null type", `{"type":"object","properties":{"n":{"type":"null"}}}`, "n", `type "null"`}, + {"additionalProperties true", `{"type":"object","additionalProperties":true}`, "", "additionalProperties"}, + {"required", `{"type":"object","required":["a"]}`, "", `keyword "required"`}, + {"$schema nested", `{"type":"object","properties":{"a":{"type":"string","$schema":"x"}}}`, "a", `keyword "$schema"`}, + {"too deep", `{"type":"object","properties":{"a":{"type":"object","properties":{"b":{"type":"object","properties":{"c":{"type":"object","properties":{"d":{"type":"object"}}}}}}}}}`, "a.b.c.d", "nest at most 3"}, + {"enum on integer", `{"type":"object","properties":{"n":{"type":"integer","enum":[1,2]}}}`, "n", `keyword "enum" isn't supported for type integer`}, + {"enum not strings", `{"type":"object","properties":{"s":{"type":"string","enum":[1]}}}`, "s", "non-empty array of strings"}, + {"enum empty", `{"type":"object","properties":{"s":{"type":"string","enum":[]}}}`, "s", "non-empty array"}, + {"enum duplicate", `{"type":"object","properties":{"s":{"type":"string","enum":["a","a"]}}}`, "s", "twice"}, + {"maxLength negative", `{"type":"object","properties":{"s":{"type":"string","maxLength":-1}}}`, "s", "non-negative integer"}, + {"maxLength float", `{"type":"object","properties":{"s":{"type":"string","maxLength":1.5}}}`, "s", "non-negative integer"}, + {"minimum float", `{"type":"object","properties":{"n":{"type":"integer","minimum":0.5}}}`, "n", `"minimum" must be an integer`}, + {"min > max", `{"type":"object","properties":{"n":{"type":"integer","minimum":5,"maximum":1}}}`, "n", "greater than"}, + {"array without items", `{"type":"object","properties":{"a":{"type":"array"}}}`, "a", `needs "items"`}, + {"array of integers", `{"type":"object","properties":{"a":{"type":"array","items":{"type":"integer"}}}}`, "a[]", "type string"}, + {"array items no enum", `{"type":"object","properties":{"a":{"type":"array","items":{"type":"string"}}}}`, "a[]", "need an enum"}, + {"array items maxLength", `{"type":"object","properties":{"a":{"type":"array","items":{"type":"string","enum":["x"],"maxLength":3}}}}`, "a[]", `keyword "maxLength"`}, + {"array uniqueItems", `{"type":"object","properties":{"a":{"type":"array","uniqueItems":true,"items":{"type":"string","enum":["x"]}}}}`, "a", `keyword "uniqueItems"`}, + {"variables without template", `{"type":"object","properties":{"s":{"type":"string","x-ccf-variables":[]}}}`, "s", "only allowed on a field with format"}, + {"variables malformed", `{"type":"object","properties":{"s":{"type":"string","format":"template","x-ccf-variables":[{"description":"x"}]}}}`, "s", "name must be a non-empty string"}, + {"variables extra key", `{"type":"object","properties":{"s":{"type":"string","format":"template","x-ccf-variables":[{"name":"a","type":"x"}]}}}`, "s", `key "type"`}, + {"default wrong type", `{"type":"object","properties":{"b":{"type":"boolean","default":"yes"}}}`, "b", `"default" doesn't match`}, + {"default not in enum", `{"type":"object","properties":{"s":{"type":"string","enum":["a"],"default":"b"}}}`, "s", `"default" doesn't match`}, + {"default too long", `{"type":"object","properties":{"s":{"type":"string","maxLength":2,"default":"abc"}}}`, "s", `"default" doesn't match`}, + {"default out of range", `{"type":"object","properties":{"n":{"type":"integer","maximum":3,"default":4}}}`, "n", `"default" doesn't match`}, + {"title not string", `{"type":"object","properties":{"s":{"type":"string","title":3}}}`, "s", `"title" must be a string`}, + {"dotted name", `{"type":"object","properties":{"a.b":{"type":"string"}}}`, "a.b", "property name"}, + {"star name", `{"type":"object","properties":{"*":{"type":"string"}}}`, "*", "property name"}, + {"property not object", `{"type":"object","properties":{"a":"string"}}`, "a", "must be a schema object"}, + {"properties not object", `{"type":"object","properties":[]}`, "", `"properties" must be an object`}, + } + for _, tt := range cases { + t.Run(tt.name, func(t *testing.T) { + err := ValidateSchema([]byte(tt.schema)) + require.Error(t, err) + assert.True(t, errors.Is(err, ErrInvalidSchema)) + var se *SchemaError + require.True(t, errors.As(err, &se)) + assert.Equal(t, tt.path, se.Path) + assert.Contains(t, se.Message, tt.want) + }) + } +} + +func TestLookupAndHasPath(t *testing.T) { + s, err := Parse([]byte(slackSchema)) + require.NoError(t, err) + assert.True(t, s.HasPath("on.activated.text")) + assert.Equal(t, FormatTemplate, s.Lookup("on.activated.text").Format) + assert.Equal(t, []Variable{{Name: ".Subject.Title", Description: "The subject's title"}}, s.Lookup("on.activated.text").Variables) + assert.False(t, s.HasPath("")) + assert.False(t, s.HasPath("layout.x")) + var nilSchema *Schema + assert.False(t, nilSchema.HasPath("layout")) +} + +func TestFormHints(t *testing.T) { + ok := `{"type":"object","x-ccf-order":["reply","text"],"properties":{ + "reply":{"type":"boolean","default":true}, + "text":{"type":"string","format":"template","x-ccf-depends-on":"reply"}}}` + s, err := Parse([]byte(ok)) + if err != nil { + t.Fatalf("valid hints rejected: %v", err) + } + if got := s.Order; len(got) != 2 || got[0] != "reply" || got[1] != "text" { + t.Fatalf("order = %v", got) + } + if s.Properties["text"].DependsOn != "reply" { + t.Fatalf("depends-on not parsed") + } + bad := map[string]string{ + "order names an unknown property": `{"type":"object","x-ccf-order":["nope"],"properties":{"a":{"type":"boolean"}}}`, + "order repeats a property": `{"type":"object","x-ccf-order":["a","a"],"properties":{"a":{"type":"boolean"}}}`, + "order isn't a list": `{"type":"object","x-ccf-order":"a","properties":{"a":{"type":"boolean"}}}`, + "depends on a missing sibling": `{"type":"object","properties":{"t":{"type":"string","x-ccf-depends-on":"x"}}}`, + "depends on a non-boolean": `{"type":"object","properties":{"s":{"type":"string"},"t":{"type":"string","x-ccf-depends-on":"s"}}}`, + "depends on itself": `{"type":"object","properties":{"b":{"type":"boolean","x-ccf-depends-on":"b"}}}`, + "depends-on on an object": `{"type":"object","properties":{"b":{"type":"boolean"},"o":{"type":"object","x-ccf-depends-on":"b"}}}`, + } + for name, schema := range bad { + if err := ValidateSchema([]byte(schema)); err == nil { + t.Errorf("%s: accepted", name) + } + } +} diff --git a/pkg/effector/params/validate.go b/pkg/effector/params/validate.go new file mode 100644 index 00000000..f6e22959 --- /dev/null +++ b/pkg/effector/params/validate.go @@ -0,0 +1,98 @@ +package params + +import ( + "fmt" + "maps" + "slices" + "strings" + "unicode/utf8" +) + +// FieldError is a parameter that fails validation, at a dotted path (`on.repeated.text`, +// `channels[1]`). Path "" is the parameter object itself. +type FieldError struct { + Path string `json:"path"` + Message string `json:"message"` +} + +func (e FieldError) Error() string { + if e.Path == "" { + return e.Message + } + return e.Path + ": " + e.Message +} + +// validate checks one value against the node at path. Parse uses it to check defaults. +func (s *Schema) validate(path string, v any) []FieldError { + fail := func(format string, args ...any) []FieldError { + return []FieldError{{Path: path, Message: fmt.Sprintf(format, args...)}} + } + switch s.Type { + case TypeObject: + m, ok := v.(map[string]any) + if !ok { + return fail("must be an object") + } + var out []FieldError + for _, k := range slices.Sorted(maps.Keys(m)) { + child, ok := s.Properties[k] + if !ok { + out = append(out, FieldError{Path: join(path, k), Message: "unknown parameter"}) + continue + } + out = append(out, child.validate(join(path, k), m[k])...) + } + return out + case TypeString: + str, ok := v.(string) + if !ok { + return fail("must be a string") + } + if len(s.Enum) > 0 && !slices.Contains(s.Enum, str) { + return fail("%q is not one of %s", str, strings.Join(s.Enum, ", ")) + } + limit := DefaultMaxLength + if s.MaxLength != nil { + limit = *s.MaxLength + } + if n := utf8.RuneCountInString(str); n > limit { + return fail("is %d characters long, at most %d allowed", n, limit) + } + return nil + case TypeBoolean: + if _, ok := v.(bool); !ok { + return fail("must be a boolean") + } + return nil + case TypeInteger: + n, ok := integer(v) + if !ok { + return fail("must be an integer") + } + if s.Minimum != nil && n < *s.Minimum { + return fail("must be at least %d", *s.Minimum) + } + if s.Maximum != nil && n > *s.Maximum { + return fail("must be at most %d", *s.Maximum) + } + return nil + case TypeArray: + var items []any + switch t := v.(type) { + case []any: + items = t + case []string: + for _, x := range t { + items = append(items, x) + } + default: + return fail("must be an array of strings") + } + var out []FieldError + for i, item := range items { + out = append(out, s.Items.validate(fmt.Sprintf("%s[%d]", path, i), item)...) + } + return out + } + return fail("unsupported type %q", s.Type) +}