diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 8221682a8..45a18176d 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -1075,6 +1075,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { proxy := hostProxy(env()) // what bunCommand gives it cmd := bunCommand(context.Background(), bun, settings.Dir(), "run", js) addr := hostAddr(cmd.Env) + log.Printf("plugin: host starts with %s", netLine(cmd.Env)) cmd.Env = hostEnv(cmd.Env) in, err := cmd.StdinPipe() if err != nil { @@ -1914,7 +1915,51 @@ func (h *host) proxyMoved() bool { } h.proxyAt = time.Now() e := env() - return hostProxy(e) != h.proxy || h.addr != "" && hostAddr(e) != h.addr + if p := hostProxy(e); p != h.proxy { + log.Printf("plugin: the proxy moved, from %s to %s; a new host takes over", + netLine(strings.Split(h.proxy, "\x00")), netLine(strings.Split(p, "\x00"))) + return true + } + if a := hostAddr(e); h.addr != "" && a != h.addr { + log.Printf("plugin: the gateway moved, from %s to %s; a new host takes over", h.addr, a) + return true + } + return false +} + +// netLine is a host's network settings in env as a log line says them: +// its proxy, without the user and password (netproxy.Redact), NO_PROXY, +// and what tells Bun which roots to trust. A host's TLS or proxy failure +// ("unable to get issuer certificate" for a chain that verifies outside +// it, youyo.p_10001) is read beside it. +func netLine(env []string) string { + keys := []string{"HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "NO_PROXY", + "NODE_EXTRA_CA_CERTS", "NODE_USE_SYSTEM_CA", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE", "SSL_CERT_DIR"} + got := map[string]string{} + for _, e := range env { + k, v, _ := strings.Cut(e, "=") + k = strings.ToUpper(k) + if slices.Contains(keys, k) { + got[k] = v // exec takes the last + } + } + var parts []string + for _, k := range keys { + v := strings.TrimSpace(got[k]) + if v == "" { + continue + } + if strings.HasSuffix(k, "_PROXY") && k != "NO_PROXY" { + if v = netproxy.Redact(v); v == "" { + v = "(malformed)" + } + } + parts = append(parts, k+"="+v) + } + if !slices.ContainsFunc(parts, func(p string) bool { return strings.Contains(p, "_PROXY=") && !strings.HasPrefix(p, "NO_PROXY=") }) { + parts = append([]string{"no proxy"}, parts...) + } + return strings.Join(parts, " ") } // hostAddr is the gateway's address a host is told, as MAGPIE_ADDR: the diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 27a71d6fe..73778f03f 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -498,17 +498,46 @@ async function proxyFor(input) { const reach = new AsyncLocalStorage() async function sent(input, init) { - if (init && "proxy" in init) return bunFetch(input, init) + if (init && "proxy" in init) return bunFetch(input, init).catch((e) => throwTLS(e, input)) const p = await proxyFor(input) - if (!p) return bunFetch(input, init) + if (!p) return bunFetch(input, init).catch((e) => throwTLS(e, input)) return bunFetch(input, { ...init, proxy: p }).catch(async (e) => { if (e?.name === "AbortError" || init?.signal?.aborted) throw e const why = await proxyRefuses(p, input) if (why) throw Object.assign(new Error(`proxyconnect tcp: ${why}`), { code: e?.code, cause: e }) - throw e + throwTLS(e, input) }) } +// The codes Bun gives a fetch whose server's certificate it didn't take. +const tlsCodes = new Set([ + "UNABLE_TO_GET_ISSUER_CERT", + "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", + "UNABLE_TO_VERIFY_LEAF_SIGNATURE", + "SELF_SIGNED_CERT_IN_CHAIN", + "DEPTH_ZERO_SELF_SIGNED_CERT", + "CERT_HAS_EXPIRED", + "CERT_NOT_YET_VALID", + "CERT_UNTRUSTED", + "ERR_TLS_CERT_ALTNAME_INVALID", +]) + +// throwTLS throws e, its message saying which host's certificate the +// plugin host refused and with what code, when that is why it failed: +// Bun says only "unable to get issuer certificate", which read like the +// vendor's own fault, for a chain that verified outside the host +// (youyo.p_10001). The message Bun gave stays first, and the error is +// the same one, its code and cause kept. +function throwTLS(e, input) { + if (e && tlsCodes.has(e.code) && typeof e.message === "string" && !e.message.includes("plugin host's TLS")) { + const h = hostOf(input)?.host + try { + e.message = `${e.message} (${e.code}: the plugin host's TLS didn't verify ${h ? h + "'s" : "the server's"} certificate chain against the roots it trusts)` + } catch {} + } + throw e +} + // proxyRefuses is why the proxy p won't carry a request to input, "" when // it will: Bun says a proxy that is down, or that turns the tunnel away, // only as a connection that failed, which a vendor's own failure is too. diff --git a/internal/plugin/host_netline_test.go b/internal/plugin/host_netline_test.go new file mode 100644 index 000000000..e9873e0a8 --- /dev/null +++ b/internal/plugin/host_netline_test.go @@ -0,0 +1,23 @@ +package plugin + +import ( + "strings" + "testing" +) + +// The line a host's start and a moved proxy log says the proxy without +// its password, NO_PROXY, and how Bun is told which roots to trust. +func TestNetLineSaysNoSecret(t *testing.T) { + got := netLine([]string{"PATH=/bin", "HTTPS_PROXY=http://me:s3cret@127.0.0.1:7897", "http_proxy=http://127.0.0.1:7897", + "NO_PROXY=localhost,*.cn", "NODE_USE_SYSTEM_CA=1", "NODE_EXTRA_CA_CERTS=ca.pem", "SSL_CERT_DIR="}) + want := "HTTPS_PROXY=http://127.0.0.1:7897 HTTP_PROXY=http://127.0.0.1:7897 NO_PROXY=localhost,*.cn NODE_EXTRA_CA_CERTS=ca.pem NODE_USE_SYSTEM_CA=1" + if got != want { + t.Errorf("netLine = %q\nwant %q", got, want) + } + if strings.Contains(got, "s3cret") || strings.Contains(got, "me:") { + t.Errorf("netLine says the proxy's user or password: %q", got) + } + if got := netLine(strings.Split(hostProxy([]string{"NO_PROXY=localhost"}), "\x00")); got != "no proxy NO_PROXY=localhost" { + t.Errorf("netLine with no proxy = %q", got) + } +} diff --git a/internal/plugin/systemca.go b/internal/plugin/systemca.go index e5b7fe120..ce36161e1 100644 --- a/internal/plugin/systemca.go +++ b/internal/plugin/systemca.go @@ -3,6 +3,7 @@ package plugin import ( "bytes" "crypto/sha256" + "crypto/x509" "encoding/hex" "encoding/pem" "os" @@ -103,19 +104,89 @@ var systemCAFile = func() string { systemCAPath = p return } - certs := systemRoots() - if len(certs) == 0 { - return - } - var b bytes.Buffer - for _, der := range certs { - _ = pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: der}) - } - systemCAPath = writeCAFile(b.Bytes()) + systemCAPath = rootsFile(systemRoots()) }) return systemCAPath } +// rootsFile is a PEM file of certs as rootsFirst orders them, "" when +// none are left. +func rootsFile(certs [][]byte) string { + certs = rootsFirst(certs) + if len(certs) == 0 { + return "" + } + var b bytes.Buffer + for _, der := range certs { + _ = pem.Encode(&b, &pem.Block{Type: "CERTIFICATE", Bytes: der}) + } + return writeCAFile(b.Bytes()) +} + +// rootsFirst is certs as Bun can be given them: the self-signed ones +// first, then each other one whose issuer is among them. Bun (BoringSSL, +// 1.4.2) builds a chain up through the first certificate it trusts with +// the subject it is after, NODE_EXTRA_CA_CERTS's before its own roots', +// and goes no further when that one's issuer is missing. A copy of a root +// that another root cross-signed (USERTrust RSA's, issued by AAA +// Certificate Services, which agent.minimaxi.com's chain goes up to) in +// the user's ROOT store came ahead of the self-signed one Bun ships, and +// every request there failed "unable to get issuer certificate" +// (UNABLE_TO_GET_ISSUER_CERT, youyo.p_10001 on Discord, Windows), while +// Node, curl and a browser got through. With the self-signed copy ahead +// of it, or with its issuer beside it, Bun got through. One whose issuer +// isn't here either is left out: Bun never ends a chain on a certificate +// that isn't self-signed, so it can only stand in front of a root. One +// Go can't parse is kept, after the rest, as before. +func rootsFirst(certs [][]byte) [][]byte { + type cert struct { + der []byte + x *x509.Certificate + } + var roots, rest []cert + var odd [][]byte + for _, der := range certs { + x, err := x509.ParseCertificate(der) + switch { + case err != nil: + odd = append(odd, der) + case bytes.Equal(x.RawSubject, x.RawIssuer): + roots = append(roots, cert{der, x}) + default: + rest = append(rest, cert{der, x}) + } + } + kept := append([]cert(nil), roots...) + issued := func(c cert) bool { + for _, k := range kept { + if bytes.Equal(k.x.RawSubject, c.x.RawIssuer) && + (len(c.x.AuthorityKeyId) == 0 || len(k.x.SubjectKeyId) == 0 || bytes.Equal(c.x.AuthorityKeyId, k.x.SubjectKeyId)) { + return true + } + } + return false + } + // an intermediate's issuer can be another intermediate + for grew := true; grew; { + grew = false + left := rest[:0] + for _, c := range rest { + if issued(c) { + kept = append(kept, c) + grew = true + } else { + left = append(left, c) + } + } + rest = left + } + out := make([][]byte, 0, len(kept)+len(odd)) + for _, k := range kept { + out = append(out, k.der) + } + return append(out, odd...) +} + // writeCAFile keeps pem beside Bun's install cache, named by its content so // a Bun that is running keeps reading the file it was given. func writeCAFile(b []byte) string { diff --git a/internal/plugin/systemca_cross_test.go b/internal/plugin/systemca_cross_test.go new file mode 100644 index 000000000..6a7729728 --- /dev/null +++ b/internal/plugin/systemca_cross_test.go @@ -0,0 +1,207 @@ +package plugin + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "fmt" + "math/big" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/testenv" +) + +// crossChain is a server whose chain goes up to a root (root) that +// another root (top) also signed (cross): leaf, then int, then root's +// subject, as USERTrust RSA's is for agent.minimaxi.com. The server sends +// leaf and int, as that one does. +type crossChain struct { + top, root, cross, int, leaf []byte + url string +} + +func newCrossChain(t *testing.T) crossChain { + t.Helper() + key := func() *ecdsa.PrivateKey { + k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + return k + } + serial := int64(0) + ca := func(name string, skid byte) *x509.Certificate { + serial++ + return &x509.Certificate{ + SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: name}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + SubjectKeyId: []byte{skid}, + } + } + mk := func(tpl, parent *x509.Certificate, pub *ecdsa.PublicKey, priv *ecdsa.PrivateKey) ([]byte, *x509.Certificate) { + der, err := x509.CreateCertificate(rand.Reader, tpl, parent, pub, priv) + if err != nil { + t.Fatal(err) + } + x, _ := x509.ParseCertificate(der) + return der, x + } + topKey, rootKey, intKey, leafKey := key(), key(), key(), key() + var c crossChain + topTpl := ca("magpie test AAA root", 1) + var top *x509.Certificate + c.top, top = mk(topTpl, topTpl, &topKey.PublicKey, topKey) + rootTpl := ca("magpie test USERTrust root", 2) + var root *x509.Certificate + c.root, root = mk(rootTpl, rootTpl, &rootKey.PublicKey, rootKey) + c.cross, _ = mk(ca("magpie test USERTrust root", 2), top, &rootKey.PublicKey, topKey) + intTpl := ca("magpie test DV server CA", 3) + var in *x509.Certificate + c.int, in = mk(intTpl, root, &intKey.PublicKey, rootKey) + serial++ + c.leaf, _ = mk(&x509.Certificate{ + SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: "127.0.0.1"}, + IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}, DNSNames: []string{"localhost"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + }, in, &leafKey.PublicKey, intKey) + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "through") })) + srv.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{c.leaf, c.int}, PrivateKey: leafKey}}} + srv.StartTLS() + t.Cleanup(srv.Close) + c.url = srv.URL + return c +} + +// The roots magpie hands Bun go self-signed first, and a certificate whose +// issuer isn't among them is left out (rootsFirst). +func TestRootsFirstPutsTheSelfSignedCopyAhead(t *testing.T) { + c := newCrossChain(t) + name := map[string]string{string(c.top): "top", string(c.root): "root", string(c.cross): "cross", string(c.int): "int"} + names := func(certs [][]byte) string { + var s []string + for _, d := range certs { + s = append(s, name[string(d)]) + } + return strings.Join(s, " ") + } + for _, tc := range []struct { + in [][]byte + want string + }{ + {[][]byte{c.cross, c.root}, "root"}, + {[][]byte{c.cross, c.top}, "top cross"}, + {[][]byte{c.cross, c.root, c.top}, "root top cross"}, + {[][]byte{c.cross}, ""}, + {[][]byte{c.int, c.cross, c.top}, "top cross int"}, + {[][]byte{c.int}, ""}, + {[][]byte{c.root, []byte("not a certificate")}, "root "}, + } { + if got := names(rootsFirst(tc.in)); got != tc.want { + t.Errorf("rootsFirst(%s) = %q, want %q", names(tc.in), got, tc.want) + } + } +} + +// youyo.p_10001 (Discord, Windows): every request the MiniMax plugin made +// to agent.minimaxi.com failed "unable to get issuer certificate", while +// the same chain verified outside the plugin host. USERTrust RSA's copy +// cross-signed by AAA Certificate Services was in the user's ROOT store, +// so in the file magpie gives Bun, and Bun took it over the self-signed +// one and found no AAA. Here the ROOT store holds the cross-signed copy +// ahead of the self-signed one; Bun gets through, as it does with the +// copy's issuer beside it, and still refuses with neither. +func TestBunGetsPastACrossSignedRootCopy(t *testing.T) { + bun := testenv.Bun(t) + sandbox(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", + "NODE_EXTRA_CA_CERTS", "NODE_USE_SYSTEM_CA", "NODE_TLS_REJECT_UNAUTHORIZED", "SSL_CERT_FILE", "SSL_CERT_DIR"} { + t.Setenv(k, "") + } + t.Setenv("NO_PROXY", "127.0.0.1,localhost") + c := newCrossChain(t) + old := systemCAFile + t.Cleanup(func() { systemCAFile = old }) + fetch := `try { const r = await fetch(` + strconv.Quote(c.url) + `); console.log(await r.text()) } catch (e) { console.log("refused", e?.code) }` + try := func(t *testing.T, store [][]byte, want bool) { + t.Helper() + systemCAFile = func() string { return rootsFile(store) } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(`{"name":"p","private":true}`), 0o644); err != nil { + t.Fatal(err) + } + out, err := bunCommand(ctx, bun, dir, "-e", fetch).CombinedOutput() + if got := err == nil && strings.Contains(string(out), "through"); got != want { + t.Errorf("Bun's fetch got through: %v, want %v (%v)\n%s", got, want, err, out) + } + } + t.Run("the cross-signed copy first", func(t *testing.T) { try(t, [][]byte{c.cross, c.root}, true) }) + t.Run("with its issuer", func(t *testing.T) { try(t, [][]byte{c.cross, c.top}, true) }) + t.Run("the self-signed one alone", func(t *testing.T) { try(t, [][]byte{c.root}, true) }) + t.Run("only the cross-signed copy", func(t *testing.T) { try(t, [][]byte{c.cross}, false) }) + t.Run("neither", func(t *testing.T) { try(t, [][]byte{c.top}, false) }) +} + +// A plugin's request whose server's chain Bun refuses says so, with the +// code and the host, after Bun's own words: "unable to get issuer +// certificate" alone read like the vendor's fault (youyo.p_10001). +func TestPluginTLSRefusalSaysWhose(t *testing.T) { + testenv.Bun(t) + sandbox(t) + for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", + "NODE_EXTRA_CA_CERTS", "NODE_USE_SYSTEM_CA", "SSL_CERT_FILE", "SSL_CERT_DIR"} { + t.Setenv(k, "") + } + t.Setenv("NO_PROXY", "127.0.0.1,localhost") + c := newCrossChain(t) + old := systemCAFile + t.Cleanup(func() { systemCAFile = old }) + // the cross-signed copy alone: Bun's words are the reporter's + systemCAFile = func() string { return writeCAFile(pemOf(c.cross)) } + Restart() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/fake/index.js") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + if _, err := Providers(ctx); err != nil { + t.Fatal(err) + } + if _, err := APIKey(ctx, "fakeco", 0, nil, "k1", NewAccount); err != nil { + t.Fatal(err) + } + res, err := Fetch(ctx, FetchRequest{Provider: "fakeco", Model: "fake-1", NPM: "@ai-sdk/openai-compatible", + URL: c.url + "/v1/chat/completions", Method: "POST", Body: []byte(`{}`)}) + if err == nil { + res.Body.Close() + t.Fatalf("got %d, want the chain refused", res.StatusCode) + } + if !strings.Contains(err.Error(), "unable to get issuer certificate (UNABLE_TO_GET_ISSUER_CERT: the plugin host's TLS didn't verify 127.0.0.1's certificate chain against the roots it trusts)") { + t.Errorf("err = %v, want Bun's words, then the code and whose chain", err) + } +} + +func pemOf(ders ...[]byte) []byte { + var b []byte + for _, d := range ders { + b = append(b, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: d})...) + } + return b +}