Files
magpie/internal/gateway/tls_test.go
T
yetone d9ca84a2f4 gateway: built-in TLS, magpie serve/web/daemon install --tls-cert --tls-key, reloaded on renewal (RoderickZH)
magpie serve, magpie web and magpie daemon install take --tls-cert <file>
--tls-key <file> (or MAGPIE_TLS_CERT / MAGPIE_TLS_KEY). The gateway and the
web UI on its listener then serve HTTPS to other computers. Without them
nothing changes.

- Half a pair, a file that doesn't parse, or a flag with no value is
  refused at start with a message naming the missing flag.
- The pair is re-read when either file's mtime or size changes (certbot
  renewal), with no restart. A renewal that doesn't parse keeps the
  certificate already served and is logged once.
- Other computers get HTTPS only. Plain HTTP from them gets net/http's
  400 "Client sent an HTTP request to an HTTPS server".
- This computer (loopback, or a peer address equal to the local one) may
  still use plain http on the same port. Its connections are sniffed on
  their own goroutine (a first byte of 0x16 is TLS) for up to 10s, so a
  silent client holds nobody else up. gateway.URL() stays
  http://127.0.0.1:<port>, which agents, MCP servers, ServedBy, the
  healthcheck and daemon status all use, and no certificate covers
  loopback.
- WSL NAT and containers count as other computers.
- ALPN is http/1.1 only (hijacked connections and websockets need it), with
  TLS 1.2 as the minimum.
- Printed links, LAN addresses, publicURL, the serve/web banners and
  daemon install show https:// for other computers' addresses.
- The DNS-rebinding Host checks (foreignPage, rebound, the MCP
  loopbackHost) don't depend on the scheme and are unchanged.
- daemon install carries MAGPIE_TLS_* into the unit or plist. A reinstall
  or `daemon web on` that names no certificate keeps the installed pair,
  and --no-tls removes it.
- Docs: reference.md gets an HTTPS section that names Caddy as the
  alternative, gateway-routing.md gets a TLS row, and docker.html (en,
  zh, ja) gets the env rows.

