Files
magpie/internal/gateway/mask_actions_test.go
T
yetone b00c82acfa masking: each kind is masked, sent with a warning or held back; a Never mask list and Try it (#1977)
Settings › Privacy gets two sections under What to mask:

- When a value is found: Mask, Warn or Block per kind (redactActions;
  a kind left out is masked). Warn sends the value as written and records
  it with a placeholder nobody remembers, not counted as masked. Block
  masks it as before and the gateway answers 400 naming the kind and the
  value's hint, never the value, with nothing sent (maskBlocked); the
  record is kept as Blocked. The secret kinds come first, the personal
  ones behind Show all kinds. A Never mask list (redactAllow) lets a whole
  value go as written in any case; a longer value it is part of is masked.
- Try it: POST /api/masking/preview masks a text as a request would
  (redact.Preview) and remembers nothing: no placeholder stands for it
  afterwards and its values aren't masked later as seen before. The page
  shows the vendor's text, what was found and what would be done, and
  keeps the text in no storage.

The masking card counts requests held back and values sent as written; a
call whose values only went as written gets an amber badge on Recent calls
and the Routing log. zh, zh-TW, ja and de throughout. Docs: gateway-routing
and gui-shell.

Broken by hand: the new GUI badge assertion fails on the old maskedBadge
(no .warn badge drawn); TestSettingsSaveKeepsWhatItDoesNotSend went red
until the two settings were in its fixture; "{n} held back" turned
i18n-keys red against the routing plugin's "{n} held" and was renamed.

Run at this tree (base origin/main 9b0f48612):
- gofmt clean; go vet on macOS, GOOS=linux -tags nogui, GOOS=windows.
- go test -count=1 -timeout 45m redact, maskrec, settings, gwmw, gui,
  gateway: ok.
- GUI, both engines: every Privacy file, mask-actions, masking-records,
  routing-bodies, i18n-keys, old-webkit: 263/263.
- Whole GUI suite earlier at 083b1c8e7's base, beside 7 other runs:
  53 red; alone, the ones left red fail the same on origin/main
  6fc532198 and are filed (#3179, #2228, #2448, #2276, #2549, #2163,
  #2399), except privacy-usage-stats and account-discovery, which this
  change's taller page moved off screen; both fixed here.

Not tried: a real vendor request held back by Block from a real agent.
2026-10-22 04:07:55 +08:00

99 lines
4.1 KiB
Go

package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/yetone/magpie/internal/maskrec"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// A request with a value of a kind the user set to block goes nowhere,
// on each protocol: 400, a message that names the kind and the value's
// hint but never the value, and a record of it held back (#1977).
func TestBlockedKindHoldsTheRequestBack(t *testing.T) {
const key = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
var hit atomic.Int32
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hit.Add(1)
w.WriteHeader(500)
}))
defer up.Close()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1", "embed-1"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := settings.Save(settings.Settings{Redact: true, RedactActions: map[string]string{"API_KEY": "block"}}); err != nil {
t.Fatal(err)
}
s := New()
for _, tc := range []struct{ path, body string }{
{"/v1/chat/completions", `{"model":"fake/m1","messages":[{"role":"user","content":"key ` + key + `"}]}`},
{"/v1/messages", `{"model":"fake/m1","max_tokens":10,"messages":[{"role":"user","content":"key ` + key + `"}]}`},
{"/v1/responses", `{"model":"fake/m1","input":"key ` + key + `"}`},
{"/v1/embeddings", `{"model":"fake/embed-1","input":"key ` + key + `"}`},
} {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", tc.path, strings.NewReader(tc.body)))
raw := rec.Body.String()
if rec.Code != 400 || strings.Contains(raw, key[3:]) || !strings.Contains(raw, "API_KEY") || !strings.Contains(raw, "sk-") {
t.Fatalf("%s: %d %s", tc.path, rec.Code, raw)
}
rs, _ := maskrec.List(0, 1, maskrec.Filter{})
if len(rs) != 1 || !rs[0].Blocked || len(rs[0].Values) != 1 || rs[0].Values[0].Action != "block" {
t.Fatalf("%s: recorded %+v", tc.path, rs)
}
}
if n := hit.Load(); n != 0 {
t.Fatalf("the vendor was sent %d requests", n)
}
}
// A kind the user set to warn of goes to the vendor as written, and the
// record tells it, with no snip of it; the rest is masked.
func TestWarnedKindGoesAsWritten(t *testing.T) {
const key, mail = "sk-proj-abcdEFGH1234ijklMNOP5678qrst", "ops.lead@kelvarn.io"
var got []byte
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":3,"completion_tokens":1}}`)
}))
defer up.Close()
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RedactActions: map[string]string{"EMAIL": "warn"}}); err != nil {
t.Fatal(err)
}
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","messages":[{"role":"user","content":"mail `+mail+` key `+key+`"}]}`)))
if rec.Code != 200 || !strings.Contains(string(got), mail) || strings.Contains(string(got), key) {
t.Fatalf("%d, sent %s", rec.Code, got)
}
rs, _ := maskrec.List(0, 1, maskrec.Filter{})
if len(rs) != 1 || rs[0].N != 1 || len(rs[0].Values) != 2 {
t.Fatalf("recorded %+v", rs)
}
for _, v := range rs[0].Values {
if v.Kind == "EMAIL" && (v.Action != "warn" || rs[0].Snips[v.Placeholder] != "") {
t.Fatalf("warned value %+v, snip %q", v, rs[0].Snips[v.Placeholder])
}
}
ts := s.Trace(t.Context(), 0, 0)
for _, rt := range ts.Routes {
if rt.ID == rs[0].Route && (rt.Masked == nil || rt.Masked.Warned != 1 || rt.Masked.Distinct != 1) {
t.Fatalf("route's masked: %+v", rt.Masked)
}
}
}