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
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 12:09:42 +01:00
1 parent 94b519b421
commit 48312fc59c
4 files changed
+499 -3

No files matched your search

+13
View File
@@ -46,6 +46,8 @@ type Spec struct {
// AllowPrivate permits targets on private networks. It is false for // AllowPrivate permits targets on private networks. It is false for
// shared checkers in the cloud edition. // shared checkers in the cloud edition.
AllowPrivate bool AllowPrivate bool
// Capture records Evidence of HTTP exchanges.
Capture bool
} }
// Outcome is the result of one check run. // Outcome is the result of one check run.
@@ -56,6 +58,9 @@ type Outcome struct {
StatusCode int StatusCode int
// Error explains a failure in a form suitable for showing to customers. // Error explains a failure in a form suitable for showing to customers.
Error string Error string
// Evidence is set when Spec.Capture was and the check made HTTP
// requests.
Evidence *Evidence
} }
// ErrInvalid is wrapped by Validate errors. Its message is the code shown to // ErrInvalid is wrapped by Validate errors. Its message is the code shown to
@@ -115,6 +120,11 @@ func Run(ctx context.Context, s Spec) Outcome {
} }
ctx, cancel := context.WithTimeout(ctx, s.Timeout) ctx, cancel := context.WithTimeout(ctx, s.Timeout)
defer cancel() defer cancel()
var rec *recorder
if s.Capture {
rec = newRecorder()
ctx = context.WithValue(ctx, recorderKey{}, rec)
}
start := time.Now() start := time.Now()
o := im.run(ctx, s) o := im.run(ctx, s)
if o.Latency == 0 { if o.Latency == 0 {
@@ -126,6 +136,9 @@ func Run(ctx context.Context, s Spec) Outcome {
if errors.Is(ctx.Err(), context.DeadlineExceeded) && !o.OK { if errors.Is(ctx.Err(), context.DeadlineExceeded) && !o.OK {
o.Error = "timeout after " + s.Timeout.String() o.Error = "timeout after " + s.Timeout.String()
} }
if rec != nil {
o.Evidence = rec.evidence(o)
}
return o return o
} }
+319
View File
@@ -0,0 +1,319 @@
package check
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"math"
"net/http"
"net/http/httptrace"
"strings"
"sync"
"time"
"unicode/utf8"
)
// Evidence is what a check saw of an HTTP exchange: every request and
// response of the redirect chain, where the time went, the server's
// certificate and the start of the final body. Secrets are redacted before
// it leaves the checker.
type Evidence struct {
Steps []HTTPStep `json:"steps"`
RemoteAddr string `json:"remote_addr,omitempty"`
Timing Timing `json:"timing"`
TLS *TLSInfo `json:"tls,omitempty"`
// FailedAt names the stage a failed exchange stopped in: dns,
// connect, tls, response or body.
FailedAt string `json:"failed_at,omitempty"`
ContentType string `json:"content_type,omitempty"`
Body string `json:"body,omitempty"`
BodyTruncated bool `json:"body_truncated,omitempty"`
// BodyBinary is set for bodies that are not text; they are not kept.
BodyBinary bool `json:"body_binary,omitempty"`
}
// HTTPStep is one request and its response.
type HTTPStep struct {
Method string `json:"method"`
URL string `json:"url"`
Status int `json:"status,omitempty"`
Proto string `json:"proto,omitempty"`
RequestHeaders map[string][]string `json:"request_headers,omitempty"`
ResponseHeaders map[string][]string `json:"response_headers,omitempty"`
}
// Timing splits the duration of the last connection, in milliseconds.
// Phases that did not happen, such as DNS for an IP target, are zero.
type Timing struct {
DNS float64 `json:"dns_ms"`
Connect float64 `json:"connect_ms"`
TLS float64 `json:"tls_ms"`
Wait float64 `json:"wait_ms"`
Download float64 `json:"download_ms"`
Total float64 `json:"total_ms"`
}
// TLSInfo describes the negotiated connection and the leaf certificate.
type TLSInfo struct {
Version string `json:"version"`
Cipher string `json:"cipher,omitempty"`
Subject string `json:"subject"`
Issuer string `json:"issuer"`
DNSNames []string `json:"dns_names,omitempty"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
}
// maxEvidenceBody bounds the captured body.
const maxEvidenceBody = 32 << 10
// redacted replaces secret header values.
const redacted = "<redacted>"
type recorderKey struct{}
// recorder collects evidence while a check runs.
type recorder struct {
mu sync.Mutex
ev Evidence
start time.Time
stage string
marks map[string]time.Time
firstByte time.Time
done time.Time
body bytes.Buffer
// secretHeaders are request headers configured by the customer; their
// values often are credentials.
secretHeaders map[string]bool
}
func newRecorder() *recorder {
return &recorder{start: time.Now(), marks: map[string]time.Time{}, secretHeaders: map[string]bool{}}
}
func recorderFrom(ctx context.Context) *recorder {
r, _ := ctx.Value(recorderKey{}).(*recorder)
return r
}
func ms(d time.Duration) float64 { return math.Round(float64(d)/float64(time.Millisecond)*10) / 10 }
func (r *recorder) mark(stage string) {
r.mu.Lock()
defer r.mu.Unlock()
r.stage = stage
r.marks[stage] = time.Now()
}
func (r *recorder) since(stage string) float64 {
if t, ok := r.marks[stage]; ok {
return ms(time.Since(t))
}
return 0
}
func (r *recorder) trace() *httptrace.ClientTrace {
return &httptrace.ClientTrace{
DNSStart: func(httptrace.DNSStartInfo) { r.mark("dns") },
DNSDone: func(httptrace.DNSDoneInfo) {
r.mu.Lock()
r.ev.Timing.DNS = r.since("dns")
r.mu.Unlock()
},
ConnectStart: func(string, string) { r.mark("connect") },
ConnectDone: func(_, addr string, err error) {
r.mu.Lock()
r.ev.Timing.Connect = r.since("connect")
if err == nil {
r.ev.RemoteAddr = addr
}
r.mu.Unlock()
},
TLSHandshakeStart: func() { r.mark("tls") },
TLSHandshakeDone: func(cs tls.ConnectionState, _ error) {
r.mu.Lock()
defer r.mu.Unlock()
r.ev.Timing.TLS = r.since("tls")
if r.ev.TLS != nil && cs.Version != 0 {
r.ev.TLS.Version = tls.VersionName(cs.Version)
r.ev.TLS.Cipher = tls.CipherSuiteName(cs.CipherSuite)
}
},
WroteRequest: func(httptrace.WroteRequestInfo) { r.mark("response") },
GotFirstResponseByte: func() {
r.mu.Lock()
r.ev.Timing.Wait = r.since("response")
r.firstByte = time.Now()
r.stage = "body"
r.mu.Unlock()
},
}
}
func tlsInfo(cs tls.ConnectionState, c *x509.Certificate) *TLSInfo {
info := &TLSInfo{
Subject: c.Subject.String(), Issuer: c.Issuer.String(), DNSNames: c.DNSNames,
NotBefore: c.NotBefore, NotAfter: c.NotAfter,
}
if cs.Version != 0 {
info.Version = tls.VersionName(cs.Version)
}
if cs.CipherSuite != 0 {
info.Cipher = tls.CipherSuiteName(cs.CipherSuite)
}
return info
}
// recordingTLS verifies certificates like crypto/tls does, but records the
// server's certificate first: crypto/tls drops it when verification fails,
// which is when it matters most.
func recordingTLS(r *recorder, verify bool) *tls.Config {
cfg := &tls.Config{InsecureSkipVerify: true} //nolint:gosec // verified in VerifyConnection unless the customer opted out
cfg.VerifyConnection = func(cs tls.ConnectionState) error {
if len(cs.PeerCertificates) == 0 {
return errors.New("tls: server sent no certificate")
}
r.mu.Lock()
r.ev.TLS = tlsInfo(cs, cs.PeerCertificates[0])
r.mu.Unlock()
if !verify {
return nil
}
opts := x509.VerifyOptions{DNSName: cs.ServerName, Roots: cfg.RootCAs, Intermediates: x509.NewCertPool()}
for _, c := range cs.PeerCertificates[1:] {
opts.Intermediates.AddCert(c)
}
if _, err := cs.PeerCertificates[0].Verify(opts); err != nil {
return &tls.CertificateVerificationError{UnverifiedCertificates: cs.PeerCertificates, Err: err}
}
return nil
}
return cfg
}
// step records one exchange of the chain.
func (r *recorder) step(req *http.Request, resp *http.Response) {
s := HTTPStep{Method: req.Method, URL: req.URL.Redacted(), RequestHeaders: r.requestHeaders(req.Header)}
if resp != nil {
s.Status, s.Proto, s.ResponseHeaders = resp.StatusCode, resp.Proto, responseHeaders(resp.Header)
}
r.mu.Lock()
r.ev.Steps = append(r.ev.Steps, s)
r.mu.Unlock()
}
func (r *recorder) requestHeaders(h http.Header) map[string][]string {
out := make(map[string][]string, len(h))
for k, vs := range h {
if r.secretHeaders[http.CanonicalHeaderKey(k)] || sensitiveHeader(k) {
out[k] = []string{redacted}
continue
}
out[k] = vs
}
return out
}
func sensitiveHeader(k string) bool {
switch http.CanonicalHeaderKey(k) {
case "Authorization", "Proxy-Authorization", "Cookie":
return true
}
return false
}
// responseHeaders keeps cookie names but not their values.
func responseHeaders(h http.Header) map[string][]string {
out := make(map[string][]string, len(h))
for k, vs := range h {
switch {
case http.CanonicalHeaderKey(k) == "Set-Cookie":
names := make([]string, len(vs))
for i, v := range vs {
name, _, _ := strings.Cut(v, "=")
names[i] = name + "=" + redacted
}
out[k] = names
case sensitiveHeader(k):
out[k] = []string{redacted}
default:
out[k] = vs
}
}
return out
}
// captureBody keeps the start of a response body. On Close it reads up to
// the capture limit if the check stopped reading earlier.
type captureBody struct {
io.ReadCloser
r *recorder
}
// Read implements io.Reader.
func (b captureBody) Read(p []byte) (int, error) {
n, err := b.ReadCloser.Read(p)
b.r.mu.Lock()
if room := maxEvidenceBody - b.r.body.Len(); room > 0 {
b.r.body.Write(p[:min(n, room)])
}
if n > 0 && b.r.body.Len() >= maxEvidenceBody {
b.r.ev.BodyTruncated = true
}
b.r.mu.Unlock()
return n, err
}
// Close implements io.Closer.
func (b captureBody) Close() error {
b.r.mu.Lock()
room := maxEvidenceBody - b.r.body.Len()
b.r.mu.Unlock()
if room > 0 {
_, _ = io.Copy(io.Discard, io.LimitReader(b, int64(room)+1))
}
b.r.mu.Lock()
b.r.done = time.Now()
b.r.mu.Unlock()
return b.ReadCloser.Close()
}
// evidence finishes the recording for an outcome.
func (r *recorder) evidence(o Outcome) *Evidence {
r.mu.Lock()
defer r.mu.Unlock()
ev := r.ev
ev.Timing.Total = ms(time.Since(r.start))
if !r.firstByte.IsZero() && !r.done.IsZero() {
ev.Timing.Download = ms(r.done.Sub(r.firstByte))
}
if !o.OK && o.StatusCode == 0 {
ev.FailedAt = r.stage
}
body := r.body.Bytes()
switch {
case len(body) == 0:
case !utf8.Valid(body) && !utf8.Valid(trimPartialRune(body)), bytes.IndexByte(body, 0) >= 0:
ev.BodyBinary = true
default:
ev.Body = string(trimPartialRune(body))
}
if len(ev.Steps) == 0 && ev.TLS == nil && ev.RemoteAddr == "" {
return nil
}
return &ev
}
// trimPartialRune drops a multi-byte character cut off by the capture limit.
func trimPartialRune(b []byte) []byte {
for i := 0; i < utf8.UTFMax && len(b) > 0; i++ {
if utf8.Valid(b) {
return b
}
b = b[:len(b)-1]
}
return b
}
+122
View File
@@ -0,0 +1,122 @@
package check
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestEvidence(t *testing.T) {
srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/old":
http.Redirect(w, r, "/new", http.StatusMovedPermanently)
case "/new":
http.SetCookie(w, &http.Cookie{Name: "session", Value: "very-secret"})
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte("<h1>Maintenance</h1>" + strings.Repeat("x", 40<<10)))
case "/binary":
_, _ = w.Write([]byte{0x89, 'P', 'N', 'G', 0, 0, 1})
}
}))
defer srv.Close()
run := func(path string, cfg map[string]any) Outcome {
t.Helper()
raw, _ := json.Marshal(cfg)
c, err := Validate(HTTP, srv.URL+path, raw)
if err != nil {
t.Fatal(err)
}
return Run(context.Background(), Spec{Type: HTTP, Target: srv.URL + path, Timeout: 3 * time.Second, Config: c, AllowPrivate: true, Capture: true})
}
o := run("/old", map[string]any{"verify_tls": false, "headers": map[string]string{"X-Api-Key": "k3y"}})
ev := o.Evidence
if o.OK || ev == nil {
t.Fatalf("Run() = %+v, want a failure with evidence", o)
}
if len(ev.Steps) != 2 || ev.Steps[0].Status != http.StatusMovedPermanently || !strings.HasSuffix(ev.Steps[1].URL, "/new") || ev.Steps[1].Status != http.StatusServiceUnavailable {
t.Errorf("steps = %+v, want the redirect and the final response", ev.Steps)
}
if got := ev.Steps[0].RequestHeaders["X-Api-Key"]; len(got) != 1 || got[0] != redacted {
t.Errorf("configured header = %v, want redacted", got)
}
if got := ev.Steps[1].ResponseHeaders["Set-Cookie"]; len(got) != 1 || got[0] != "session="+redacted {
t.Errorf("Set-Cookie = %v, want the name only", got)
}
if !strings.HasPrefix(ev.Body, "<h1>Maintenance</h1>") || len(ev.Body) != maxEvidenceBody || !ev.BodyTruncated || ev.ContentType != "text/html" {
t.Errorf("body = %d bytes, truncated %t, type %q", len(ev.Body), ev.BodyTruncated, ev.ContentType)
}
if ev.TLS == nil || ev.TLS.Version == "" || ev.TLS.NotAfter.IsZero() || ev.RemoteAddr == "" {
t.Errorf("tls = %+v, remote = %q", ev.TLS, ev.RemoteAddr)
}
if ev.Timing.Total <= 0 || ev.Timing.Total < ev.Timing.Wait {
t.Errorf("timing = %+v", ev.Timing)
}
// Verification failures still show the certificate that caused them.
o = run("/new", map[string]any{"verify_tls": true})
if o.Evidence == nil || o.Evidence.TLS == nil || o.Evidence.FailedAt != "tls" {
t.Errorf("verification failure evidence = %+v", o.Evidence)
}
if o = run("/binary", map[string]any{"verify_tls": false}); !o.Evidence.BodyBinary || o.Evidence.Body != "" {
t.Errorf("binary body = %+v", o.Evidence)
}
// Refused connections stop at connect.
dead := httptest.NewServer(http.NotFoundHandler())
url := dead.URL
dead.Close()
raw, _ := Validate(HTTP, url, nil)
o = Run(context.Background(), Spec{Type: HTTP, Target: url, Timeout: time.Second, Config: raw, AllowPrivate: true, Capture: true})
if o.Evidence == nil || o.Evidence.FailedAt != "connect" || len(o.Evidence.Steps) != 1 {
t.Errorf("refused connection evidence = %+v", o.Evidence)
}
// Without Capture nothing is recorded.
raw, _ = Validate(HTTP, srv.URL+"/new", json.RawMessage(`{"verify_tls":false}`))
if o = Run(context.Background(), Spec{Type: HTTP, Target: srv.URL + "/new", Timeout: time.Second, Config: raw, AllowPrivate: true}); o.Evidence != nil {
t.Error("evidence recorded without Capture")
}
}
// recordingTLS replaces crypto/tls verification, so it must reject what
// crypto/tls rejects.
func TestRecordingTLSVerifies(t *testing.T) {
srv := httptest.NewTLSServer(http.NotFoundHandler())
defer srv.Close()
roots := x509.NewCertPool()
roots.AddCert(srv.Certificate())
handshake := func(serverName string, trusted, verify bool) error {
cfg := recordingTLS(newRecorder(), verify)
if trusted {
cfg.RootCAs = roots
}
cfg.ServerName = serverName
conn, err := tls.Dial("tcp", srv.Listener.Addr().String(), cfg)
if err == nil {
_ = conn.Close()
}
return err
}
if err := handshake("example.com", true, true); err != nil {
t.Errorf("valid name and trusted root rejected: %v", err)
}
if err := handshake("evil.test", true, true); err == nil {
t.Error("wrong host name accepted")
}
if err := handshake("example.com", false, true); err == nil {
t.Error("untrusted certificate accepted")
}
if err := handshake("evil.test", false, false); err != nil {
t.Errorf("opted-out verification still rejects: %v", err)
}
}
+45 -3
View File
@@ -10,6 +10,7 @@ import (
"io" "io"
"net" "net"
"net/http" "net/http"
"net/http/httptrace"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
@@ -133,16 +134,37 @@ type request struct {
// the response body. // the response body.
func fetch(ctx context.Context, s Spec, r request) (*http.Response, error) { func fetch(ctx context.Context, s Spec, r request) (*http.Response, error) {
d := netguard.Dialer(s.AllowPrivate, s.Timeout) 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{ tr := &http.Transport{
DialContext: d.DialContext, DialContext: d.DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: !r.VerifyTLS}, //nolint:gosec // opt-out chosen by the customer per monitor TLSClientConfig: tlsConfig,
DisableKeepAlives: true, DisableKeepAlives: true,
TLSHandshakeTimeout: s.Timeout, TLSHandshakeTimeout: s.Timeout,
ForceAttemptHTTP2: true, ForceAttemptHTTP2: true,
} }
client := &http.Client{Transport: tr} client := &http.Client{Transport: tr}
client.CheckRedirect = func(next *http.Request, via []*http.Request) error {
if !r.FollowRedirects { if !r.FollowRedirects {
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } // 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 var body io.Reader
if r.Body != "" { if r.Body != "" {
@@ -159,7 +181,27 @@ func fetch(ctx context.Context, s Spec, r request) (*http.Response, error) {
for k, v := range r.Headers { for k, v := range r.Headers {
req.Header.Set(k, v) req.Header.Set(k, v)
} }
return client.Do(req) 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. // validURL accepts absolute http(s) URLs without credentials.