Files
yetone 4623f54190 gateway: HTTPS for other computers, from magpie's CA or an imported certificate (zhangly1 on X)
zhangly1 on X: Claude on another computer on the LAN needed magpie at
https://. Settings → Network and sharing → HTTPS (magpie https on)
serves other computers TLS on the gateway's own port, with a
certificate magpie's CA (the mTLS one, in ~/.config/magpie/mtls) signs
for this computer's names and addresses; this computer keeps plain
http://. The switch is read per connection, so no restart.

- Certificate row: Import… takes the user's own PEM certificate (with
  chain) and unencrypted key, in any files and order; a pair that can't
  be served (no key, no cert, a stranger key, a passphrase, run out,
  nothing PEM) is refused with the reason in the page's language and
  leaves nothing behind. Remove goes back to magpie's CA. --tls-cert
  still comes first.
- magpie's CA row: SHA-256 shown, Save puts magpie-ca.crt in Downloads;
  the gateway serves it without a key at /magpie-ca.crt to any address
  the share lets in. Rows under it give curl -kO, macOS, Windows, Linux
  and NODE_EXTRA_CA_CERTS steps with Copy.
- A page open from another computer can't turn HTTPS on or off under
  itself (it would lose its own address).
- magpie https status|on|off|import|remove|ca --out; the serve banner
  names magpie's CA or the imported file instead of "(mTLS)".
- docs/reference.md and gateway-routing.md say all of it, and that
  Windows' curl.exe needs --ssl-no-revoke for any private CA.

Run:
- gofmt -l clean; go vet linux -tags nogui ./internal/..., GOOS=windows
  and GOOS=darwin -tags nogui vet of the touched packages (WSL, mote
  refused ssh all evening).
