Files
magpie/internal/gateway/tls.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

320 lines
8.5 KiB
Go

package gateway
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// TLS: `magpie serve --tls-cert <file> --tls-key <file>` (or
// MAGPIE_TLS_CERT and MAGPIE_TLS_KEY) serves the gateway, and `magpie
// web`'s page, over HTTPS to other computers (RoderickZH on Discord: magpie
// on a server as a relay, reached over the internet). The certificate is
// read again when its files change, so a certbot renewal is served without
// a restart. A connection from this computer itself (loopback, or this
// computer calling its own address) may still speak plain HTTP on the same
// port: the agents, MCP servers and status checks magpie wires here call
// http://127.0.0.1, which no certificate for a server's name covers, and
// their requests never leave the machine. Every other peer gets TLS alone;
// plain HTTP from it is answered 400 by net/http.
// TLSCertEnv and TLSKeyEnv name the PEM certificate (its chain after it)
// and private key files the flags set.
const (
TLSCertEnv = "MAGPIE_TLS_CERT"
TLSKeyEnv = "MAGPIE_TLS_KEY"
)
// TLSFiles are the certificate and key files set, "" for none.
func TLSFiles() (cert, key string) {
return strings.TrimSpace(os.Getenv(TLSCertEnv)), strings.TrimSpace(os.Getenv(TLSKeyEnv))
}
// TLSOn: the gateway serves other computers over HTTPS.
func TLSOn() bool {
c, k := TLSFiles()
return c != "" && k != ""
}
// Scheme is the gateway's scheme for other computers: https with TLS on.
func Scheme() string {
if TLSOn() {
return "https"
}
return "http"
}
// SetTLS sets the files the flags name, as absolute paths (a service
// starts in another folder), after checking them as CheckTLS does.
func SetTLS(cert, key string) error {
abs := func(p string) string {
if p == "" {
return ""
}
if a, err := filepath.Abs(p); err == nil {
return a
}
return p
}
cert, key = abs(strings.TrimSpace(cert)), abs(strings.TrimSpace(key))
if err := checkTLS(cert, key); err != nil {
return err
}
if cert == "" {
return nil
}
os.Setenv(TLSCertEnv, cert)
os.Setenv(TLSKeyEnv, key)
return nil
}
// CheckTLS says why the files set can't be served: only one of the two,
// or a pair that doesn't load. nil with neither set.
func CheckTLS() error { return checkTLS(TLSFiles()) }
func checkTLS(cert, key string) error {
switch {
case cert == "" && key == "":
return nil
case key == "":
return fmt.Errorf("TLS needs a key beside the certificate %s: give --tls-key <file> (or %s) too", cert, TLSKeyEnv)
case cert == "":
return fmt.Errorf("TLS needs a certificate beside the key %s: give --tls-cert <file> (or %s) too", key, TLSCertEnv)
}
if _, err := tls.LoadX509KeyPair(cert, key); err != nil {
return fmt.Errorf("TLS: the certificate %s and key %s can't be served: %w", cert, key, err)
}
return nil
}
// TLSSummary says what the certificate served now is for and until when,
// for the serve banner: "" with TLS off or a pair that doesn't load.
func TLSSummary() string {
if !TLSOn() {
return ""
}
c, err := tls.LoadX509KeyPair(TLSFiles())
if err != nil || len(c.Certificate) == 0 {
return ""
}
leaf, err := x509.ParseCertificate(c.Certificate[0])
if err != nil {
return ""
}
names := append([]string{}, leaf.DNSNames...)
for _, ip := range leaf.IPAddresses {
names = append(names, ip.String())
}
if len(names) == 0 && leaf.Subject.CommonName != "" {
names = []string{leaf.Subject.CommonName}
}
s := strings.Join(names, ", ")
if s != "" {
s += " · "
}
return s + "valid until " + leaf.NotAfter.Format("2006-01-02")
}
// certFiles serves the pair in its files, read again when either changes
// (a renewal), in its GetCertificate. A pair that doesn't load then (a
// renewal half written) leaves the one served before in place.
type certFiles struct {
cert, key string
mu sync.Mutex
served *tls.Certificate
stamp, bad [2]fileStamp
}
type fileStamp struct {
mod time.Time
size int64
}
func stampOf(path string) fileStamp {
fi, err := os.Stat(path)
if err != nil {
return fileStamp{}
}
return fileStamp{fi.ModTime(), fi.Size()}
}
func (f *certFiles) get(*tls.ClientHelloInfo) (*tls.Certificate, error) {
f.mu.Lock()
defer f.mu.Unlock()
now := [2]fileStamp{stampOf(f.cert), stampOf(f.key)}
if f.served != nil && (now == f.stamp || now == f.bad) {
return f.served, nil
}
c, err := tls.LoadX509KeyPair(f.cert, f.key)
if err != nil {
if f.served == nil {
return nil, err
}
f.bad = now
log.Printf("TLS: %s and %s changed but don't load (%v): still serving the certificate read before", f.cert, f.key, err)
return f.served, nil
}
f.served, f.stamp, f.bad = &c, now, [2]fileStamp{}
return f.served, nil
}
// tlsConfig is the server's config for the files set, nil with TLS off.
func tlsConfig() (*tls.Config, error) {
if err := CheckTLS(); err != nil {
return nil, err
}
if !TLSOn() {
return nil, nil
}
cert, key := TLSFiles()
f := &certFiles{cert: cert, key: key}
if _, err := f.get(nil); err != nil {
return nil, err
}
return &tls.Config{
GetCertificate: f.get,
MinVersion: tls.VersionTLS12,
// HTTP/1.1 alone, as over plain HTTP: Codex's websocket and the
// streams' handling hijack the connection
NextProtos: []string{"http/1.1"},
}, nil
}
// ServeTLS wraps ln to serve TLS, with plain HTTP for this computer's own
// connections, when the files are set; ln as it is otherwise.
func ServeTLS(ln net.Listener) (net.Listener, error) {
cfg, err := tlsConfig()
if err != nil || cfg == nil {
return ln, err
}
return newTLSListener(ln, cfg), nil
}
// fromThisComputer: the connection's peer is this computer — loopback, or
// this computer calling one of its own addresses, which the kernel answers
// without the network (a MAGPIE_ADDR on one interface's address, which
// the agents wired here then call). A var for the tests, which have no
// other computer to call from.
var fromThisComputer = func(c net.Conn) bool {
r, ok := c.RemoteAddr().(*net.TCPAddr)
if !ok {
return false
}
if r.IP.IsLoopback() {
return true
}
l, ok := c.LocalAddr().(*net.TCPAddr)
return ok && l.IP.Equal(r.IP)
}
// sniffWait is how long a connection from this computer has to send its
// first byte, which says whether it speaks TLS.
const sniffWait = 10 * time.Second
// tlsListener hands the server each connection as TLS, unless it comes
// from this computer and its first byte isn't a TLS handshake's. The
// first byte is waited for on a goroutine of the connection's own, so a
// client that connects and says nothing (a browser's preconnect) never
// holds up the next.
type tlsListener struct {
net.Listener
cfg *tls.Config
conns chan net.Conn
done chan struct{}
stopped chan struct{}
err error // why accepting stopped, set before stopped closes
once sync.Once
}
func newTLSListener(ln net.Listener, cfg *tls.Config) *tlsListener {
l := &tlsListener{Listener: ln, cfg: cfg, conns: make(chan net.Conn), done: make(chan struct{}), stopped: make(chan struct{})}
go l.accept()
return l
}
func (l *tlsListener) accept() {
var wait time.Duration
for {
c, err := l.Listener.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() { //nolint:staticcheck // what net/http's Serve looks at
// out of file descriptors and the like: wait, as net/http does
wait = min(max(2*wait, 5*time.Millisecond), time.Second)
select {
case <-time.After(wait):
continue
case <-l.done:
}
}
l.err = err
close(l.stopped)
return
}
wait = 0
if !fromThisComputer(c) {
l.hand(tls.Server(c, l.cfg))
continue
}
go l.sniff(c)
}
}
func (l *tlsListener) sniff(c net.Conn) {
c.SetReadDeadline(time.Now().Add(sniffWait))
first := make([]byte, 1)
if _, err := io.ReadFull(c, first); err != nil {
c.Close()
return
}
c.SetReadDeadline(time.Time{})
p := &peeked{Conn: c, r: io.MultiReader(bytes.NewReader(first), c)}
if first[0] == 0x16 { // a TLS record of type handshake
l.hand(tls.Server(p, l.cfg))
return
}
l.hand(p)
}
func (l *tlsListener) hand(c net.Conn) {
select {
case l.conns <- c:
case <-l.done:
c.Close()
}
}
func (l *tlsListener) Accept() (net.Conn, error) {
select {
case c := <-l.conns:
return c, nil
case <-l.stopped:
return nil, l.err
case <-l.done:
return nil, net.ErrClosed
}
}
func (l *tlsListener) Close() error {
l.once.Do(func() { close(l.done) })
return l.Listener.Close()
}
// peeked is a connection whose first byte was read to tell TLS from plain
// HTTP, and is read again from r.
type peeked struct {
net.Conn
r io.Reader
}
func (p *peeked) Read(b []byte) (int, error) { return p.r.Read(b) }