Files
magpie/internal/cli/mtls_cli.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

156 lines
4.7 KiB
Go

package cli
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/mtls"
"github.com/yetone/magpie/internal/settings"
)
const mtlsUsage = `usage: magpie mtls [on|off|issue <device> [--out <folder>]|list|revoke <device or serial>]
other computers reach this magpie only with a client certificate it issued (mTLS;
hhdaxia on X, #5596). On, the gateway and magpie web's page are served over https://
to them with magpie's own CA (or the --tls-cert one), and a request without a good
certificate is refused, a gateway key or not. This computer, and a WSL distro's agent
with its key, are answered as before.
magpie mtls whether it is on, and the certificates issued
magpie mtls on|off require a client certificate from other computers, or stop
magpie mtls issue <name> a certificate for one device: client.pem, client-key.pem and
ca.pem in Downloads/magpie-<name> (or --out <folder>). Give the
device all three; the key is not kept here. Issuing a name
again revokes the one before.
magpie mtls revoke <name> refuses that device's certificate from now on
In Remote magpie (or a provider) on the other computer, set Client certificate, Client key
and Server CA to the three files. curl: --cert client.pem --key client-key.pem --cacert ca.pem.`
func mtlsCmd(args []string) error {
st := gateway.MTLSStore()
if len(args) == 0 || args[0] == "list" || args[0] == "status" {
return mtlsList(st)
}
switch args[0] {
case "on", "off":
on := args[0] == "on"
if on {
if _, _, err := st.CA(); err != nil {
return err
}
}
if err := settings.SetMTLS(on); err != nil {
return err
}
if !on {
fmt.Println("mTLS off: other computers are answered as before (a gateway key, while shared)")
return nil
}
fmt.Println("mTLS on: other computers need a client certificate magpie issued; this computer is answered as before")
if l, _ := st.List(); len(l) == 0 {
fmt.Println("no certificate issued yet: magpie mtls issue <device>")
}
return nil
case "issue":
rest, out, err := outFlag(args[1:])
if err != nil {
return err
}
if len(rest) != 1 {
return errors.New("usage: magpie mtls issue <device> [--out <folder>]")
}
iss, err := st.Issue(rest[0])
if err != nil {
return err
}
if out == "" {
out = downloadsDir()
}
dir, err := mtls.Export(iss, out)
if err != nil {
return err
}
fmt.Printf("issued %q (serial %s, valid until %s)\n", iss.Name, iss.Serial, iss.Expires.Format("2006-01-02"))
fmt.Println(" " + dir + string(filepath.Separator) + " client.pem, client-key.pem, ca.pem")
if !gateway.MTLSOn() {
fmt.Println("mTLS is off: magpie mtls on to require it")
}
return nil
case "revoke":
if len(args) != 2 {
return errors.New("usage: magpie mtls revoke <device or serial>")
}
n, err := st.Revoke(args[1])
if err != nil {
return err
}
if n == 0 {
return fmt.Errorf("no certificate issued to %q that isn't revoked already", args[1])
}
fmt.Printf("revoked %d certificate(s) for %q\n", n, args[1])
return nil
}
return fmt.Errorf("magpie mtls: unknown %q\n%s", args[0], mtlsUsage)
}
func mtlsList(st mtls.Store) error {
state := "off"
if gateway.MTLSOn() {
state = "on"
}
fmt.Println("mTLS " + state)
l, err := st.List()
if err != nil {
return err
}
now := time.Now()
for _, c := range l {
why := "valid until " + c.Expires.Format("2006-01-02")
switch {
case !c.Revoked.IsZero():
why = "revoked " + c.Revoked.Format("2006-01-02")
case !c.Good(now):
why = "ran out " + c.Expires.Format("2006-01-02")
}
fmt.Printf(" %-24s %s issued %s · %s\n", c.Name, c.Serial, c.Issued.Format("2006-01-02"), why)
}
return nil
}
// outFlag takes --out <folder> (or --out=<folder>) out of args.
func outFlag(args []string) (rest []string, out string, err error) {
for i := 0; i < len(args); i++ {
switch a := args[i]; {
case a == "--out":
if i+1 >= len(args) {
return nil, "", errors.New("--out takes a folder")
}
i++
out = args[i]
case strings.HasPrefix(a, "--out="):
out = strings.TrimPrefix(a, "--out=")
case strings.HasPrefix(a, "-"):
return nil, "", fmt.Errorf("unknown flag %s", a)
default:
rest = append(rest, a)
}
}
return rest, out, nil
}
// downloadsDir is the Downloads folder the system keeps, else
// home/Downloads, else this folder.
func downloadsDir() string {
home, _ := os.UserHomeDir()
for _, d := range []string{appdir.Downloads(), filepath.Join(home, "Downloads")} {
if fi, err := os.Stat(d); d != "" && err == nil && fi.IsDir() {
return d
}
}
return "."
}