What was run:
- New tests: internal/gateway/tls_test.go (others HTTPS-only, this
  computer both, a silent local client holds no other, renewed
  certificate served, CheckTLS, addresses, Relisten keeps TLS),
  internal/cli/tls_cli_test.go and daemon TestInstallCarriesTLS (linux
  and darwin, paths with space, %, & and ").
- Each was broken by hand and went red: no wrap in listen, no reload, a
  synchronous sniff, a bad renewal dropping the certificate, http in
  publicURL or the pinned LANURLs, the carried entries removed, and
  keepTLS as a no-op.
- Real use under a sandbox HOME, with a self-signed pair, on
  0.0.0.0:3461:
  - Half a pair, a garbage certificate, a flag with no value, and the
    env set to half a pair each exit 1 with the message.
  - curl -k https://127.0.0.1 and https://<LAN IP>/v1/models with a key:
    200. Plain http on loopback: 200.
  - The cert files were swapped for a second pair while it ran.
    openssl s_client then showed the new CN and serial, and curl
    --cacert with the new pair got 200. A junk key file then kept the
    second pair, logged once.
  - From the Windows box over the LAN: plain http got 400; https with
    the key got 200, and without it 401.
  - magpie web --addr 0.0.0.0:3462: https network links. From Windows,
    http got 400 and https with the key got 303.
- gofmt -l clean. go vet passed on darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- go test -tags nogui for ./internal/cli, ./internal/daemon, and the TLS
  tests of ./internal/gateway and ./internal/gui: all pass at the rebased
  head.
- Two reds in the full suite (`go test -tags nogui ./...`) are the same
  on origin/main f074996d9; both are filed:
  - TestGatewayHeldByAContainer failed 2 of 5 there (#2107).
  - The gateway package runs past go test's default 10m under load:
    1208s on main and 1221s here, both passing with -timeout 40m
    (#2108).
2026-10-14 13:36:03 +08:00

294 lines
9.7 KiB
Go

package gateway
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"io"
"math/big"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// writeCert writes a self-signed certificate for name, as certbot's
// fullchain.pem and privkey.pem would be, and returns its pool.
func writeCert(t *testing.T, certFile, keyFile, name string) *x509.CertPool {
t.Helper()
k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(time.Now().UnixNano()),
Subject: pkix.Name{CommonName: name},
DNSNames: []string{name},
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
IsCA: true, BasicConstraintsValid: true,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &k.PublicKey, k)
if err != nil {
t.Fatal(err)
}
kb, err := x509.MarshalECPrivateKey(k)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb}), 0o600); err != nil {
t.Fatal(err)
}
c, _ := x509.ParseCertificate(der)
pool := x509.NewCertPool()
pool.AddCert(c)
return pool
}
// serveTLSGateway serves the gateway as ListenAndServe does — lanGuard
// in front, on the listener Server.listen makes — with the TLS files the
// environment names, on loopback; seen from other computers says whether
// a connection counts as another computer's.
func serveTLSGateway(t *testing.T, other bool) (addr string) {
t.Helper()
was := fromThisComputer
fromThisComputer = func(net.Conn) bool { return !other }
t.Cleanup(func() { fromThisComputer = was })
cfg, err := tlsConfig()
if err != nil || cfg == nil {
t.Fatalf("tlsConfig: %v, %v", cfg, err)
}
s := New()
s.tls = cfg
t.Setenv("MAGPIE_ADDR", "127.0.0.1:0")
ln, err := s.listen("127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 5 * time.Second}
done := make(chan struct{})
go func() { defer close(done); srv.Serve(ln) }()
t.Cleanup(func() { srv.Close(); <-done })
return ln.Addr().String()
}
func tlsFiles(t *testing.T) (cert, key string) {
d := t.TempDir()
cert, key = filepath.Join(d, "fullchain.pem"), filepath.Join(d, "privkey.pem")
t.Setenv(TLSCertEnv, cert)
t.Setenv(TLSKeyEnv, key)
return cert, key
}
func get(t *testing.T, c *http.Client, url string) (int, string, error) {
t.Helper()
res, err := c.Get(url)
if err != nil {
return 0, "", err
}
defer res.Body.Close()
b, _ := io.ReadAll(res.Body)
return res.StatusCode, string(b), nil
}
func tlsClient(pool *x509.CertPool) *http.Client {
return &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: pool, ServerName: "relay.example"},
DisableKeepAlives: true,
}}
}
var plain = &http.Client{Timeout: 5 * time.Second, Transport: &http.Transport{DisableKeepAlives: true}}
// Another computer reaches the gateway over TLS alone: plain HTTP is
// turned away, HTTPS answers /v1/models with the certificate's chain.
func TestTLSOtherComputersOnlyOverHTTPS(t *testing.T) {
cert, key := tlsFiles(t)
pool := writeCert(t, cert, key, "relay.example")
addr := serveTLSGateway(t, true)
code, body, err := get(t, plain, "http://"+addr+"/v1/models")
if err == nil && code != http.StatusBadRequest {
t.Fatalf("plain HTTP from another computer: %d %s, want it refused", code, body)
}
if err == nil && !strings.Contains(body, "HTTPS") {
t.Errorf("plain HTTP refused with %q, which doesn't say to use HTTPS", body)
}
code, body, err = get(t, tlsClient(pool), "https://"+addr+"/v1/models")
if err != nil || code != http.StatusOK || !strings.Contains(body, `"data"`) {
t.Fatalf("HTTPS /v1/models: %d %s %v", code, body, err)
}
}
// This computer's agents, MCP servers and status checks call plain
// http://127.0.0.1 with TLS on, and HTTPS works there too.
func TestTLSThisComputerTakesBoth(t *testing.T) {
cert, key := tlsFiles(t)
pool := writeCert(t, cert, key, "relay.example")
addr := serveTLSGateway(t, false)
if code, body, err := get(t, plain, "http://"+addr+"/v1/models"); err != nil || code != http.StatusOK {
t.Fatalf("plain HTTP from this computer: %d %s %v", code, body, err)
}
if code, body, err := get(t, tlsClient(pool), "https://"+addr+"/v1/models"); err != nil || code != http.StatusOK {
t.Fatalf("HTTPS from this computer: %d %s %v", code, body, err)
}
}
// A client here that connects and says nothing (a browser's preconnect)
// doesn't hold up the connections after it while its first byte, which
// says TLS or not, is waited for.
func TestTLSSilentLocalClientHoldsNoOther(t *testing.T) {
cert, key := tlsFiles(t)
writeCert(t, cert, key, "relay.example")
addr := serveTLSGateway(t, false)
silent, err := net.Dial("tcp", addr)
if err != nil {
t.Fatal(err)
}
defer silent.Close()
time.Sleep(50 * time.Millisecond) // it is the one accepted first
c := &http.Client{Timeout: sniffWait / 2, Transport: &http.Transport{DisableKeepAlives: true}}
if code, body, err := get(t, c, "http://"+addr+"/v1/models"); err != nil || code != http.StatusOK {
t.Fatalf("a request behind a silent connection: %d %s %v", code, body, err)
}
}
// A renewal (certbot writing new files) is served on the next connection
// without a restart; files half written keep the certificate before.
func TestTLSServesRenewedCertificate(t *testing.T) {
cert, key := tlsFiles(t)
poolA := writeCert(t, cert, key, "relay.example")
addr := serveTLSGateway(t, true)
served := func(pool *x509.CertPool) error {
_, _, err := get(t, tlsClient(pool), "https://"+addr+"/v1/models")
return err
}
if err := served(poolA); err != nil {
t.Fatalf("first certificate: %v", err)
}
poolB := writeCert(t, cert, key, "relay.example")
later := time.Now().Add(time.Minute)
os.Chtimes(cert, later, later)
os.Chtimes(key, later, later)
if err := served(poolB); err != nil {
t.Fatalf("renewed certificate not served: %v", err)
}
if served(poolA) == nil {
t.Fatal("the certificate before the renewal is still served")
}
// a renewal half written: the key changed, the certificate not yet
os.WriteFile(key, []byte("not a key"), 0o600)
if err := served(poolB); err != nil {
t.Fatalf("a pair that doesn't load took the served certificate away: %v", err)
}
}
// Only one of the two files, or files that aren't a certificate and its
// key, refuse to start, saying which.
func TestCheckTLS(t *testing.T) {
cert, key := tlsFiles(t)
writeCert(t, cert, key, "relay.example")
if err := CheckTLS(); err != nil || !TLSOn() {
t.Fatalf("a good pair: %v, on %v", err, TLSOn())
}
t.Setenv(TLSKeyEnv, "")
if err := CheckTLS(); err == nil || !strings.Contains(err.Error(), "--tls-key") {
t.Errorf("certificate alone: %v", err)
}
t.Setenv(TLSKeyEnv, key)
t.Setenv(TLSCertEnv, "")
if err := CheckTLS(); err == nil || !strings.Contains(err.Error(), "--tls-cert") {
t.Errorf("key alone: %v", err)
}
t.Setenv(TLSCertEnv, key) // a key where the certificate goes
if err := CheckTLS(); err == nil {
t.Error("a key as the certificate loaded")
}
if _, err := tlsConfig(); err == nil {
t.Error("tlsConfig served a pair that doesn't load")
}
t.Setenv(TLSCertEnv, "")
t.Setenv(TLSKeyEnv, "")
if err := CheckTLS(); err != nil || TLSOn() {
t.Errorf("neither: %v, on %v", err, TLSOn())
}
if cfg, err := tlsConfig(); cfg != nil || err != nil {
t.Errorf("neither: %v %v", cfg, err)
}
}
// The addresses printed for other computers are https:// with TLS on.
func TestTLSAddressesForOtherComputers(t *testing.T) {
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_ADDR", "10.1.2.3:3425")
if got := LANURLs(); len(got) != 1 || got[0] != "http://10.1.2.3:3425" {
t.Fatalf("without TLS: %v", got)
}
cert, key := tlsFiles(t)
writeCert(t, cert, key, "relay.example")
if got := LANURLs(); len(got) != 1 || got[0] != "https://10.1.2.3:3425" {
t.Errorf("with TLS: %v", got)
}
t.Setenv("MAGPIE_PUBLIC_URL", "relay.example:3425")
if got := PublicURL(); got != "https://relay.example:3425" {
t.Errorf("MAGPIE_PUBLIC_URL with no scheme: %q", got)
}
t.Setenv("MAGPIE_PUBLIC_URL", "http://relay.example")
if got := PublicURL(); got != "http://relay.example" {
t.Errorf("MAGPIE_PUBLIC_URL's own scheme: %q", got)
}
}
// Moving the gateway (sharing turned on, another port) keeps TLS.
func TestTLSRelistenKeepsTLS(t *testing.T) {
cert, key := tlsFiles(t)
pool := writeCert(t, cert, key, "relay.example")
cfg, err := tlsConfig()
if err != nil {
t.Fatal(err)
}
was := fromThisComputer
fromThisComputer = func(net.Conn) bool { return false }
t.Cleanup(func() { fromThisComputer = was })
s := New()
s.tls = cfg
first, err := s.listen("127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
s.ln = first
free, _ := net.Listen("tcp", "127.0.0.1:0")
to := free.Addr().String()
free.Close()
t.Setenv("MAGPIE_ADDR", to)
if err := s.Relisten(); err != nil {
t.Fatal(err)
}
srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 5 * time.Second}
done := make(chan struct{})
go func() { defer close(done); srv.Serve(s.ln) }()
defer func() { srv.Close(); <-done }()
if code, _, err := get(t, plain, "http://"+to+"/v1/models"); err == nil && code != http.StatusBadRequest {
t.Errorf("plain HTTP after moving: %d", code)
}
if code, body, err := get(t, tlsClient(pool), "https://"+to+"/v1/models"); err != nil || code != http.StatusOK {
t.Errorf("HTTPS after moving: %d %s %v", code, body, err)
}
}