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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
209 lines
5.8 KiB
Go
209 lines
5.8 KiB
Go
package check
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/netguard"
|
|
)
|
|
|
|
// HTTPConfig configures an HTTP(S) check.
|
|
type HTTPConfig struct {
|
|
Method string `json:"method"`
|
|
// ExpectStatus lists accepted codes or classes such as "2xx" or "301".
|
|
ExpectStatus []string `json:"expect_status"`
|
|
// Keyword must appear in the body, or must not if KeywordAbsent is set.
|
|
Keyword string `json:"keyword,omitempty"`
|
|
KeywordAbsent bool `json:"keyword_absent,omitempty"`
|
|
FollowRedirects bool `json:"follow_redirects"`
|
|
VerifyTLS bool `json:"verify_tls"`
|
|
Headers map[string]string `json:"headers,omitempty"`
|
|
}
|
|
|
|
// maxBody bounds how much of a response is searched for the keyword.
|
|
const maxBody = 1 << 20
|
|
|
|
type httpCheck struct{}
|
|
|
|
func (httpCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
|
if !validURL(target) {
|
|
return nil, invalid("invalid_target")
|
|
}
|
|
c := HTTPConfig{Method: http.MethodGet, ExpectStatus: []string{"2xx", "3xx"}, FollowRedirects: true, 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.MethodHead {
|
|
return nil, invalid("invalid_method")
|
|
}
|
|
if c.Method == http.MethodHead && c.Keyword != "" {
|
|
return nil, invalid("keyword_needs_get")
|
|
}
|
|
if len(c.ExpectStatus) == 0 || len(c.ExpectStatus) > 20 {
|
|
return nil, invalid("invalid_expect_status")
|
|
}
|
|
for _, p := range c.ExpectStatus {
|
|
if !validStatusPattern(p) {
|
|
return nil, invalid("invalid_expect_status")
|
|
}
|
|
}
|
|
if len(c.Keyword) > 500 {
|
|
return nil, invalid("invalid_config")
|
|
}
|
|
if !validHeaders(c.Headers) {
|
|
return nil, invalid("invalid_header")
|
|
}
|
|
return encode(c), nil
|
|
}
|
|
|
|
func validStatusPattern(p string) bool {
|
|
if len(p) == 3 && p[1:] == "xx" {
|
|
return p[0] >= '1' && p[0] <= '5'
|
|
}
|
|
n, err := strconv.Atoi(p)
|
|
return err == nil && n >= 100 && n <= 599
|
|
}
|
|
|
|
func statusMatches(code int, patterns []string) bool {
|
|
s := strconv.Itoa(code)
|
|
for _, p := range patterns {
|
|
if p == s || (strings.HasSuffix(p, "xx") && p[0] == s[0]) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (httpCheck) run(ctx context.Context, s Spec) Outcome {
|
|
c, err := decode[HTTPConfig](s.Config)
|
|
if err != nil {
|
|
return Outcome{Error: "invalid configuration"}
|
|
}
|
|
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)}
|
|
}
|
|
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
|
|
}
|
|
if c.Keyword != "" {
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
|
|
if err != nil {
|
|
o.Error = describeNetErr(err)
|
|
return o
|
|
}
|
|
found := bytes.Contains(body, []byte(c.Keyword))
|
|
switch {
|
|
case found && c.KeywordAbsent:
|
|
o.Error = "keyword present"
|
|
return o
|
|
case !found && !c.KeywordAbsent:
|
|
o.Error = "keyword not found"
|
|
return o
|
|
}
|
|
}
|
|
o.OK = true
|
|
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
|
|
var certErr *tls.CertificateVerificationError
|
|
var opErr *net.OpError
|
|
switch {
|
|
case errors.Is(err, netguard.ErrForbiddenAddress):
|
|
return "target resolves to a non-public address"
|
|
case errors.Is(err, context.DeadlineExceeded):
|
|
return "timeout"
|
|
case errors.As(err, &dnsErr):
|
|
if dnsErr.IsNotFound {
|
|
return "host not found"
|
|
}
|
|
return "dns lookup failed"
|
|
case errors.As(err, &certErr):
|
|
return "tls certificate invalid: " + certErr.Err.Error()
|
|
case errors.As(err, &opErr):
|
|
if opErr.Op == "dial" {
|
|
return "connection failed: " + opErr.Err.Error()
|
|
}
|
|
return opErr.Op + " failed: " + opErr.Err.Error()
|
|
}
|
|
return err.Error()
|
|
}
|