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 base0791c91c5and 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 on031938ca9(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.
206 lines
6.9 KiB
Go
206 lines
6.9 KiB
Go
package netproxy
|
|
|
|
import (
|
|
"context"
|
|
"crypto/tls"
|
|
"errors"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/mtls"
|
|
)
|
|
|
|
// mtlsServer is an HTTPS server with a certificate st's CA signs, that
|
|
// asks for a client certificate st's CA issued (require) or takes one if
|
|
// given, and answers with the name on the one shown.
|
|
func mtlsServer(t *testing.T, st mtls.Store, require bool, h http.HandlerFunc) *httptest.Server {
|
|
t.Helper()
|
|
cert, err := st.ServerCert([]string{"localhost"}, []net.IP{net.IPv4(127, 0, 0, 1)})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
pool, err := st.Pool()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if h == nil {
|
|
h = func(w http.ResponseWriter, r *http.Request) {
|
|
name := "none"
|
|
if len(r.TLS.PeerCertificates) > 0 {
|
|
name = r.TLS.PeerCertificates[0].Subject.CommonName
|
|
}
|
|
io.WriteString(w, name)
|
|
}
|
|
}
|
|
s := httptest.NewUnstartedServer(h)
|
|
s.Config.ErrorLog = log.New(io.Discard, "", 0)
|
|
s.TLS = &tls.Config{Certificates: []tls.Certificate{cert}, ClientCAs: pool, ClientAuth: tls.VerifyClientCertIfGiven}
|
|
if require {
|
|
s.TLS.ClientAuth = tls.RequireAndVerifyClientCert
|
|
}
|
|
s.StartTLS()
|
|
t.Cleanup(s.Close)
|
|
return s
|
|
}
|
|
|
|
// device issues a certificate for name and writes the three files a
|
|
// device is given, returning their paths.
|
|
func device(t *testing.T, st mtls.Store, name string) (cert, key, ca string) {
|
|
t.Helper()
|
|
iss, err := st.Issue(name)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d, err := mtls.Export(iss, t.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return filepath.Join(d, "client.pem"), filepath.Join(d, "client-key.pem"), filepath.Join(d, "ca.pem")
|
|
}
|
|
|
|
func body(t *testing.T, c *http.Client, ctx context.Context, u string) (string, error) {
|
|
t.Helper()
|
|
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
|
res, err := c.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer res.Body.Close()
|
|
b, err := io.ReadAll(res.Body)
|
|
return string(b), err
|
|
}
|
|
|
|
// A provider's client certificate and server CA (#5596) reach its own
|
|
// host alone: the host it names is reached with them, while the same
|
|
// request without them, one to another host signed by the same CA, a
|
|
// redirect there, and one made for another provider (With) are not shown
|
|
// the certificate nor take the CA.
|
|
func TestClientCertOnlyItsHost(t *testing.T) {
|
|
st := mtls.Store{Dir: t.TempDir()}
|
|
other := mtlsServer(t, st, false, nil)
|
|
own := mtlsServer(t, st, true, func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/elsewhere" {
|
|
http.Redirect(w, r, other.URL+"/", http.StatusFound)
|
|
return
|
|
}
|
|
io.WriteString(w, r.TLS.PeerCertificates[0].Subject.CommonName)
|
|
})
|
|
cert, key, ca := device(t, st, "laptop")
|
|
d := Dispatch(&http.Transport{Proxy: Func, ForceAttemptHTTP2: true}).(*dispatch)
|
|
t.Cleanup(d.CloseIdleConnections)
|
|
c := &http.Client{Transport: d}
|
|
bg := context.Background()
|
|
mine := WithClientCert(bg, cert, key, ca, own.URL+"/v1")
|
|
|
|
if _, err := body(t, c, bg, own.URL); !certRefused(err) {
|
|
t.Fatalf("without them: want a certificate error, got %v", err)
|
|
}
|
|
if got, err := body(t, c, mine, own.URL+"/v1/models"); err != nil || got != "laptop" {
|
|
t.Fatalf("with them: %q, %v", got, err)
|
|
}
|
|
if _, err := body(t, c, mine, other.URL); !certRefused(err) {
|
|
t.Fatalf("another host: want a certificate error, got %v", err)
|
|
}
|
|
if _, err := body(t, c, mine, own.URL+"/elsewhere"); !certRefused(err) {
|
|
t.Fatalf("a redirect to another host: want a certificate error, got %v", err)
|
|
}
|
|
if _, err := body(t, c, With(mine, ""), own.URL); !certRefused(err) {
|
|
t.Fatalf("a request made for another provider: want a certificate error, got %v", err)
|
|
}
|
|
if _, err := body(t, c, WithClientCert(bg, cert, key, ca, "http://"+strings.TrimPrefix(own.URL, "https://")), own.URL); !certRefused(err) {
|
|
t.Fatalf("an http:// base: want a certificate error, got %v", err)
|
|
}
|
|
}
|
|
|
|
// A server CA alone (a server that takes no client certificate, signed by
|
|
// a CA of the user's) is trusted beside the system's roots, and no
|
|
// certificate is shown; a server that asks for one is refused without.
|
|
func TestServerCAAlone(t *testing.T) {
|
|
st := mtls.Store{Dir: t.TempDir()}
|
|
lenient := mtlsServer(t, st, false, nil)
|
|
strict := mtlsServer(t, st, true, nil)
|
|
_, _, ca := device(t, st, "x")
|
|
d := Dispatch(&http.Transport{Proxy: Func}).(*dispatch)
|
|
t.Cleanup(d.CloseIdleConnections)
|
|
c := &http.Client{Transport: d}
|
|
ctx := WithClientCert(context.Background(), "", "", ca, lenient.URL, strict.URL)
|
|
if got, err := body(t, c, ctx, lenient.URL); err != nil || got != "none" {
|
|
t.Fatalf("CA alone: %q, %v", got, err)
|
|
}
|
|
if _, err := body(t, c, ctx, strict.URL); err == nil {
|
|
t.Fatal("a server asking for a certificate answered without one")
|
|
}
|
|
}
|
|
|
|
// A certificate renewed in place (the same paths) is shown from the next
|
|
// request: the route names each file's change.
|
|
func TestClientCertRenewedInPlace(t *testing.T) {
|
|
st := mtls.Store{Dir: t.TempDir()}
|
|
s := mtlsServer(t, st, true, nil)
|
|
cert, key, ca := device(t, st, "old")
|
|
d := Dispatch(&http.Transport{Proxy: Func, DisableKeepAlives: true}).(*dispatch)
|
|
c := &http.Client{Transport: d}
|
|
ctx := WithClientCert(context.Background(), cert, key, ca, s.URL)
|
|
if got, _ := body(t, c, ctx, s.URL); got != "old" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
c2, k2, _ := device(t, st, "new")
|
|
for from, to := range map[string]string{c2: cert, k2: key} {
|
|
b, _ := os.ReadFile(from)
|
|
if err := os.WriteFile(to, append(b, '\n'), 0o600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if got, err := body(t, c, ctx, s.URL); got != "new" {
|
|
t.Fatalf("after renewal: %q, %v", got, err)
|
|
}
|
|
}
|
|
|
|
// An https:// proxy would be shown the certificate (its TLS is dialled
|
|
// with the same config), so a request with one is refused there; an
|
|
// http:// proxy is used as it is.
|
|
func TestClientCertRefusesHTTPSProxy(t *testing.T) {
|
|
for scheme, refused := range map[string]bool{"https": true, "http": false} {
|
|
tr := &http.Transport{Proxy: func(*http.Request) (*url.URL, error) { return &url.URL{Scheme: scheme, Host: "proxy:8080"}, nil }}
|
|
clientTLS(tr, "c.pem\x00k.pem\x00\x00")
|
|
u, err := tr.Proxy(httptest.NewRequest(http.MethodGet, "https://h/", nil))
|
|
if refused != errors.Is(err, ErrClientCertOverHTTPSProxy) || (!refused && u == nil) {
|
|
t.Errorf("%s proxy: %v, %v", scheme, u, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCheckClientCert(t *testing.T) {
|
|
st := mtls.Store{Dir: t.TempDir()}
|
|
cert, key, ca := device(t, st, "x")
|
|
_, otherKey, _ := device(t, st, "y")
|
|
junk := filepath.Join(t.TempDir(), "junk.pem")
|
|
os.WriteFile(junk, []byte("not pem"), 0o600)
|
|
for _, c := range []struct {
|
|
cert, key, ca string
|
|
ok bool
|
|
}{
|
|
{"", "", "", true},
|
|
{cert, key, ca, true},
|
|
{cert, key, "", true},
|
|
{"", "", ca, true},
|
|
{cert, "", "", false},
|
|
{"", key, "", false},
|
|
{cert, otherKey, "", false},
|
|
{cert, key, junk, false},
|
|
{cert, key, filepath.Join(t.TempDir(), "gone.pem"), false},
|
|
} {
|
|
if err := CheckClientCert(c.cert, c.key, c.ca); (err == nil) != c.ok {
|
|
t.Errorf("%q %q %q: %v", filepath.Base(c.cert), filepath.Base(c.key), filepath.Base(c.ca), err)
|
|
}
|
|
}
|
|
}
|