cli, gateway: magpie heap writes the running magpie's Go heap profile, with its memory numbers

A user on X (FatimaHill74421) reports the macOS app at 3.95 GB physical
footprint after ~12h (v0.1.1273, after 8a1b5916f's #2278 fix), and a macOS
`sample` shows Go's frames as ???. `magpie heap [<file>]` asks the magpie
that serves the gateway for GET /v1/magpie/heap: runtime/pprof's heap
profile after a GC (gzipped protobuf, go tool pprof reads it), with
HeapAlloc, live heap, HeapInuse, HeapSys, StackSys, Sys, NumGC and the
goroutine count in X-Magpie-Heap-Stats. It writes <file>, else
magpie-heap-<date>-<time>.pb.gz here (0600, never over a file), and prints
the path, the pid and the numbers. --help writes nothing; an unknown flag,
"-" or a second file is refused before anything is asked.

The route answers only a loopback, unproxied caller with no browser marks
calling localhost or a loopback IP. heapRefused checks this in the handler
itself, so a gateway key never lets in another machine, a listed page,
Origin null, a localhost page or a rebound Host, and it holds where Handler
is served without lanGuard.

Run at dccfefdf7: gofmt -l (nothing); go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... (clean); go build for darwin,
linux (nogui) and windows; go test -tags nogui -timeout 45m ./... under a
sandbox HOME: every package ok (gateway 1218s, cli 613s). Broken by hand:
heapRefused returning "" turns TestHeapProfileOnlyToThisComputer red
(19 failures).

Real use: the built binary's `magpie serve` under a sandbox HOME on
127.0.0.1:3481; `magpie heap` saved a 10 KB profile (0600) and printed the
numbers, go tool pprof -top read it, --help wrote nothing, and a curl with
Origin: null got 403. Not tried: the GUI app's own process, or the
Windows box.
This commit is contained in:
yetone
2026-10-17 12:04:53 +08:00
parent df341e7671
commit e085d6e926
10 changed files with 554 additions and 2 deletions
+19
View File
@@ -1791,6 +1791,25 @@ add it to `~/.claude/settings.json` yourself:
`"statusLine": {"type": "command", "command": "magpie statusline"}`. With
the gateway not running it prints an empty line.
`magpie heap [<file>]` is for a report of magpie holding too much memory: a
macOS `sample` of the app shows Go's frames as `???`. It asks the running
magpie that serves the gateway (the app, the menu bar, `magpie serve` or
`magpie web`) for `GET /v1/magpie/heap`, a Go heap profile taken after a
collection (`runtime/pprof`'s `heap`, gzipped protobuf, which
`go tool pprof` reads), and writes it to `<file>`, else
`magpie-heap-<date>-<time>.pb.gz` in the working folder, never over a file
there. It prints the file and the runtime's numbers the gateway sends in
`X-Magpie-Heap-Stats`: the process, `HeapAlloc` (and what is live after the
collection), `HeapInuse`, `HeapSys`, `StackSys`, `Sys` (all Go took from
the system; a footprint far above it is outside Go, such as the webview),
`NumGC` and the goroutine count. The route answers only a program on this
computer calling it as `localhost` or a loopback address: another machine,
a proxy's or tunnel's client, any request with a browser's marks (an
Origin, listed or not, `null`, `Sec-Fetch-*`, a `Mozilla/` user agent) and
any other `Host` are refused 403, with a gateway key too. With
`MAGPIE_ADDR` on an address that isn't loopback, the call isn't from
loopback, so it is refused as well.
A gateway key held to a budget, to some models or to some accounts is told
none of this magpie's accounts (#1981): `/v1/magpie/quotas`,
`/v1/magpie/quotas/history`, `/v1/magpie/quotas/cards`,
File diff suppressed because one or more lines are too long
+152
View File
@@ -0,0 +1,152 @@
package cli
// magpie heap: a Go heap profile of the running magpie, for a report of it
// holding too much memory. A macOS `sample` of the app shows Go's frames
// as ???, so the profile is asked of the process itself, through the
// gateway it serves on this computer (gateway.HeapPath, loopback only).
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/gateway"
)
const heapUsage = `usage: magpie heap [<file>]
a Go heap profile of the magpie serving the gateway on this computer (the app, the
menu bar, magpie serve or magpie web), for a report of magpie using too much memory.
It is written to <file>, else to magpie-heap-<date>-<time>.pb.gz in this folder, and
never over a file that is there. magpie then prints the file and the process's memory
as Go counts it (its heap, what it took from the system, its goroutines): send both.
The profile holds where memory was allocated (function names, source lines, sizes) and
the path of the magpie program, not keys or messages; go tool pprof <file> reads it.
It asks the gateway at Settings' Gateway port (or MAGPIE_ADDR) over loopback.`
// heapWait bounds the ask: the profile runs a collection first, which on a
// heap of gigabytes takes a while.
const heapWait = 2 * time.Minute
// heapCmd: magpie heap [<file>]
func heapCmd(args []string) error {
file := ""
for _, a := range args {
switch {
case strings.HasPrefix(a, "-") && a != "-":
return fmt.Errorf("unknown flag %s: nothing was written (magpie heap [<file>])", a)
case a == "-" || strings.TrimSpace(a) == "":
return fmt.Errorf("%q is not a file name: nothing was written (magpie heap [<file>])", a)
case file != "":
return errors.New("magpie heap takes one file: nothing was written (magpie heap [<file>])")
default:
file = a
}
}
if file == "" {
file = "magpie-heap-" + time.Now().Format("20060102-150405") + ".pb.gz"
}
prof, stats, err := fetchHeap(gateway.URL())
if err != nil {
return err
}
f, err := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
if errors.Is(err, os.ErrExist) {
return fmt.Errorf("%s is there already: name another file (magpie heap <file>)", file)
}
return err
}
if _, err := f.Write(prof); err != nil {
f.Close()
os.Remove(file)
return err
}
if err := f.Close(); err != nil {
os.Remove(file)
return err
}
if abs, err := filepath.Abs(file); err == nil {
file = abs
}
fmt.Printf("%s %s (%s)\n", green.Render("saved"), file, bytesSize(uint64(len(prof))))
fmt.Print(heapSummary(stats))
fmt.Println(muted.Render("Send the file and these lines with the report."))
return nil
}
// fetchHeap asks the gateway at base for the profile: its bytes, checked
// to be gzip, and the runtime's numbers beside it.
func fetchHeap(base string) ([]byte, gateway.HeapStats, error) {
var st gateway.HeapStats
c := &http.Client{Timeout: heapWait}
res, err := c.Get(base + gateway.HeapPath)
if err != nil {
return nil, st, fmt.Errorf("no magpie answers at %s, so there is nothing to profile: is magpie running? (%v)", base, err)
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, st, fmt.Errorf("the profile from %s was cut off: %w", base, err)
}
if res.StatusCode == http.StatusNotFound {
return nil, st, fmt.Errorf("the magpie at %s is older than this one and has no heap profile: update it, then run magpie heap again", base)
}
if res.StatusCode != http.StatusOK {
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
msg := strings.TrimSpace(string(body))
if json.Unmarshal(body, &e) == nil && e.Error.Message != "" {
msg = e.Error.Message
}
return nil, st, fmt.Errorf("the magpie at %s answered %s: %s", base, res.Status, msg)
}
if !bytes.HasPrefix(body, []byte{0x1f, 0x8b}) {
return nil, st, fmt.Errorf("what %s answered is not a heap profile (%d bytes): is it magpie?", base, len(body))
}
if err := json.Unmarshal([]byte(res.Header.Get(gateway.HeapStatsHeader)), &st); err != nil {
return nil, st, fmt.Errorf("the magpie at %s sent no memory numbers with its profile: %v", base, err)
}
return body, st, nil
}
// heapSummary is the lines magpie heap prints of st.
func heapSummary(st gateway.HeapStats) string {
var b strings.Builder
who := st.Program
if st.Window {
who += ", with a window"
}
fmt.Fprintf(&b, " process %d (%s) magpie %s, up %s\n", st.PID, who, st.Version, st.Uptime)
fmt.Fprintf(&b, " HeapAlloc %s (live after a collection: %s)\n", bytesSize(st.HeapAlloc), bytesSize(st.LiveHeap))
fmt.Fprintf(&b, " HeapInuse %s\n", bytesSize(st.HeapInuse))
fmt.Fprintf(&b, " HeapSys %s (idle %s, of it returned to the system %s)\n", bytesSize(st.HeapSys), bytesSize(st.HeapIdle), bytesSize(st.HeapReleased))
fmt.Fprintf(&b, " StackSys %s\n", bytesSize(st.StackSys))
fmt.Fprintf(&b, " Sys %s (all Go took from the system; a footprint far above it is outside Go)\n", bytesSize(st.Sys))
fmt.Fprintf(&b, " NumGC %d\n", st.NumGC)
fmt.Fprintf(&b, " goroutines %d\n", st.Goroutines)
return b.String()
}
// bytesSize is n in B, KB, MB or GB (of 1024).
func bytesSize(n uint64) string {
const k = 1024
switch {
case n >= k*k*k:
return fmt.Sprintf("%.2f GB", float64(n)/(k*k*k))
case n >= k*k:
return fmt.Sprintf("%.1f MB", float64(n)/(k*k))
case n >= k:
return fmt.Sprintf("%.1f KB", float64(n)/k)
}
return fmt.Sprintf("%d B", n)
}
+138
View File
@@ -0,0 +1,138 @@
package cli
import (
"bytes"
"compress/gzip"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/yetone/magpie/internal/gateway"
)
// heapDir is a home of its own and a working folder in it, the one magpie
// heap writes its file to.
func heapDir(t *testing.T) (root, dir string) {
t.Helper()
root = helpHome(t)
dir = filepath.Join(root, "work")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(dir)
return root, dir
}
// --help and its other forms print magpie heap's usage, ask nothing and
// write nothing, here or under the home; a flag it doesn't take, "-", or
// a second file are refused the same way, before the gateway is asked.
func TestHeapHelpAndBadArgsWriteNothing(t *testing.T) {
root, _ := heapDir(t)
asked := false
gw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { asked = true }))
defer gw.Close()
t.Setenv("MAGPIE_ADDR", strings.TrimPrefix(gw.URL, "http://"))
before := tree(t, root)
for _, args := range [][]string{{"heap", "--help"}, {"heap", "-h"}, {"heap", "help"}, {"heap", "out.pb.gz", "--help"}} {
out, err := runOut(t, args...)
if err != nil || !strings.Contains(out, "usage: magpie heap [<file>]") {
t.Errorf("magpie %s: %v %q", strings.Join(args, " "), err, out)
}
}
for _, args := range [][]string{{"heap", "--out", "x"}, {"heap", "-o"}, {"heap", "-"}, {"heap", "a.pb.gz", "b.pb.gz"}, {"heap", " "}} {
if _, err := runOut(t, args...); err == nil || !strings.Contains(err.Error(), "nothing was written") {
t.Errorf("magpie %s: %v", strings.Join(args, " "), err)
}
}
if asked {
t.Error("the gateway was asked")
}
if got := tree(t, root); !reflect.DeepEqual(got, before) {
t.Fatalf("written:\nbefore %v\nafter %v", before, got)
}
}
// Against a running gateway (its Handler, on loopback), magpie heap
// writes the gzipped profile into the working folder, prints its path and
// the memory numbers, and never writes over a file there.
func TestHeapWritesTheRunningGatewaysProfile(t *testing.T) {
_, dir := heapDir(t)
gw := httptest.NewServer(gateway.New().Handler())
defer gw.Close()
t.Setenv("MAGPIE_ADDR", strings.TrimPrefix(gw.URL, "http://"))
out, err := runOut(t, "heap", "mem.pb.gz")
if err != nil {
t.Fatal(err)
}
file := filepath.Join(dir, "mem.pb.gz")
b, err := os.ReadFile(file)
if err != nil {
t.Fatal(err)
}
zr, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
if raw, err := io.ReadAll(zr); err != nil || !bytes.Contains(raw, []byte("inuse_space")) {
t.Fatalf("not a heap profile: %v", err)
}
if info, _ := os.Stat(file); info.Mode().Perm() != 0o600 && os.PathSeparator == '/' {
t.Errorf("mode %v", info.Mode())
}
for _, want := range []string{"mem.pb.gz", "HeapAlloc", "HeapInuse", "HeapSys", "Sys ", "NumGC", "goroutines", "process"} {
if !strings.Contains(out, want) {
t.Errorf("printed no %s: %q", want, out)
}
}
// the same name again: refused, the first file kept
if _, err := runOut(t, "heap", "mem.pb.gz"); err == nil || !strings.Contains(err.Error(), "there already") {
t.Fatalf("written over: %v", err)
}
if again, _ := os.ReadFile(file); !bytes.Equal(again, b) {
t.Fatal("the first profile changed")
}
// no name: magpie-heap-<date>-<time>.pb.gz here
if _, err := runOut(t, "heap"); err != nil {
t.Fatal(err)
}
if m, _ := filepath.Glob(filepath.Join(dir, "magpie-heap-*.pb.gz")); len(m) != 1 {
t.Fatalf("no default file: %v", m)
}
}
// With no magpie answering, magpie heap says so and writes nothing.
func TestHeapWithNoGateway(t *testing.T) {
_, dir := heapDir(t)
// a port kept by the test that hangs up on every call: one freed
// could be handed to anything next
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer ln.Close()
go func() {
for {
c, err := ln.Accept()
if err != nil {
return
}
c.Close()
}
}()
t.Setenv("MAGPIE_ADDR", ln.Addr().String())
if _, err := runOut(t, "heap", "x.pb.gz"); err == nil || !strings.Contains(err.Error(), "is magpie running") {
t.Fatalf("%v", err)
}
if ents, _ := os.ReadDir(dir); len(ents) != 0 {
t.Fatalf("written: %v", ents)
}
}
+2
View File
@@ -51,6 +51,8 @@ func helpFor(args []string) string {
return quotaUsage
case "statusline":
return statuslineUsage
case "heap":
return heapUsage
case "sessions":
return sessionsUsage
case "search":
+1 -1
View File
@@ -129,7 +129,7 @@ func runCommands(t *testing.T) []string {
if len(cmds) < 40 {
t.Fatalf("read %d commands from run's switch: %v", len(cmds), cmds)
}
return append(cmds, "healthcheck")
return append(cmds, "healthcheck", "heap")
}
func types(ix *ast.IndexExpr) string {
+5
View File
@@ -113,6 +113,7 @@ const usage = `magpie — one place to pick every agent's model
magpie daemon web [on|off] [--lan] [--addr host:port]
the service's page: its link, or turn it on or off
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
magpie heap [<file>] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
magpie gateway-key limit <id> [list|off|reset [n]|remove <n>|[add] day|week|month|<N>d|<N>h --tokens N --cost USD --cache-reads] a key's own limits, and what it used
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
@@ -221,6 +222,10 @@ func run(args []string) error {
if len(args) > 0 && args[0] == "healthcheck" {
return healthcheck() // every few seconds in a container: nothing else
}
if len(args) > 0 && args[0] == "heap" {
// the running magpie's heap profile: asks it, and moves nothing here
return heapCmd(args[1:])
}
if len(args) == 2 && args[0] == agent.DryRunArg {
// an agent disconnected on a copy of its files under a temporary
// home, for the Agents page to show what disconnecting changes
+2
View File
@@ -636,6 +636,8 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /v1/magpie/route", s.sessionRoute)
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
// a heap profile of this process, for magpie heap (loopback only)
mux.HandleFunc("GET "+HeapPath, s.heapProfile)
mux.HandleFunc("GET /v1/magpie/omarchy", s.omarchyTheme)
mux.HandleFunc("OPTIONS /v1/magpie/omarchy", s.omarchyTheme)
mux.HandleFunc("POST /v1/chat/completions", s.handle(provider.Chat))
+121
View File
@@ -0,0 +1,121 @@
package gateway
// GET /v1/magpie/heap: a Go heap profile of the process serving the
// gateway, for a report of magpie holding too much memory. A macOS
// `sample` of the app names none of Go's frames, so this is the one way
// to see what the Go side holds; `magpie heap` asks for it and writes the
// file the user sends.
import (
"bytes"
"encoding/json"
"log"
"net/http"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"time"
"github.com/yetone/magpie/internal/provider"
)
// HeapPath is where the gateway answers a heap profile.
const HeapPath = "/v1/magpie/heap"
// HeapStatsHeader carries HeapStats, as JSON, beside the profile.
const HeapStatsHeader = "X-Magpie-Heap-Stats"
// HeapStats is what Go's runtime says of the process's memory when the
// profile was taken. HeapAlloc and the others are read before the
// collection the profile runs; LiveHeap is HeapAlloc after it, what is
// still reachable. Sys is all Go took from the system, so a footprint far
// above it is memory outside Go (the webview, cgo).
type HeapStats struct {
PID int `json:"pid"`
Program string `json:"program"`
Version string `json:"version"`
Window bool `json:"window"` // the app's window or magpie web serves the gateway
Uptime string `json:"uptime"`
HeapAlloc uint64 `json:"heapAlloc"`
HeapInuse uint64 `json:"heapInuse"`
HeapIdle uint64 `json:"heapIdle"`
HeapReleased uint64 `json:"heapReleased"`
HeapSys uint64 `json:"heapSys"`
StackSys uint64 `json:"stackSys"`
Sys uint64 `json:"sys"`
LiveHeap uint64 `json:"liveHeap"`
NumGC uint32 `json:"numGC"`
Goroutines int `json:"goroutines"`
}
// processStarted is when this process began, for HeapStats' Uptime.
var processStarted = time.Now()
// heapProfile answers HeapPath: the "heap" profile (gzipped protobuf, as
// go tool pprof reads it) after a collection, with HeapStats in
// HeapStatsHeader.
func (s *Server) heapProfile(w http.ResponseWriter, r *http.Request) {
if why := heapRefused(r); why != "" {
log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, why)
writeError(w, provider.Chat, http.StatusForbidden, why)
return
}
var before runtime.MemStats
runtime.ReadMemStats(&before)
goroutines := runtime.NumGoroutine()
// what is still reachable, not what the next collection frees: the
// profile's in-use numbers are as of the last collection
runtime.GC()
var after runtime.MemStats
runtime.ReadMemStats(&after)
var buf bytes.Buffer
if err := pprof.Lookup("heap").WriteTo(&buf, 0); err != nil {
writeError(w, provider.Chat, http.StatusInternalServerError, "the heap profile couldn't be written: "+err.Error())
return
}
exe, _ := os.Executable()
stats, _ := json.Marshal(HeapStats{
PID: os.Getpid(),
Program: filepath.Base(exe),
Version: Version,
Window: Window,
Uptime: time.Since(processStarted).Round(time.Second).String(),
HeapAlloc: before.HeapAlloc,
HeapInuse: before.HeapInuse,
HeapIdle: before.HeapIdle,
HeapReleased: before.HeapReleased,
HeapSys: before.HeapSys,
StackSys: before.StackSys,
Sys: before.Sys,
LiveHeap: after.HeapAlloc,
NumGC: after.NumGC,
Goroutines: goroutines,
})
h := w.Header()
h.Set("Content-Type", "application/octet-stream")
h.Set("Content-Disposition", `attachment; filename="magpie-heap.pb.gz"`)
h.Set("Cache-Control", "no-store")
h.Set(HeapStatsHeader, string(stats))
w.Write(buf.Bytes())
}
// heapRefused says why r may not have the heap profile, "" when it may.
// Only a program on this computer, calling it as localhost or a loopback
// address, does — never another machine, even with a gateway key (the
// profile is this computer's, not a shared gateway's), never anything
// carrying a browser's marks, whatever its Origin (a listed page, null, a
// localhost page), and never under another Host (DNS rebinding). lanGuard
// and corsGuard turn most of these away first; this holds where Handler
// is served without them too.
func heapRefused(r *http.Request) string {
switch {
case !local(r):
return "magpie hands its heap profile only to a program on this computer, over loopback: run magpie heap there"
case fromBrowser(r):
return "magpie doesn't hand its heap profile to a web page: run magpie heap in a terminal"
case !loopbackHost(r.Host):
return "magpie hands its heap profile only to a call to localhost or a loopback address, not " + r.Host + ": run magpie heap"
}
return ""
}
+113
View File
@@ -0,0 +1,113 @@
package gateway
import (
"bytes"
"compress/gzip"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// The heap profile is a program's on this computer alone: whatever a
// normal route refuses is refused (a foreign page, Origin null, a rebound
// Host, another machine), and so is what a normal route lets through but
// a profile has no use for — a page on localhost, a listed page with its
// gateway key, another machine with one, a proxy's client. An agent-like
// call to 127.0.0.1 or localhost gets a gzipped pprof heap profile, and
// the runtime's numbers beside it.
func TestHeapProfileOnlyToThisComputer(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
_, secrets := newCaller(t, "Page") // the gateway shared, with a key
s := settings.Load()
s.CORSOrigins = []string{"https://listed.example"}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
key := secrets[0]
srv := New()
chrome := []string{"User-Agent", "Mozilla/5.0 (Macintosh) AppleWebKit/605.1.15 Version/27.2 Safari/605.1.15", "Sec-Fetch-Site", "cross-site", "Sec-Fetch-Mode", "cors"}
call := func(guarded bool, remote, host string, hdr ...string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest("GET", HeapPath, nil)
r.RemoteAddr = remote
r.Host = host
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
h := srv.Handler()
if guarded {
h = lanGuard(h)
}
h.ServeHTTP(w, r)
return w
}
refused := []struct {
name string
remote, host string
hdr []string
}{
{"a foreign page", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://evil.example"}, chrome...)},
{"Origin null", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null"}, chrome...)},
{"Origin null with a key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "null", "Authorization", "Bearer " + key}, chrome...)},
{"a page on localhost", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://localhost:5173"}, chrome...)},
{"a localhost subdomain", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "http://evil.localhost"}, chrome...)},
{"a listed page with its key", "127.0.0.1:50123", "127.0.0.1:3425", append([]string{"Origin", "https://listed.example", "Authorization", "Bearer " + key}, chrome...)},
{"a rebound page's GET", "127.0.0.1:50123", "rebind.attacker.example:3425", chrome},
{"a rebound page with a key", "127.0.0.1:50123", "rebind.attacker.example:3425", append([]string{"Authorization", "Bearer " + key}, chrome...)},
{"a call to another name", "127.0.0.1:50123", "rebind.attacker.example:3425", []string{"User-Agent", "curl/8"}},
{"a localhost subdomain as Host", "127.0.0.1:50123", "wails.localhost:3425", []string{"User-Agent", "curl/8"}},
{"another machine", "192.168.1.20:50123", "192.168.1.10:3425", nil},
{"another machine with a key", "192.168.1.20:50123", "192.168.1.10:3425", []string{"Authorization", "Bearer " + key}},
{"a proxy's client", "127.0.0.1:50123", "127.0.0.1:3425", []string{"X-Forwarded-For", "203.0.113.9"}},
{"a proxy's client with a key", "127.0.0.1:50123", "127.0.0.1:3425", []string{"Cf-Connecting-IP", "203.0.113.9", "Authorization", "Bearer " + key}},
}
for _, c := range refused {
for _, guarded := range []bool{true, false} {
w := call(guarded, c.remote, c.host, c.hdr...)
// lanGuard asks another machine without a key for one (401)
if w.Code != http.StatusForbidden && w.Code != http.StatusUnauthorized || w.Header().Get(HeapStatsHeader) != "" || bytes.HasPrefix(w.Body.Bytes(), []byte{0x1f, 0x8b}) {
t.Errorf("%s (lanGuard %v): %d %q", c.name, guarded, w.Code, w.Body.String())
}
}
}
for _, host := range []string{"127.0.0.1:3425", "localhost:3425", "[::1]:3425"} {
w := call(true, "127.0.0.1:50123", host, "User-Agent", "Go-http-client/1.1")
if w.Code != http.StatusOK {
t.Fatalf("magpie heap at %s: %d %q", host, w.Code, w.Body.String())
}
zr, err := gzip.NewReader(bytes.NewReader(w.Body.Bytes()))
if err != nil {
t.Fatalf("at %s: not gzip: %v", host, err)
}
raw, err := io.ReadAll(zr)
if err != nil || len(raw) == 0 {
t.Fatalf("at %s: %v, %d bytes", host, err, len(raw))
}
// a pprof heap profile's string table names its sample types
for _, want := range []string{"alloc_space", "inuse_space", "bytes"} {
if !bytes.Contains(raw, []byte(want)) {
t.Errorf("at %s: the profile names no %s", host, want)
}
}
var st HeapStats
if err := json.Unmarshal([]byte(w.Header().Get(HeapStatsHeader)), &st); err != nil {
t.Fatalf("at %s: stats %q: %v", host, w.Header().Get(HeapStatsHeader), err)
}
if st.PID != os.Getpid() || st.HeapSys == 0 || st.Sys < st.HeapSys || st.HeapInuse == 0 || st.LiveHeap == 0 || st.NumGC == 0 || st.Goroutines < 1 {
t.Errorf("at %s: stats %+v", host, st)
}
if !strings.Contains(w.Header().Get("Cache-Control"), "no-store") {
t.Errorf("at %s: cacheable: %v", host, w.Header())
}
}
}