Files
magpie/internal/gui/mtls.go
T
yetone efb75ad1f0 gateway: client certificates (mTLS), and Remote Magpie can show one (hhdaxia on X, #5596)
hhdaxia on X asked for mTLS so a shared magpie isn't open to the internet
on a key alone; clxsh's #5596 asks Remote Magpie to send a client
certificate and key (PEM) to an Nginx doing mTLS, the server still
verified, the Gateway Key still sent, for models, the test and streaming.

Server side (magpie's own CA, internal/mtls):
- Settings -> Network and sharing -> Require a client certificate, or
  `magpie mtls on|off|issue <device>|list|revoke`. Issue saves
  client.pem, client-key.pem and ca.pem to ~/Downloads/magpie-<device>;
  the key is kept nowhere else.
- With it on, a peer that isn't this computer or a WSL distro must finish
  the TLS handshake with a certificate the CA issued and hasn't revoked
  (RequireAndVerifyClientCert + VerifyConnection -> Admits). The TLS
  config is chosen per connection, so the switch needs no relisten;
  without --tls-cert the server certificate is made by the CA in memory.
- lanGuard and ClientCertGuard (magpie web's page) refuse 403 what still
  arrives without a verified one: plain HTTP, a proxy or tunnel on
  loopback (unless MAGPIE_TRUST_PROXY=1), the page port, a connection
  from before the switch, a certificate revoked since its handshake.
- Loopback, this computer's own address and a WSL agent with its key are
  answered as before.
- A page open from another computer can't shut itself out: without a
  certificate it can't turn mTLS on, and it can't revoke or reissue the
  certificate it came with.

Client side: a provider with a base URL of the user's own (Remote
Magpie included) takes ClientCert, ClientKey and ServerCA paths (editor:
Advanced -> Client certificate). netproxy.WithClientCert shows them to
that provider's own hosts only, on a transport per identity keyed on the
files' mtimes; through an https:// proxy such a request is refused. Save
refuses half a pair, a pair that doesn't match and a CA that isn't one.

Run (on mote, at 4024df0f9, this commit before its rebase):
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 ./internal/mtls ./internal/netproxy ./internal/provider
  ./internal/settings ./internal/settingsapi ./internal/cli ./internal/gui
  ./internal/gateway: ok (gateway 893s). The first run had three reds of
  this change, each green at base and fixed here:
  TestEveryRouteHasACommandOrIsNamed (the mtls routes now name `magpie
  mtls`), TestSettingsSaveKeepsWhatItDoesNotSend (MTLS kept), and
  TestGoroutineDumpAnswersWhileRequestsWait (mtlsRefuses asks whether the
  peer is remote before reading settings, so a local request never waits
  on the settings lock). TestHandedOffGatewayAnswersAConnectionNotedLate
  was reset because ServeTLS now always wraps the listener: tlsListener
  hands a connection it took as Close came to the server instead of
  dropping it. -count=3 of these and every TLS/MTLS/Handover/Relisten test
  ok.
- Every route without a certificate, with a foreign one, a revoked one
  and a good one: TestMTLSOtherComputerHandshake, TestMTLSGuardEveryRoute,
  TestMTLSThisComputerAndProxies, TestMTLSToggleWithoutRelisten,
  TestMTLSRevokeMidConnection, TestClientCertGuardPage. Remote Magpie
  against an httptest server asking RequireAndVerifyClientCert: models
  and the connection test fail without the certificate and pass with it
  (TestRemoteMagpieClientCert).
- GUI: the 92 files near the change (settings-*, provider-*, editor-*,
  lan-*, i18n*, allow-ips, remote-*, mtls-settings new) in Chromium and
  WebKit: 2904 pass, 74 fail, all in nine files red the same way at base
  0791c91c5 and listed in #5872 (editor-thumbs-batched also #5886;
  provider-fetch-again #5057 #5232; provider-many-keys, -models-rest,
  -picks-stay, -typed #5475 #4396 #5233 #4673; remote-magpie #4398;
  settings-hints, settings-lines-wrap run alone at base and here: the
  same 8 reds). The whole GUI suite and the whole Go suite were not run:
  mote's suite lock had about 15 runs queued at load 31-40.

Rebased on 031938ca9 (one conflict, internal/gui/api.go's route list,
both kept) and run again there: gofmt clean, vet on three systems, go
test ./internal/{gui,cli,mtls,netproxy,provider,settings,settingsapi} ok
(cli with the next commit's line), the gateway's TLS, MTLS, Handover,
Relisten, HandedOff, GoroutineDump, ClientCert and RemoteMagpie tests ok,
TestCoreScriptBudget ok, and mtls-settings, i18n-keys, allow-ips and
provider-insecure-tls in Chromium and WebKit: 143 pass, 0 fail.

Broken by hand, each red:
- lanGuard without refuseWithoutClientCert: TestMTLSGuardEveryRoute,
  TestMTLSThisComputerAndProxies, TestMTLSRevokeMidConnection.
- VerifyClientCertIfGiven and no Admits: TestMTLSOtherComputerHandshake.
- netproxy.With keeping another provider's certificate:
  TestClientCertOnlyItsHost.
- The page-lockout and own-serial guards in internal/gui/mtls.go:
  TestSettingsMTLSPageLockout.

Not tried: a real Nginx doing mTLS; a Windows or Linux run (vet only);
installing the certificate in a browser (there is no .p12 yet); a
proxy that checks certificates itself with MAGPIE_TRUST_PROXY=1.
2026-11-10 14:27:21 +08:00

125 lines
3.9 KiB
Go

package gui
import (
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/mtls"
"github.com/yetone/magpie/internal/settings"
)
// mtlsCert is a client certificate magpie issued (hhdaxia on X, #5596),
// for Settings → Network and sharing: one still good, the newest last.
type mtlsCert struct {
Name string `json:"name"`
Serial string `json:"serial"`
Expires time.Time `json:"expires"`
}
// mtlsCerts: the certificates still good, and the list's error when it
// can't be read (then none is admitted either).
func mtlsCerts() ([]mtlsCert, string) {
l, err := gateway.MTLSStore().List()
if err != nil {
return nil, err.Error()
}
out := []mtlsCert{}
now := time.Now()
for _, c := range l {
if c.Good(now) {
out = append(out, mtlsCert{Name: c.Name, Serial: c.Serial, Expires: c.Expires})
}
}
return out, ""
}
// pageCert is the client certificate a browser page came with (magpie
// web, or the app's page, opened from another computer): revoking it, or
// issuing its name again, would shut that page out at its next request.
func pageCert(w Windows, r *http.Request) *x509.Certificate {
if !isWeb(w) || r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
return nil
}
return r.TLS.PeerCertificates[0]
}
var errOwnCert = errors.New("this page came with that certificate, so it would be shut out: do this from another device, or from the computer magpie runs on")
func mtlsRoutes(mux *http.ServeMux, w Windows) {
// on or off: on makes the CA first. A page open from another computer
// without a certificate this magpie issued can't turn it on, which
// would shut that page out at its next request.
mux.HandleFunc("POST /api/settings/mtls", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ On bool }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if in.On {
if isWeb(w) && gateway.NeedsClientCert(r) != "" {
fail(rw, errors.New("this page is open from another computer without a client certificate this magpie issued, so turning this on would shut it out: issue one, install it in this browser, and open the page again over https://, or turn it on from the computer magpie runs on"))
return
}
if _, _, err := gateway.MTLSStore().CA(); err != nil {
fail(rw, err)
return
}
}
if err := settings.SetMTLS(in.On); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// a certificate for a device, saved to Downloads as magpie-<name>:
// client.pem, client-key.pem and ca.pem; the key is kept nowhere else
mux.HandleFunc("POST /api/settings/mtls/issue", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Name string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if c := pageCert(w, r); c != nil && strings.EqualFold(c.Subject.CommonName, strings.TrimSpace(in.Name)) {
fail(rw, errOwnCert)
return
}
iss, err := gateway.MTLSStore().Issue(in.Name)
if err != nil {
fail(rw, err)
return
}
dir, err := mtls.Export(iss, downloads())
if err != nil {
fail(rw, fmt.Errorf("issued, but the files couldn't be saved, so the certificate is revoked again: %w", err))
gateway.MTLSStore().Revoke(iss.Serial)
return
}
_ = w.OpenFolder(dir) // saved either way; the path is in the answer
st := settingsState()
st.MTLSSaved = tilde(dir)
writeJSON(rw, st)
})
mux.HandleFunc("POST /api/settings/mtls/revoke", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Serial string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if c := pageCert(w, r); c != nil && strings.EqualFold(c.SerialNumber.Text(16), strings.TrimSpace(in.Serial)) {
fail(rw, errOwnCert)
return
}
if _, err := gateway.MTLSStore().Revoke(in.Serial); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
}