Zhangzhangi on X couldn't add a Remote magpie at a domain with a
self-signed certificate ("x509: "api.magpie.local" certificate is not
standards compliant") and asked for a skip-verification option. A
follow-up asked for the same on other self-signed hosts.
This adds a pin (trust on first use), not a blind skip. It is off by
default and kept per provider:
- Advanced → Server certificate → "Trust its certificate…" fetches the
certificate the server shows (provider/peekcert) and lists its SHA-256,
subject, issuer and expiry. "Trust this certificate" keeps the
fingerprint as the provider's serverPin.
- From then on only that certificate is accepted (netproxy pinTLS:
InsecureSkipVerify plus VerifyConnection comparing the leaf's DER
SHA-256). Another one fails with PinMismatchError, saying the server
showed a certificate other than the one trusted.
- The editor shows a red "Certificate not verified: only this one is
accepted" with the fingerprint, and "Verify it again" drops the pin.
- The pin is set only on the provider's own hosts (provider.PinHosts):
- every address of Remote magpie and of a provider added by URL;
- for a preset (Ollama, LM Studio, OpenAI at your own box), only https
addresses whose host is not one of the preset's or its regions' own
hosts. A vendor's host never takes a pin.
- Never for an account, Vertex or a subscription. Save refuses one
elsewhere.
- The client certificate and Server CA still go only to the providers
that took them before (TakesClientCert). A preset gets the pin alone.
- The editor's certificate rows (Client certificate and the new Server
certificate) are drawn by a lazily imported tlscerts.js. The Client
certificate row moved out of app.js with it, so the core scripts stay
under TestCoreScriptBudget without a raise.
Run (Go 1.26.8):
- WSL magpie-desktop, before the rebase:
- go test -tags nogui -count=1 ./internal/netproxy ./internal/provider
./internal/gui all ok;
- GOOS=darwin -tags nogui vet of gui fails on traywindows_darwin_test.go's
undefined trayImagePNG, the same at the base (a cgo-only helper).
- mote and mica, after the rebase on ab5824aee:
- gofmt -l clean; node --check app.js;
- go vet darwin (cgo), GOOS=linux -tags nogui, GOOS=windows: ok;
- go test ./internal/netproxy ./internal/provider: ok.
- mote, at the final tree: node --check app.js and tlscerts.js; go test
./internal/gui -run 'Budget|ServerPin|InsecureTLS|ClientCert|OnDemand|Lazy'
ok (TestCoreScriptBudget under 1,533,802) at the base ab5824aee.
Rebased on fe5a0cf6d, TestCoreScriptBudget is red, as it is on that
main alone: main's core is 1,534,708 (16ed1a952 took it to 1,535,318);
this change takes it to 1,534,484, 224 bytes less (#5918, commented).
The rest of the run above passes at the pushed head.
- mica, GUI files at the final tree, both engines inside each file:
- green: provider-server-pin (54), mtls-settings (16),
provider-insecure-tls (60), provider-socket (60), provider-http1 (60),
i18n-keys, i18n-en-no-cjk, editor-advanced-align, provider-advanced-fold
(50);
- old-webkit: headerpresets.js not loaded (#6030) and Safari 15's :has()
(#5919), both on main too;
- menu-scroll: 24 of 24 red on /api/update/using, the same alone at
origin/main fe5a0cf6d (#5982, commented).
- Earlier flakes of provider-http1 beside another session's suite:
#6159.
- Broken by hand, each red:
- presets never take a pin: TestServerPinSaveChecks,
TestServerPinPresetAtOwnServer, TestServerPinNoVendorHost;
- vendor hosts pinned (the own-host check dropped):
TestServerPinNoVendorHost;
- client cert and CA sent to presets: TestServerPinPresetAtOwnServer;
- the pin never compared: TestPinOnlyThatCertificate,
TestServerPinRemoteMagpie.
Restored: both packages ok.
Not tried:
- a real self-signed domain from the macOS app (httptest servers with
their own certificates only);
- the Responses WebSocket dial (read only: it takes the same netproxy
transport);
- go test ./internal/cli and the whole GUI suite before the tag (the
full Go suite runs after it, under suite.lock).
206 lines
7.0 KiB
Go
206 lines
7.0 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)
|
|
}
|
|
}
|
|
}
|