package check import ( "context" "encoding/json" "fmt" "io" "net/http" "slices" "strconv" "strings" ) // JSONConfig configures a check of a JSON API: the response must have an // expected status and every assertion must hold. type JSONConfig struct { Method string `json:"method"` Headers map[string]string `json:"headers,omitempty"` Body string `json:"body,omitempty"` ExpectStatus []string `json:"expect_status"` VerifyTLS bool `json:"verify_tls"` Assertions []Assertion `json:"assertions"` } // Assertion compares the value at Path with Value. type Assertion struct { Path string `json:"path"` Op string `json:"op"` Value string `json:"value,omitempty"` } // Assertion operators. Ordering operators compare numbers; equality // compares numbers numerically and everything else as text. var assertionOps = []string{"==", "!=", ">", ">=", "<", "<=", "contains", "exists", "absent"} type jsonCheck struct{} func (jsonCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { if !validURL(target) { return nil, invalid("invalid_target") } c := JSONConfig{Method: http.MethodGet, ExpectStatus: []string{"2xx"}, VerifyTLS: true} if err := json.Unmarshal(config, &c); err != nil { return nil, invalid("invalid_config") } c.Method = strings.ToUpper(c.Method) if c.Method != http.MethodGet && c.Method != http.MethodPost { return nil, invalid("invalid_method") } if c.Method == http.MethodGet { c.Body = "" } if len(c.Body) > 10000 { return nil, invalid("invalid_config") } if c.Body != "" && !json.Valid([]byte(c.Body)) { return nil, invalid("invalid_json_body") } if !validHeaders(c.Headers) { return nil, invalid("invalid_header") } if len(c.ExpectStatus) == 0 { c.ExpectStatus = []string{"2xx"} } if len(c.ExpectStatus) > 20 { return nil, invalid("invalid_expect_status") } for _, p := range c.ExpectStatus { if !validStatusPattern(p) { return nil, invalid("invalid_expect_status") } } // Forms send empty rows for unused assertion slots. c.Assertions = slices.DeleteFunc(c.Assertions, func(a Assertion) bool { return strings.TrimSpace(a.Path) == "" }) if len(c.Assertions) == 0 || len(c.Assertions) > 10 { return nil, invalid("invalid_assertions") } for i, a := range c.Assertions { a.Path = strings.TrimSpace(a.Path) if _, err := parsePath(a.Path); err != nil || len(a.Path) > 200 || len(a.Value) > 500 { return nil, invalid("invalid_assertion_path") } if !slices.Contains(assertionOps, a.Op) { return nil, invalid("invalid_assertion_op") } if isOrdering(a.Op) { if _, err := strconv.ParseFloat(a.Value, 64); err != nil { return nil, invalid("invalid_assertion_value") } } c.Assertions[i] = a } return encode(c), nil } func isOrdering(op string) bool { return op == ">" || op == ">=" || op == "<" || op == "<=" } func (jsonCheck) run(ctx context.Context, s Spec) Outcome { c, err := decode[JSONConfig](s.Config) if err != nil { return Outcome{Error: "invalid configuration"} } resp, err := fetch(ctx, s, request{Method: c.Method, Headers: c.Headers, Body: c.Body, VerifyTLS: c.VerifyTLS, FollowRedirects: true}) if err != nil { return Outcome{Error: describeNetErr(err)} } defer func() { _ = resp.Body.Close() }() o := Outcome{StatusCode: resp.StatusCode} if !statusMatches(resp.StatusCode, c.ExpectStatus) { o.Error = fmt.Sprintf("unexpected status %d", resp.StatusCode) return o } var doc any if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&doc); err != nil { o.Error = "response is not JSON" return o } for _, a := range c.Assertions { if msg := a.evaluate(doc); msg != "" { o.Error = msg return o } } o.OK = true return o } // evaluate returns why a does not hold for doc, or "" if it does. func (a Assertion) evaluate(doc any) string { p, err := parsePath(a.Path) if err != nil { return "invalid path " + a.Path } v, found := p.lookup(doc) switch a.Op { case "exists": if !found { return a.Path + " is missing" } return "" case "absent": if found { return a.Path + " is present" } return "" } if !found { return a.Path + " is missing" } got := describe(v) fail := fmt.Sprintf("%s is %s, expected %s %s", a.Path, got, a.Op, a.Value) if isOrdering(a.Op) { n, ok := v.(float64) want, _ := strconv.ParseFloat(a.Value, 64) if !ok { return a.Path + " is not a number: " + got } holds := map[string]bool{">": n > want, ">=": n >= want, "<": n < want, "<=": n <= want}[a.Op] if !holds { return fail } return "" } var holds bool switch a.Op { case "==", "!=": holds = equal(v, a.Value) == (a.Op == "==") case "contains": holds = contains(v, a.Value) } if !holds { return fail } return "" } // equal compares a JSON value with the text of an assertion: numbers // numerically, strings as they are, other values in their JSON form. func equal(v any, want string) bool { switch x := v.(type) { case float64: n, err := strconv.ParseFloat(want, 64) return err == nil && x == n case string: return x == want } return describe(v) == want } // contains looks for want in strings and among array elements. func contains(v any, want string) bool { switch x := v.(type) { case string: return strings.Contains(x, want) case []any: return slices.ContainsFunc(x, func(e any) bool { return equal(e, want) }) } return false } // describe renders a value for messages, shortened to keep them readable. func describe(v any) string { b, _ := json.Marshal(v) out := string(b) if len(out) > 80 { out = out[:77] + "..." } return out }