From 0815148ea12aeab63936959aa420bbab947ab528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 11:45:11 +0100 Subject: [PATCH] feat(check): check JSON APIs against conditions on response values A JSON check requests a URL with GET or POST, optional headers and body, and requires the expected status and every condition: paths like checks[0].state compared with ==, !=, <, <=, >, >=, contains, exists or absent. Failures name the path, the value found and the expectation. HTTP and JSON checks share the request code and its network guard. Refs #26 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/check/check.go | 5 +- internal/check/http.go | 95 +++++++++----- internal/check/jsoncheck.go | 209 +++++++++++++++++++++++++++++++ internal/check/jsoncheck_test.go | 126 +++++++++++++++++++ internal/check/jsonpath.go | 69 ++++++++++ 5 files changed, 474 insertions(+), 30 deletions(-) create mode 100644 internal/check/jsoncheck.go create mode 100644 internal/check/jsoncheck_test.go create mode 100644 internal/check/jsonpath.go diff --git a/internal/check/check.go b/internal/check/check.go index 2e0a9f6..9df58af 100644 --- a/internal/check/check.go +++ b/internal/check/check.go @@ -22,13 +22,15 @@ const ( ICMP Type = "icmp" DNS Type = "dns" TLS Type = "tls" + // JSON checks an HTTP API's JSON response against assertions. + JSON Type = "json" // Heartbeat monitors are pinged by the monitored job; no checker runs // them. Heartbeat Type = "heartbeat" ) // Types lists every check type. -var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, Heartbeat} +var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Heartbeat} // Passive reports whether t is reported to us rather than run by checkers. func Passive(t Type) bool { return t == Heartbeat } @@ -84,6 +86,7 @@ var impls = map[Type]impl{ DNS: dnsCheck{}, TLS: tlsCheck{}, + JSON: jsonCheck{}, Heartbeat: heartbeatCheck{}, } diff --git a/internal/check/http.go b/internal/check/http.go index deef359..b2fed3f 100644 --- a/internal/check/http.go +++ b/internal/check/http.go @@ -36,8 +36,7 @@ const maxBody = 1 << 20 type httpCheck struct{} func (httpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) { - u, err := url.Parse(target) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil { + if !validURL(target) { return nil, invalid("invalid_target") } c := HTTPConfig{Method: http.MethodGet, ExpectStatus: []string{"2xx", "3xx"}, FollowRedirects: true, VerifyTLS: true} @@ -59,13 +58,11 @@ func (httpCheck) validate(target string, config json.RawMessage) (json.RawMessag return nil, invalid("invalid_expect_status") } } - if len(c.Keyword) > 500 || len(c.Headers) > 20 { + if len(c.Keyword) > 500 { return nil, invalid("invalid_config") } - for k, v := range c.Headers { - if k == "" || strings.ContainsAny(k+v, "\r\n") || strings.EqualFold(k, "Host") { - return nil, invalid("invalid_header") - } + if !validHeaders(c.Headers) { + return nil, invalid("invalid_header") } return encode(c), nil } @@ -93,28 +90,7 @@ func (httpCheck) run(ctx context.Context, s Spec) Outcome { if err != nil { return Outcome{Error: "invalid configuration"} } - d := netguard.Dialer(s.AllowPrivate, s.Timeout) - tr := &http.Transport{ - DialContext: d.DialContext, - TLSClientConfig: &tls.Config{InsecureSkipVerify: !c.VerifyTLS}, //nolint:gosec // opt-out chosen by the customer per monitor - DisableKeepAlives: true, - TLSHandshakeTimeout: s.Timeout, - ForceAttemptHTTP2: true, - } - defer tr.CloseIdleConnections() - client := &http.Client{Transport: tr} - if !c.FollowRedirects { - client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - } - req, err := http.NewRequestWithContext(ctx, c.Method, s.Target, nil) - if err != nil { - return Outcome{Error: "invalid target"} - } - req.Header.Set("User-Agent", "uptimesebi-checker") - for k, v := range c.Headers { - req.Header.Set(k, v) - } - resp, err := client.Do(req) + resp, err := fetch(ctx, s, request{Method: c.Method, Headers: c.Headers, VerifyTLS: c.VerifyTLS, FollowRedirects: c.FollowRedirects}) if err != nil { return Outcome{Error: describeNetErr(err)} } @@ -144,6 +120,67 @@ func (httpCheck) run(ctx context.Context, s Spec) Outcome { return o } +// request describes an HTTP request of a check. +type request struct { + Method string + Headers map[string]string + Body string + VerifyTLS bool + FollowRedirects bool +} + +// fetch sends r to s.Target through the network guard. The caller closes +// the response body. +func fetch(ctx context.Context, s Spec, r request) (*http.Response, error) { + d := netguard.Dialer(s.AllowPrivate, s.Timeout) + tr := &http.Transport{ + DialContext: d.DialContext, + TLSClientConfig: &tls.Config{InsecureSkipVerify: !r.VerifyTLS}, //nolint:gosec // opt-out chosen by the customer per monitor + DisableKeepAlives: true, + TLSHandshakeTimeout: s.Timeout, + ForceAttemptHTTP2: true, + } + client := &http.Client{Transport: tr} + if !r.FollowRedirects { + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + } + var body io.Reader + if r.Body != "" { + body = strings.NewReader(r.Body) + } + req, err := http.NewRequestWithContext(ctx, r.Method, s.Target, body) + if err != nil { + return nil, err + } + req.Header.Set("User-Agent", "uptimesebi-checker") + if r.Body != "" { + req.Header.Set("Content-Type", "application/json") + } + for k, v := range r.Headers { + req.Header.Set(k, v) + } + return client.Do(req) +} + +// validURL accepts absolute http(s) URLs without credentials. +func validURL(target string) bool { + u, err := url.Parse(target) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" && u.User == nil +} + +// validHeaders rejects headers that could smuggle requests or redirect them. +func validHeaders(h map[string]string) bool { + if len(h) > 20 { + return false + } + for k, v := range h { + if k == "" || strings.ContainsAny(k+v, "\r\n") || strings.EqualFold(k, "Host") { + return false + } + } + return true +} + // describeNetErr turns transport errors into short, stable messages. func describeNetErr(err error) string { var dnsErr *net.DNSError diff --git a/internal/check/jsoncheck.go b/internal/check/jsoncheck.go new file mode 100644 index 0000000..d74ae46 --- /dev/null +++ b/internal/check/jsoncheck.go @@ -0,0 +1,209 @@ +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 +} diff --git a/internal/check/jsoncheck_test.go b/internal/check/jsoncheck_test.go new file mode 100644 index 0000000..43a0756 --- /dev/null +++ b/internal/check/jsoncheck_test.go @@ -0,0 +1,126 @@ +package check + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestParsePath(t *testing.T) { + doc := map[string]any{"a": map[string]any{"b": []any{"x", map[string]any{"c": 1.0}}}, "list": []any{[]any{"deep"}}} + for _, tc := range []struct { + path string + want any + found bool + }{ + {"a.b[1].c", 1.0, true}, + {"$.a.b[0]", "x", true}, + {"list[0][0]", "deep", true}, + {"a.b[5]", nil, false}, + {"a.missing", nil, false}, + {"a.b.c", nil, false}, + } { + p, err := parsePath(tc.path) + if err != nil { + t.Fatalf("parsePath(%q) = %v", tc.path, err) + } + got, found := p.lookup(doc) + if found != tc.found || (found && got != tc.want) { + t.Errorf("lookup(%q) = %v, %t; want %v, %t", tc.path, got, found, tc.want, tc.found) + } + } + for _, bad := range []string{"a..b", "a[x]", "a[-1]", "a[1]b", "[", "a[1"} { + if _, err := parsePath(bad); err == nil { + t.Errorf("parsePath(%q) accepted", bad) + } + } +} + +func TestAssertions(t *testing.T) { + var doc any + _ = json.Unmarshal([]byte(`{"status":"ok","queue":{"depth":12},"healthy":true,"tags":["eu","db"],"version":"1.20"}`), &doc) + for _, tc := range []struct { + a Assertion + ok bool + want string + }{ + {Assertion{Path: "status", Op: "==", Value: "ok"}, true, ""}, + {Assertion{Path: "status", Op: "!=", Value: "ok"}, false, `status is "ok", expected != ok`}, + {Assertion{Path: "queue.depth", Op: "<", Value: "100"}, true, ""}, + {Assertion{Path: "queue.depth", Op: ">=", Value: "20"}, false, "queue.depth is 12, expected >= 20"}, + {Assertion{Path: "queue.depth", Op: "==", Value: "12.0"}, true, ""}, + {Assertion{Path: "healthy", Op: "==", Value: "true"}, true, ""}, + {Assertion{Path: "tags", Op: "contains", Value: "db"}, true, ""}, + {Assertion{Path: "version", Op: "contains", Value: "1.2"}, true, ""}, + {Assertion{Path: "version", Op: ">", Value: "1"}, false, `version is not a number: "1.20"`}, + {Assertion{Path: "error", Op: "absent"}, true, ""}, + {Assertion{Path: "queue", Op: "exists"}, true, ""}, + {Assertion{Path: "queue.lag", Op: "==", Value: "0"}, false, "queue.lag is missing"}, + } { + got := tc.a.evaluate(doc) + if (got == "") != tc.ok || (tc.want != "" && got != tc.want) { + t.Errorf("%+v.evaluate() = %q, want ok=%t %q", tc.a, got, tc.ok, tc.want) + } + } +} + +func TestJSONValidate(t *testing.T) { + ok := `{"assertions":[{"path":"status","op":"==","value":"ok"},{"path":"","op":"==","value":""}]}` + cfg, err := Validate(JSON, "https://api.example.com/health", json.RawMessage(ok)) + if err != nil { + t.Fatalf("Validate() = %v", err) + } + var c JSONConfig + _ = json.Unmarshal(cfg, &c) + if len(c.Assertions) != 1 || c.Method != http.MethodGet || c.ExpectStatus[0] != "2xx" { + t.Errorf("normalized config = %+v", c) + } + for body, code := range map[string]string{ + `{"assertions":[]}`: "invalid_assertions", + `{"assertions":[{"path":"a[","op":"=="}]}`: "invalid_assertion_path", + `{"assertions":[{"path":"a","op":"~"}]}`: "invalid_assertion_op", + `{"assertions":[{"path":"a","op":">","value":"x"}]}`: "invalid_assertion_value", + `{"method":"POST","body":"{","assertions":[{"path":"a","op":"exists"}]}`: "invalid_json_body", + } { + var inv ErrInvalid + if _, err := Validate(JSON, "https://api.example.com", json.RawMessage(body)); !errors.As(err, &inv) || inv.Code != code { + t.Errorf("Validate(%s) = %v, want %s", body, err, code) + } + } +} + +func TestJSONRun(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && r.Header.Get("Content-Type") != "application/json" { + http.Error(w, "bad", http.StatusBadRequest) + return + } + if r.Header.Get("Authorization") != "Bearer t" { + http.Error(w, "no", http.StatusUnauthorized) + return + } + _, _ = w.Write([]byte(`{"db":{"status":"degraded"}}`)) + })) + defer srv.Close() + run := func(cfg string) Outcome { + c, err := Validate(JSON, srv.URL, json.RawMessage(cfg)) + if err != nil { + t.Fatal(err) + } + return Run(context.Background(), Spec{Type: JSON, Target: srv.URL, Timeout: 2 * time.Second, Config: c, AllowPrivate: true}) + } + if o := run(`{"headers":{"Authorization":"Bearer t"},"assertions":[{"path":"db.status","op":"==","value":"degraded"}]}`); !o.OK { + t.Errorf("matching assertion failed: %+v", o) + } + if o := run(`{"method":"POST","body":"{}","headers":{"Authorization":"Bearer t"},"assertions":[{"path":"db.status","op":"==","value":"ok"}]}`); o.OK || !strings.Contains(o.Error, `db.status is "degraded"`) { + t.Errorf("failing assertion = %+v", o) + } + if o := run(`{"assertions":[{"path":"db","op":"exists"}]}`); o.OK || o.StatusCode != http.StatusUnauthorized { + t.Errorf("unexpected status = %+v", o) + } +} diff --git a/internal/check/jsonpath.go b/internal/check/jsonpath.go new file mode 100644 index 0000000..4703336 --- /dev/null +++ b/internal/check/jsonpath.go @@ -0,0 +1,69 @@ +package check + +import ( + "errors" + "strconv" + "strings" +) + +// A path selects a value in a JSON document: keys separated by dots and +// array indexes in brackets, e.g. "checks[0].status". A leading "$." is +// accepted for familiarity. Keys containing dots or brackets cannot be +// addressed. +type path []any // string keys and int indexes + +var errPath = errors.New("check: invalid path") + +func parsePath(s string) (path, error) { + s = strings.TrimPrefix(strings.TrimPrefix(s, "$"), ".") + if s == "" { + return path{}, nil + } + var p path + for _, part := range strings.Split(s, ".") { + key, rest, bracket := strings.Cut(part, "[") + if (key == "" && rest == "") || (bracket && rest == "") { + return nil, errPath + } + if key != "" { + p = append(p, key) + } + for rest != "" { + idx, after, ok := strings.Cut(rest, "]") + n, err := strconv.Atoi(idx) + if !ok || err != nil || n < 0 { + return nil, errPath + } + p = append(p, n) + rest = strings.TrimPrefix(after, "[") + if after != "" && !strings.HasPrefix(after, "[") { + return nil, errPath + } + } + } + return p, nil +} + +// lookup returns the value at p in doc, as decoded by encoding/json. +func (p path) lookup(doc any) (any, bool) { + cur := doc + for _, step := range p { + switch k := step.(type) { + case string: + m, ok := cur.(map[string]any) + if !ok { + return nil, false + } + if cur, ok = m[k]; !ok { + return nil, false + } + case int: + a, ok := cur.([]any) + if !ok || k >= len(a) { + return nil, false + } + cur = a[k] + } + } + return cur, true +}