Files
uptimesebi/internal/check/http.go
T
Sebastian UnterschützandClaude Opus 5.5 48312fc59c feat(check): record what HTTP checks saw
With Spec.Capture, HTTP, JSON and Prometheus checks record every request
and response of the redirect chain, the time spent per phase, the remote
address, the server certificate and the first 32 KiB of the body.
Configured headers, credentials and cookie values are redacted. The
certificate is recorded before verification, which is now done in
VerifyConnection the way crypto/tls does it, because crypto/tls drops the
certificate exactly when verification fails.

Refs #79

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 12:09:42 +01:00

251 lines
6.8 KiB
Go

package check
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptrace"
"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)
rec := recorderFrom(ctx)
tlsConfig := &tls.Config{InsecureSkipVerify: !r.VerifyTLS} //nolint:gosec // opt-out chosen by the customer per monitor
if rec != nil {
tlsConfig = recordingTLS(rec, r.VerifyTLS)
}
tr := &http.Transport{
DialContext: d.DialContext,
TLSClientConfig: tlsConfig,
DisableKeepAlives: true,
TLSHandshakeTimeout: s.Timeout,
ForceAttemptHTTP2: true,
}
client := &http.Client{Transport: tr}
client.CheckRedirect = func(next *http.Request, via []*http.Request) error {
if !r.FollowRedirects {
// The redirect is the final response and recorded as such.
return http.ErrUseLastResponse
}
if rec != nil {
rec.step(via[len(via)-1], next.Response)
}
if len(via) >= 10 {
return errors.New("stopped after 10 redirects")
}
return nil
}
if rec != nil {
ctx = httptrace.WithClientTrace(ctx, rec.trace())
for k := range r.Headers {
rec.secretHeaders[http.CanonicalHeaderKey(k)] = true
}
}
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)
}
resp, err := client.Do(req)
if rec == nil {
return resp, err
}
if err != nil {
// The failed request may be a redirect target; url.Error names it.
failed := req
var uerr *url.Error
if errors.As(err, &uerr) {
if u, perr := url.Parse(uerr.URL); perr == nil {
failed = req.Clone(ctx)
failed.URL = u
}
}
rec.step(failed, nil)
return resp, err
}
rec.step(resp.Request, resp)
rec.ev.ContentType = resp.Header.Get("Content-Type")
resp.Body = captureBody{ReadCloser: resp.Body, r: rec}
return resp, nil
}
// 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()
}