Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
pii: the masking model downloads through magpie's proxy, and from hf-mirror when huggingface.co fails (hh0592821 on Discord)
yetone3a89dd53c06e
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex 6a5b61da7..fa0f40690 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -133,7 +133,7 @@ recorded as a prediction failure (`noPrediction`).1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, or 32 hex digits or more) goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), a bare `key`, a serial number, or what the model takes a UUID for (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then, so a value a rule first finds later in a conversation doesn't change the prompt the vendor has cached and rewrite all of it to the cache, `sentKnownSpans`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so (a date over a year ago: one in the last year or ahead is the day an agent runs on, `dateOK`), MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `[email protected]`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`[email protected]`, `[email protected]`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). `[email protected]` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.- - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is the user's pick (`settings.RedactModelName`, `pii.Choose`; the app's menu beside the switch, `pmPick`): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by [`internal/pii/guard`](../../internal/pii/guard) (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, `guardLabels`), loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick, a user who had Privacy Filter on or downloaded keeps it and everyone else gets AstrLink Guard (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (`backend`). Privacy Filter is a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; `pf-serve-vulkan` runs its MoE in 2048-token chunks, `PF_MOE_CHUNK`, 1.77× faster than its default 4096 on an RX 470/580-class GPU and a little slower on Metal, so Vulkan's alone, and a value the user set is kept, `moeChunk`): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-<model>.bin` beside the model: hashes, offsets and labels, never text; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, so a short request goes before the rest of a long one. The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). A model that is on and can't answer (not on disk, didn't start, hung, held back) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).+ - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is the user's pick (`settings.RedactModelName`, `pii.Choose`; the app's menu beside the switch, `pmPick`): AstrLink Guard (QuantumNous/astrlink-guard at a pinned revision, Apache-2.0, a 39 MB int8 Multilingual-MiniLM token classifier for Chinese and English), run in magpie's own process on the CPU by [`internal/pii/guard`](../../internal/pii/guard) (an ONNX reader, the XLM-R tokenizer and int8 kernels in Go, NEON/SDOT on arm64 and SSE2 on amd64; its labels named as Privacy Filter's, `guardLabels`), loaded on the first request and let go after 10 minutes with none; or OpenAI's Privacy Filter. With no pick, a user who had Privacy Filter on or downloaded keeps it and everyone else gets AstrLink Guard (#3578): on 234 segments of real code and config it found 2 spans where Privacy Filter found 100 (38 of them go.sum hashes after redact's own checks), and with the rules it found 42 of 42 test values to Privacy Filter's 41. Each model has its own download, cache file and turn (`backend`). Privacy Filter is a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; `pf-serve-vulkan` runs its MoE in 2048-token chunks, `PF_MOE_CHUNK`, 1.77× faster than its default 4096 on an RX 470/580-class GPU and a little slower on Metal, so Vulkan's alone, and a value the user set is kept, `moeChunk`): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, through magpie's proxy (`netproxy.Func`, as its other requests; hh0592821 on Discord, whose download went direct before), from hf-mirror first in China (`source.chinaFirst`) and from hf-mirror after Hugging Face everywhere else, the switch off too (`source.modelMirror`), so a poisoned or blocked huggingface.co doesn't stop it; hf-mirror serves AstrLink Guard's files itself and sends Privacy Filter's back to Hugging Face) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-<model>.bin` beside the model: hashes, offsets and labels, never text; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, so a short request goes before the rest of a long one. The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). A model that is on and can't answer (not on disk, didn't start, hung, held back) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request.- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.diff --git a/internal/pii/fetch.go b/internal/pii/fetch.goindex 4f81e874b..68916e78d 100644--- a/internal/pii/fetch.go+++ b/internal/pii/fetch.go@@ -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.Funct.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.diff --git a/internal/pii/mirror_test.go b/internal/pii/mirror_test.gonew file mode 100644index 000000000..c753876fe--- /dev/null+++ b/internal/pii/mirror_test.go@@ -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)+ }+}diff --git a/internal/source/china_test.go b/internal/source/china_test.goindex 734c31281..8cb550ecc 100644--- a/internal/source/china_test.go+++ b/internal/source/china_test.go@@ -1,9 +1,11 @@package sourceimport (+ "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)+}diff --git a/internal/source/source.go b/internal/source/source.goindex 73ed64ffe..3e2123fae 100644--- a/internal/source/source.go+++ b/internal/source/source.go@@ -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())...)