pii: the masking model downloads through magpie's proxy, and from hf-mirror when huggingface.co fails (hh0592821 on Discord)
hh0592821 (China) couldn't download the local masking model: "EOF",
"x509: certificate is valid for *.facebook.com ... not huggingface.co",
"net/http: TLS handshake timeout", while the same file came through
their proxy outside magpie.
Cause: internal/pii's download client cloned http.DefaultTransport when
the package loaded, before netproxy.Install set its Proxy, so it kept
only ProxyFromEnvironment. An app started from the Dock has no
HTTPS_PROXY, so the proxy set in magpie and the system's were both
skipped, and the request went direct to a poisoned huggingface.co. Every
other client magpie builds (update, mcp_check, mcpauth, gateway/mcp)
sets t.Proxy = netproxy.Func; pii was the only one built at init without
it. And hf-mirror was asked only with the 「国内镜像」 switch on.
Fix:
- pii's client: t.Proxy = netproxy.Func, through netproxy.Dispatch,
ResponseHeaderTimeout kept.
- source.URLs: a masking model's file (the two pinned repos' /resolve/
paths, https, no query; modelMirror) has hf-mirror after
huggingface.co with the switch off and no MAGPIE_MIRRORS; with the
switch on it stays first, once. fetch still checks each file against
its pinned sha256, so a mirror can't hand over anything else.
- docs/subsystems/gateway-routing.md says both.
Checked against the real mirror (curl, outside the tests): hf-mirror.com
serves AstrLink Guard's three files at 7216b6a3 with their pinned sizes
and sha256 (model_int8.onnx 330781 0a070d31..., model_int8.onnx_data
37124608 0ba34216..., tokenizer.json 1502881 0cf3b235...). For Privacy
Filter's gguf it answers 308 back to huggingface.co, so the mirror
helps AstrLink Guard (the default) only.
Tests, none reaching the network: TestFetchGoesThroughMagpiesProxy (proxy
set in Settings is an httptest server; a fetch of a TEST-NET-1 URL is
answered by it), TestModelFromTheMirrorWhenHuggingFaceFails (huggingface.co
failing with the reporter's certificate error, a handshake timeout and
EOF: the file comes from hf-mirror; a mirror file that isn't the pinned
one fails the checksum), TestModelMirrorWithoutTheSwitch,
TestModelFallsToTheMirror (source).
Broken by hand, each red then restored: without t.Proxy =
netproxy.Func, TestFetchGoesThroughMagpiesProxy is red (context deadline,
direct dial); with modelMirror out of URLs, the three mirror tests are
red.
Run: the full suite (go test -tags nogui -timeout 45m ./..., sandbox
HOME) at 7065e3734, this change on the zoecats commit on 11dcc743f,
while the disk was full (1 GB free, other sessions' runs and a 57 GB
shared Go cache): internal/pii 134s, internal/source and 69 more
packages ok; agent, gateway and library red only on "no space left on
device" (TempDir and file writes); provider on the synctest crash open
as #3632. Rerun at that head: internal/pii, internal/source and
internal/netproxy ok, and the gateway's 429/patience tests ok.
The previous commit's full run at its base had every package ok but
provider (#3632).
gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./... clean; go build for darwin, linux (nogui) and
windows ok.
Not tried: a download from China through a real poisoned DNS, or with
the reporter's proxy; ModelScope for Privacy Filter's gguf.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -16,6 +16,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/source"
|
||||
)
|
||||
|
||||
@@ -33,11 +34,17 @@ var dl dlState
|
||||
|
||||
// client has no timeout: the model takes minutes on a slow line. A
|
||||
// download that stops getting bytes is ended by stall instead, and one
|
||||
// whose server doesn't answer by the header timeout.
|
||||
// whose server doesn't answer by the header timeout. It goes through
|
||||
// magpie's proxy (netproxy.Func: the one set in magpie, else the
|
||||
// system's), like every other request magpie makes: cloned from
|
||||
// http.DefaultTransport when this package loads, before netproxy.Install
|
||||
// set its Proxy, it went direct, and in China huggingface.co answered with
|
||||
// a *.facebook.com certificate (hh0592821 on Discord).
|
||||
var client = func() *http.Client {
|
||||
t := http.DefaultTransport.(*http.Transport).Clone()
|
||||
t.Proxy = netproxy.Func
|
||||
t.ResponseHeaderTimeout = 60 * time.Second
|
||||
return &http.Client{Transport: t}
|
||||
return &http.Client{Transport: netproxy.Dispatch(t)}
|
||||
}()
|
||||
|
||||
// stallAfter is how long a download waits for its next byte.
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package pii
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The model is downloaded through the proxy set in magpie, as magpie's
|
||||
// other requests are (hh0592821 on Discord: a client made before
|
||||
// netproxy.Install went direct, and in China huggingface.co answered with
|
||||
// a *.facebook.com certificate while their proxy got the file).
|
||||
func TestFetchGoesThroughMagpiesProxy(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
body := bytes.Repeat([]byte("model bytes "), 1000)
|
||||
var mu sync.Mutex
|
||||
var seen []string
|
||||
// the proxy: a plain http:// request comes to it whole, by its URL
|
||||
px := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
seen = append(seen, r.URL.String())
|
||||
mu.Unlock()
|
||||
w.Write(body)
|
||||
}))
|
||||
defer px.Close()
|
||||
if err := settings.Save(settings.Settings{Proxy: px.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// TEST-NET-1: nothing answers there but the proxy, and no name is
|
||||
// looked up for it
|
||||
raw := "http://192.0.2.1/QuantumNous/astrlink-guard/resolve/r/int8/tokenizer.json"
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
path := filepath.Join(t.TempDir(), "tokenizer.json")
|
||||
var n atomic.Int64
|
||||
if err := fetch(ctx, raw, path, int64(len(body)), sum(body), &n); err != nil {
|
||||
t.Fatalf("fetch: %v", err)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if !slices.Equal(seen, []string{raw}) {
|
||||
t.Fatalf("through the proxy: %v, want %s", seen, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// hosts answers each request by its host, as the world would: one host's
|
||||
// answer an error, another's the file.
|
||||
type hosts map[string]func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (h hosts) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
if f, ok := h[r.URL.Host]; ok {
|
||||
return f(r)
|
||||
}
|
||||
return nil, errors.New("no such host " + r.URL.Host)
|
||||
}
|
||||
|
||||
func serving(b []byte) func(*http.Request) (*http.Response, error) {
|
||||
return func(r *http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 200, Status: "200 OK", Header: http.Header{}, Body: io.NopCloser(bytes.NewReader(b)), ContentLength: int64(len(b)), Request: r}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Where huggingface.co can't be reached (hh0592821's poisoned answer, a
|
||||
// handshake that times out, EOF), the masking model comes from hf-mirror,
|
||||
// with the 「国内镜像」 switch off; and what hf-mirror serves is checked
|
||||
// against the pin all the same.
|
||||
func TestModelFromTheMirrorWhenHuggingFaceFails(t *testing.T) {
|
||||
body := bytes.Repeat([]byte("guard bytes "), 1000)
|
||||
was := client
|
||||
t.Cleanup(func() { client = was })
|
||||
raw := guardBase + guardRev + "/int8/tokenizer.json"
|
||||
for _, fail := range []error{
|
||||
errors.New("tls: failed to verify certificate: x509: certificate is valid for *.facebook.com, facebook.com, not huggingface.co"),
|
||||
errors.New("net/http: TLS handshake timeout"),
|
||||
io.EOF,
|
||||
} {
|
||||
var asked []string
|
||||
var mu sync.Mutex
|
||||
note := func(f func(*http.Request) (*http.Response, error)) func(*http.Request) (*http.Response, error) {
|
||||
return func(r *http.Request) (*http.Response, error) {
|
||||
mu.Lock()
|
||||
asked = append(asked, r.URL.String())
|
||||
mu.Unlock()
|
||||
return f(r)
|
||||
}
|
||||
}
|
||||
client = &http.Client{Transport: hosts{
|
||||
"huggingface.co": note(func(*http.Request) (*http.Response, error) { return nil, fail }),
|
||||
"hf-mirror.com": note(serving(body)),
|
||||
}}
|
||||
path := filepath.Join(t.TempDir(), "tokenizer.json")
|
||||
var n atomic.Int64
|
||||
if err := fetch(context.Background(), raw, path, int64(len(body)), sum(body), &n); err != nil {
|
||||
t.Fatalf("%v: %v", fail, err)
|
||||
}
|
||||
want := []string{raw, strings.Replace(raw, "https://huggingface.co", "https://hf-mirror.com", 1)}
|
||||
if !slices.Equal(asked, want) {
|
||||
t.Fatalf("%v: asked %v, want %v", fail, asked, want)
|
||||
}
|
||||
}
|
||||
|
||||
// a mirror's file that isn't the pinned one is not kept
|
||||
client = &http.Client{Transport: hosts{
|
||||
"huggingface.co": func(*http.Request) (*http.Response, error) { return nil, io.EOF },
|
||||
"hf-mirror.com": serving(bytes.Repeat([]byte("other bytes "), 1000)),
|
||||
}}
|
||||
path := filepath.Join(t.TempDir(), "tokenizer.json")
|
||||
var n atomic.Int64
|
||||
err := fetch(context.Background(), raw, path, int64(len(body)), sum(body), &n)
|
||||
if err == nil || !strings.Contains(err.Error(), "checksum") {
|
||||
t.Fatalf("a mirror's wrong file: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
package source
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -182,3 +184,72 @@ func TestDoFaithful(t *testing.T) {
|
||||
type roundTrip func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
// The masking models' files, pinned by sha256, have hf-mirror after
|
||||
// Hugging Face with the switch off and no MAGPIE_MIRRORS (hh0592821 on
|
||||
// Discord: huggingface.co poisoned in China); before it with the switch
|
||||
// on, once. Nothing else of Hugging Face's has.
|
||||
func TestModelMirrorWithoutTheSwitch(t *testing.T) {
|
||||
t.Setenv("MAGPIE_MIRRORS", "")
|
||||
raw := "https://huggingface.co/QuantumNous/astrlink-guard/resolve/7216b6a/int8/tokenizer.json"
|
||||
mirror := "https://hf-mirror.com/QuantumNous/astrlink-guard/resolve/7216b6a/int8/tokenizer.json"
|
||||
if got := strings.Join(URLs(raw), " "); got != raw+" "+mirror {
|
||||
t.Fatalf("switch off: URLs = %q", got)
|
||||
}
|
||||
for _, other := range []string{
|
||||
"https://huggingface.co/someone/else/resolve/main/x.gguf",
|
||||
"https://huggingface.co/QuantumNous/astrlink-guard/resolve/7216b6a/x?dl=1",
|
||||
"http://huggingface.co/QuantumNous/astrlink-guard/resolve/7216b6a/x",
|
||||
} {
|
||||
if got := URLs(other); len(got) != 1 {
|
||||
t.Errorf("URLs(%s) = %q", other, got)
|
||||
}
|
||||
}
|
||||
chinaOn(t)
|
||||
if got := strings.Join(URLs(raw), " "); got != mirror+" "+raw {
|
||||
t.Fatalf("switch on: URLs = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Hugging Face's address failing as it does where it is poisoned, the
|
||||
// file is asked of hf-mirror.
|
||||
func TestModelFallsToTheMirror(t *testing.T) {
|
||||
t.Setenv("MAGPIE_MIRRORS", "")
|
||||
var asked atomic.Int32
|
||||
mirror := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked.Add(1)
|
||||
io.WriteString(w, "model")
|
||||
}))
|
||||
defer mirror.Close()
|
||||
c := mirror.Client()
|
||||
c.Transport = rewrite{base: c.Transport, to: mirror.URL}
|
||||
req, _ := http.NewRequest(http.MethodGet, "https://huggingface.co/QuantumNous/astrlink-guard/resolve/7216b6a/int8/tokenizer.json", nil)
|
||||
resp, err := Do(c, req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if b, _ := io.ReadAll(resp.Body); string(b) != "model" || asked.Load() != 1 {
|
||||
t.Fatalf("got %q, mirror asked %d", b, asked.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// rewrite fails huggingface.co with the certificate hh0592821 saw, and
|
||||
// sends hf-mirror.com's requests to to.
|
||||
type rewrite struct {
|
||||
base http.RoundTripper
|
||||
to string
|
||||
}
|
||||
|
||||
func (rw rewrite) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
switch r.URL.Host {
|
||||
case "huggingface.co":
|
||||
return nil, errors.New("tls: failed to verify certificate: x509: certificate is valid for *.facebook.com, facebook.com, not huggingface.co")
|
||||
case "hf-mirror.com":
|
||||
u, _ := url.Parse(rw.to + r.URL.Path)
|
||||
r = r.Clone(r.Context())
|
||||
r.URL, r.Host = u, ""
|
||||
return rw.base.RoundTrip(r)
|
||||
}
|
||||
return nil, errors.New("no such host " + r.URL.Host)
|
||||
}
|
||||
|
||||
+30
-12
@@ -55,14 +55,7 @@ func chinaFirst(raw string) string {
|
||||
return bunMirror + "/" + rest
|
||||
}
|
||||
case "huggingface.co":
|
||||
// the local masking models (internal/pii), at the revision their
|
||||
// sha256 were pinned at: hf-mirror serves Hugging Face's files,
|
||||
// and what it serves is checked against those pins
|
||||
for _, repo := range []string{"/LocalAI-io/privacy-filter-GGUF/resolve/", "/QuantumNous/astrlink-guard/resolve/"} {
|
||||
if strings.HasPrefix(u.EscapedPath(), repo) && u.RawQuery == "" {
|
||||
return hfMirror + u.EscapedPath()
|
||||
}
|
||||
}
|
||||
return modelMirror(u)
|
||||
case "raw.githubusercontent.com":
|
||||
// /magpie-community/plugins/<branch>/<path>
|
||||
if rest, ok := strings.CutPrefix(u.EscapedPath(), "/magpie-community/plugins/"); ok {
|
||||
@@ -74,6 +67,25 @@ func chinaFirst(raw string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// modelMirror is hf-mirror's copy of one of the local masking models'
|
||||
// files (internal/pii), "" for anything else of Hugging Face's. Those
|
||||
// files are fetched at the revision their sha256 were pinned at, and what
|
||||
// hf-mirror serves is checked against those pins, so it is asked with the
|
||||
// switch off too, after Hugging Face: where huggingface.co is blocked or
|
||||
// poisoned (a *.facebook.com certificate, EOF, a handshake that times out;
|
||||
// hh0592821 on Discord) the model still comes.
|
||||
func modelMirror(u *url.URL) string {
|
||||
if u.Scheme != "https" || !strings.EqualFold(u.Hostname(), "huggingface.co") || u.RawQuery != "" {
|
||||
return ""
|
||||
}
|
||||
for _, repo := range []string{"/LocalAI-io/privacy-filter-GGUF/resolve/", "/QuantumNous/astrlink-guard/resolve/"} {
|
||||
if strings.HasPrefix(u.EscapedPath(), repo) {
|
||||
return hfMirror + u.EscapedPath()
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Enabled reports whether mirror fallback was turned on with
|
||||
// MAGPIE_MIRRORS=on (or true, 1, cn).
|
||||
func Enabled() bool {
|
||||
@@ -100,16 +112,22 @@ func githubBase() string {
|
||||
|
||||
// URLs is the official address followed by its mirrors, or just the
|
||||
// official one when there is no mirror for it; with the 「国内镜像」 switch
|
||||
// on, a mirror in China comes before it.
|
||||
// on, a mirror in China comes before it. A masking model's file has
|
||||
// hf-mirror after it with no switch at all (modelMirror); every other
|
||||
// fallback mirror waits for MAGPIE_MIRRORS.
|
||||
func URLs(raw string) []string {
|
||||
out := faithful(raw)
|
||||
if !Enabled() {
|
||||
return out
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
if m := modelMirror(u); m != "" {
|
||||
// pinned by sha256: no switch needed (modelMirror)
|
||||
return distinct(append(out, m)...)
|
||||
}
|
||||
if !Enabled() {
|
||||
return out
|
||||
}
|
||||
switch strings.ToLower(u.Hostname()) {
|
||||
case "registry.npmjs.org":
|
||||
return distinct(append(out, npmBase()+u.RequestURI())...)
|
||||
|
||||
Reference in New Issue
Block a user