- WSL: go test -tags nogui gateway -run HTTPS|MTLS|ClientCert|CAFile|TLS|LAN
  ok; gui -run HTTPS|MTLS|Keep ok; settings, settingsapi, mtls ok;
  cli -run Help|HTTPS|TLS|Serve|Banner|Flag|Unknown ok. The whole cli
  package hit its 40m timeout in TestEveryAgentFieldNameWritesNothing
  (#5234, #4247, not this change).
- GUI (WSL Playwright, chromium + webkit): https-settings (en, zh, 390px,
  strings in all four languages) ok, plus mtls-settings, allow-ips,
  browser-access, cors-origins, gui-de/ja/zh-tw, i18n-keys,
  i18n-en-no-cjk, lan-*, public-url*, api-key-theme,
  connect-address-kept, gateway-connect-keys, gateway-caller-keys,
  side-gateway-lan, menu-scroll. Reds at load ~130: api-key-theme
  (#5044), connect-address-kept (#5972), gateway-caller-keys (#2572),
  gui-ja (#5943), lan-docker (#4692), all red the same at base
  10bef5fe0 run beside it; allow-ips and gateway-connect-keys went red
  once under that load and pass 18/18 at concurrency 1, base and this
  change side by side.
- Real: a sandbox HOME gateway built from this tree on WSL
  (MAGPIE_ADDR=0.0.0.0:3593, a gateway key, magpie https on, magpie
  serve). From the Windows host: curl -k /magpie-ca.crt 200 without a
  key; Node fetch with NODE_EXTRA_CA_CERTS=magpie-ca.crt 200 on
  /v1/models, 401 without the key, SELF_SIGNED_CERT_IN_CHAIN without
  the CA; plain http:// 400; curl.exe --cacert needs --ssl-no-revoke
  (schannel), then 200. Cert SANs: localhost, the hostname, .local,
  127.0.0.1, ::1 and every address. magpie https import of an openssl
  CA's leaf on the running gateway: Node trusting that CA 200, magpie's
  CA alone refused. remove + off on the running gateway: plain http://
  from Windows 200. This computer's plain http:// 200 throughout.
- At the pushed tree (on origin/main ee818e8bc), WSL:
  gofmt -l clean; go vet -tags nogui linux, GOOS=windows, GOOS=darwin
  nogui of gateway, gui, cli ok; go test -run 'HTTPS|CAFile|MTLS|LAN'
  gateway, gui ok. GUI https-settings, mtls-settings, i18n-keys,
  gui-de/ja/zh-tw, allow-ips, lan-* (both engines): 147/155; reds are
  gui-ja (#5943), lan-docker (#4692), allow-ips webkit under load, and
  gui-zh-tw chromium under load (2 of 3 green alone, filed #5983).

Broken by hand:
- TLSOn without HTTPSOn: TestHTTPSOtherComputer red.
- lanGuard without the caFileOpen exemption: TestHTTPSCAFile red.
- mtls config without GetCertificate = settingsCert: all three
  serving tests red.
- app.js without renderHTTPS(s): https-settings red in both engines.

Not tried: the macOS, Windows and Linux system trust commands on a real
store (they change the box's trust); Claude Desktop itself; a darwin
GUI run (mote unreachable); the full suite before the tag (started
after it).
2026-11-10 23:05:47 +08:00

241 lines
8.8 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"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/settings"
)
func setHTTPS(t *testing.T, on bool) {
t.Helper()
if err := settings.SetHTTPS(on); err != nil {
t.Fatal(err)
}
if HTTPSOn() != on {
t.Fatalf("HTTPSOn() = %v after SetHTTPS(%v)", !on, on)
}
}
// trusting is an HTTPS client that trusts only roots' certificates.
func trusting(t *testing.T, roots ...*x509.Certificate) *http.Client {
t.Helper()
pool := x509.NewCertPool()
for _, c := range roots {
pool.AddCert(c)
}
tr := &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}, DisableKeepAlives: true}
t.Cleanup(tr.CloseIdleConnections)
return &http.Client{Timeout: 5 * time.Second, Transport: tr}
}
func magpieCA(t *testing.T) *x509.Certificate {
t.Helper()
b, fp, err := CA()
if err != nil {
t.Fatal(err)
}
blk, _ := pem.Decode(b)
if blk == nil {
t.Fatalf("CA() isn't PEM: %q", b)
}
c, err := x509.ParseCertificate(blk.Bytes)
if err != nil {
t.Fatal(err)
}
if fp != Fingerprint(c.Raw) || len(fp) != 32*3-1 {
t.Fatalf("fingerprint %q", fp)
}
return c
}
// zhangly1 on X: Claude on another computer on the LAN needed magpie at
// https://. With HTTPS on, another computer is served TLS with a
// certificate magpie's CA signs, which a client trusting that CA alone
// verifies, plain http:// from it is refused, and the switch takes
// effect at the next connection; off, it is plain http:// again.
func TestHTTPSOtherComputer(t *testing.T) {
key := mtlsHome(t, false)
addr := serveMTLSGateway(t, true, "")
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 {
t.Fatalf("off: %d %q %v", code, body, err)
}
setHTTPS(t, true)
if !TLSOn() || Scheme() != "https" {
t.Fatalf("TLSOn %v, Scheme %q with HTTPS on", TLSOn(), Scheme())
}
c := trusting(t, magpieCA(t))
for _, rt := range mtlsRoutes {
code, body, err := mcall(t, c, rt[0], "https://"+addr+rt[1], key)
if err != nil || code != 200 || body != "served "+rt[1] {
t.Errorf("on, %s %s: %d %q %v", rt[0], rt[1], code, body, err)
}
}
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err == nil && code < 400 {
t.Errorf("on, plain from another computer: %d %q, want it refused", code, body)
}
if _, _, err := mcall(t, trusting(t), "GET", "https://"+addr+"/v1/models", key); err == nil {
t.Error("a client that doesn't trust magpie's CA verified its certificate")
}
info, err := ServedCert()
if err != nil || info.From != "magpie" || info.Issuer == "" || !info.Until.After(time.Now()) {
t.Errorf("ServedCert: %+v %v", info, err)
}
setHTTPS(t, false)
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 {
t.Fatalf("off again: %d %q %v", code, body, err)
}
}
// This computer's own agents keep plain http:// with HTTPS on.
func TestHTTPSThisComputerPlain(t *testing.T) {
key := mtlsHome(t, false)
setHTTPS(t, true)
addr := serveMTLSGateway(t, false, "")
if code, body, err := mcall(t, plain, "GET", "http://"+addr+"/v1/models", key); err != nil || code != 200 {
t.Fatalf("this computer, plain: %d %q %v", code, body, err)
}
if code, body, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 {
t.Fatalf("this computer, https: %d %q %v", code, body, err)
}
}
// testPKI is a CA of the test's own and a server certificate it signs
// for 127.0.0.1, valid until notAfter.
type testPKI struct {
ca *x509.Certificate
caPEM, cert, key []byte
otherKey, encKey []byte
expiredC, expiredK []byte
}
func newTestPKI(t *testing.T) testPKI {
t.Helper()
var p testPKI
caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
caTpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Test Root"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign}
der, err := x509.CreateCertificate(rand.Reader, caTpl, caTpl, &caKey.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}
p.ca, _ = x509.ParseCertificate(der)
p.caPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
leaf := func(serial int64, until time.Time) ([]byte, []byte) {
k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
tpl := &x509.Certificate{SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: "nas.home"}, DNSNames: []string{"nas.home"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, NotBefore: until.Add(-48 * time.Hour), NotAfter: until, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature}
d, err := x509.CreateCertificate(rand.Reader, tpl, p.ca, &k.PublicKey, caKey)
if err != nil {
t.Fatal(err)
}
kd, _ := x509.MarshalPKCS8PrivateKey(k)
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: d}), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: kd})
}
p.cert, p.key = leaf(2, time.Now().Add(12*time.Hour))
_, p.otherKey = leaf(3, time.Now().Add(12*time.Hour))
p.expiredC, p.expiredK = leaf(4, time.Now().Add(-time.Hour))
p.encKey = pem.EncodeToMemory(&pem.Block{Type: "ENCRYPTED PRIVATE KEY", Bytes: []byte{1, 2, 3}})
return p
}
// The user's own certificate and key, imported (a chain and a key apart,
// in any order), are served instead of one magpie's CA signs; a pair
// that can't be served is refused and leaves nothing behind; removed,
// magpie's CA signs again.
func TestHTTPSImportedCert(t *testing.T) {
key := mtlsHome(t, false)
setHTTPS(t, true)
p := newTestPKI(t)
for name, files := range map[string][][]byte{
"no key": {p.cert},
"no certificate": {p.key},
"a stranger key": {p.cert, p.otherKey},
"a passphrase": {p.cert, p.encKey},
"run out": {p.expiredC, p.expiredK},
"nothing in them": {[]byte("hello")},
} {
if err := ImportCert(files...); err == nil {
t.Errorf("%s: imported", name)
}
if c, _ := ImportedFiles(); c != "" {
t.Fatalf("%s: left %s behind", name, c)
}
}
// the key first, the CA's certificate before the leaf: the leaf the
// key belongs to goes first
if err := ImportCert(p.key, append(append([]byte{}, p.caPEM...), p.cert...)); err != nil {
t.Fatal(err)
}
if c, k := ImportedFiles(); c == "" || k == "" {
t.Fatal("nothing kept")
} else if fi, err := os.Stat(k); err == nil && fi.Mode().Perm()&0o077 != 0 && os.PathSeparator == '/' {
t.Errorf("key.pem mode %v", fi.Mode().Perm())
}
addr := serveMTLSGateway(t, true, "")
if code, body, err := mcall(t, trusting(t, p.ca), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 {
t.Fatalf("imported: %d %q %v", code, body, err)
}
if _, _, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err == nil {
t.Error("magpie's CA's certificate was served over the imported one")
}
if info, err := ServedCert(); err != nil || info.From != "imported" || info.Issuer != "Test Root" || !strings.Contains(strings.Join(info.Names, ","), "nas.home") {
t.Errorf("ServedCert: %+v %v", info, err)
}
if err := RemoveImportedCert(); err != nil {
t.Fatal(err)
}
if code, body, err := mcall(t, trusting(t, magpieCA(t)), "GET", "https://"+addr+"/v1/models", key); err != nil || code != 200 {
t.Fatalf("removed: %d %q %v", code, body, err)
}
}
// Another computer fetches magpie's CA without a key, from an address
// the share lets in, before it trusts magpie's https://; every other
// route still asks for the key. With no CA made yet there is none.
func TestHTTPSCAFile(t *testing.T) {
mtlsHome(t, false)
var s Server
mux := http.NewServeMux()
mux.HandleFunc("GET "+CAPath, s.caFile)
mux.HandleFunc("GET /v1/models", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "models") })
h := lanGuard(mux)
get := func(path string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", path, nil)
r.RemoteAddr = "192.168.1.9:5000"
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
w := get(CAPath)
want, _, _ := CA()
if w.Code != 200 || w.Body.String() != string(want) || w.Header().Get("Content-Type") != "application/x-x509-ca-cert" {
t.Fatalf("CA: %d %q %q", w.Code, w.Header().Get("Content-Type"), w.Body.String())
}
if w := get("/v1/models"); w.Code != http.StatusUnauthorized && w.Code != http.StatusForbidden {
t.Errorf("/v1/models without a key: %d", w.Code)
}
if w := get(CAPath + "x"); w.Code < 400 {
t.Errorf("%sx without a key: %d", CAPath, w.Code)
}
if err := os.RemoveAll(filepath.Dir(MTLSStore().CAFile())); err != nil {
t.Fatal(err)
}
if w := get(CAPath); w.Code != http.StatusNotFound {
t.Errorf("no CA: %d", w.Code)
}
}