diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index d4666cac5..84f98d412 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -888,6 +888,27 @@ that honours no service tier is sent none, and Anthropic-protocol requests `TestKeyTieredChat`, `TestKeyServiceTier` in `internal/access`, `TestGatewayKeyTierCLI`, `gateway-key-tier.test.cjs`. +A key's `Redact` (y0ngb1n on X; `access.Key`, set by the `redact-key` action, +the key row's masking badge or `magpie gateway-key redact +follow|on|off`; stored as "", "on" or "off") decides whether Settings › +Privacy's masking applies to its requests. Unset follows the settings, as a +request with no key (this computer's own) always does. Off sends the key's +requests as written, for a device the user trusts; on masks them where the +settings mask nothing too, with the default rules for secrets and personal +data (`masking.WithForced`). Every place that masks what goes to a vendor +asks `maskingFor` (`redactedHits`, `maskTextHits`, so chat, count_tokens, +searches, drawing, video, speech and embeddings alike), and a native call +asks `redactionWantedFor`; a masker that doesn't read the request's context +can't be held to a forced pass, so that is an error, not a request sent as +it is. A request with the key's own setting is never reported to a Remote +magpie as masked (`ownMaskedAs`), whichever way it was set, so the remote +masks by its own settings. An issued key keeps its own setting, and its +issuer's `on` holds for it (`Identity.Redact`). Records of requests kept +locally (`maskedCopy`) stay masked by the settings. `InUse` of the redact +plugin counts a key set on. Tests: `TestKeyRedactSetting`, +`TestKeyRedactEveryRoute`, `TestKeyRedact` in `internal/access`, +`TestGatewayKeyRedactCLI`, `gateway-key-redact.test.cjs`. + `GET /me` is the key page: a gateway key's holder opens it in a browser at the address they reach the gateway at, types their key, and sees that key's own name, limits, usage (today, 7 and 30 days, its most used models) and diff --git a/internal/access/access.go b/internal/access/access.go index 70fb2343d..e64d76a6e 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -197,6 +197,32 @@ type Key struct { // X): settings.CodexTierStandard for none, "priority" (Codex's Fast) // or "ultrafast"; "" follows the request. ServiceTier string `json:"serviceTier,omitempty"` + // Redact is whether Settings › Privacy's masking applies to the key's + // requests (y0ngb1n on X): "" follows the setting, RedactOn masks them + // even where the setting masks nothing, RedactOff sends them as they + // are, for a device the user trusts. A request with no key (this + // computer's own) always follows the setting. + Redact string `json:"redact,omitempty"` +} + +// A key's Redact. +const ( + RedactOn = "on" + RedactOff = "off" +) + +// CleanRedact is a key's masking setting as it is kept: "" to follow +// Settings › Privacy, RedactOn or RedactOff. +func CleanRedact(v string) (string, error) { + switch strings.ToLower(strings.TrimSpace(v)) { + case "", "follow", "global", "default", "auto": + return "", nil + case "on", "true", "yes", "mask": + return RedactOn, nil + case "off", "false", "no", "none": + return RedactOff, nil + } + return "", fmt.Errorf("Masking: one of follow, on or off, not %q", v) } // CleanTier is a key's service tier as it is kept: "" to follow the @@ -262,6 +288,8 @@ type Identity struct { MaxConcurrency int // ServiceTier is Key.ServiceTier. ServiceTier string + // Redact is Key.Redact; an issued key is held on by its issuer's on. + Redact string // Default: the key is the sharing key magpie made itself (Default), // the one it writes into this computer's own agents that reach the // gateway from beyond loopback, never one the user made for someone @@ -474,6 +502,8 @@ type Change struct { // ServiceTier is what "tier-key" sets (Key.ServiceTier), "" to follow // the request. ServiceTier string `json:"serviceTier,omitempty"` + // Redact is what "redact-key" sets (Key.Redact): "", "on" or "off". + Redact string `json:"redact,omitempty"` // Secret is the value "add-key" gives the new key, one its clients // already send (love1sbug on X: keys handed out from another gateway), // or "rotate-key" gives the key; "" for one magpie makes. @@ -656,6 +686,12 @@ func Update(action string, in Change) (string, error) { return "", err } keys[i].ServiceTier = tier + case "redact-key": + mode, err := CleanRedact(in.Redact) + if err != nil { + return "", err + } + keys[i].Redact = mode case "issuer-key": // may issue short-lived keys under itself (POST /v1/magpie/keys) if in.Issues && keys[i].Browser { @@ -701,7 +737,7 @@ func Update(action string, in Change) (string, error) { default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { mirror = &keys[i] } } diff --git a/internal/access/concurrency_test.go b/internal/access/concurrency_test.go index 5c4552d6f..c54fda1e7 100644 --- a/internal/access/concurrency_test.go +++ b/internal/access/concurrency_test.go @@ -79,3 +79,53 @@ func TestKeyConcurrency(t *testing.T) { t.Fatal("the sharing key:", who.MaxConcurrency, who.Default) } } + +// y0ngb1n on X: a key's masking setting is "", on or off; redact-key sets +// it, Authenticate tells it, a word it doesn't know is refused and leaves +// it as it was, and an issued key is held on by its issuer's on. +func TestKeyRedact(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + clockAt(t, time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)) + id, secret := addKey(t, "Team") + if who, _ := Authenticate(secret); who.Redact != "" { + t.Fatal("a new key has a setting:", who.Redact) + } + for in, want := range map[string]string{"off": RedactOff, "ON": RedactOn, "follow": "", "off ": RedactOff} { + if _, err := Update("redact-key", Change{Key: id, Redact: in}); err != nil { + t.Fatal(in, err) + } + if who, ok := Authenticate(secret); !ok || who.Redact != want { + t.Fatalf("set %q: %q %v", in, who.Redact, ok) + } + } + if _, err := Update("redact-key", Change{Key: id, Redact: "off"}); err != nil { + t.Fatal(err) + } + if _, err := Update("redact-key", Change{Key: id, Redact: "sometimes"}); err == nil { + t.Fatal("accepted sometimes") + } + if keys, _ := List(); keys[0].Redact != RedactOff { + t.Fatal("a refused word changed it:", keys[0].Redact) + } + + // issued: its own off is told, but its issuer's on holds + if _, err := Update("issuer-key", Change{Key: id, Issues: true}); err != nil { + t.Fatal(err) + } + child, err := IssueKey(Issue{TTL: time.Hour, Issuer: id}) + if err != nil { + t.Fatal(err) + } + if _, err := Update("redact-key", Change{Key: child.ID, Redact: "off"}); err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(child.Key); who.Redact != RedactOff { + t.Fatal("issued under off:", who.Redact) + } + if _, err := Update("redact-key", Change{Key: id, Redact: "on"}); err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(child.Key); who.Redact != RedactOn { + t.Fatal("issued under on, its own off:", who.Redact) + } +} diff --git a/internal/access/issue.go b/internal/access/issue.go index e802a43de..8198de243 100644 --- a/internal/access/issue.go +++ b/internal/access/issue.go @@ -353,7 +353,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q names an account group, and magpie can't read its account groups now: %v", k.Name, err)} } k.Accounts = accounts - who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier} + who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact} // the default key as Default tells it: marked LAN, or the id the // settings name (settings read only for an unmarked key) who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID) @@ -379,6 +379,10 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { who.ReadOnly = who.ReadOnly || p.ReadOnly who.Browser = who.Browser || p.Browser who.Quotas = who.Quotas && p.Quotas + // masking an issuer holds on holds for what it issued; off is the key's own + if p.Redact == RedactOn { + who.Redact = RedactOn + } if !p.Expires.IsZero() && (who.Expires.IsZero() || p.Expires.Before(who.Expires)) { who.Expires = p.Expires } diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index 8023a71fc..139ee8226 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -58,6 +58,10 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyTier(out, args[1:]) } + if action == "redact" || action == "masking" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyRedact(out, args[1:]) + } if action == "mcp" { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyMCP(out, args[1:]) @@ -111,7 +115,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|total|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|total|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | tier [follow | standard | fast | ultrafast] | redact [follow | on | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -858,6 +862,35 @@ func gatewayKeyTier(out io.Writer, args []string) error { return err } +// gatewayKeyRedact shows or sets whether Settings › Privacy's masking +// applies to a key's requests (access.Key.Redact, y0ngb1n on X): +// +// magpie gateway-key redact its setting +// magpie gateway-key redact follow|on|off set it +func gatewayKeyRedact(out io.Writer, args []string) error { + if len(args) == 0 || len(args) > 2 { + return fmt.Errorf("usage: magpie gateway-key redact [follow | on | off]") + } + id := args[0] + if len(args) == 2 { + if _, err := access.Update("redact-key", access.Change{Key: id, Redact: args[1]}); err != nil { + return err + } + } + keys, err := access.List() + if err != nil { + return err + } + i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id }) + if i < 0 { + return fmt.Errorf("Key not found") + } + k := keys[i] + word := map[string]string{"": "follows Settings › Privacy", access.RedactOn: "on", access.RedactOff: "off"}[k.Redact] + _, err = fmt.Fprintf(out, "%s: masking %s\n", k.Name, word) + return err +} + // accessWord is a key's access as the list says it: "browser" (Magpie // Browser's, access.Key.Browser), "read-only" or "full". func accessWord(k access.Key) string { diff --git a/internal/cli/gateway_keys_cli_test.go b/internal/cli/gateway_keys_cli_test.go index aac683170..b948b7d2c 100644 --- a/internal/cli/gateway_keys_cli_test.go +++ b/internal/cli/gateway_keys_cli_test.go @@ -778,3 +778,42 @@ func TestGatewayKeyTierCLI(t *testing.T) { t.Fatalf("a refused call changed it: %q", keys[0].ServiceTier) } } + +// y0ngb1n on X: `gateway-key redact [follow|on|off]` shows or sets +// whether Settings › Privacy's masking applies to a key's requests. +func TestGatewayKeyRedactCLI(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + call := func(args ...string) (string, error) { + var out bytes.Buffer + err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)) + return out.String(), err + } + if _, err := call("add", "Team"); err != nil { + t.Fatal(err) + } + keys, _ := access.List() + id := keys[0].ID + for _, c := range [][3]string{{"", "", "follows Settings › Privacy"}, {"off", "", "off"}, {"on", "", "on"}, {"follow", "", "follows Settings › Privacy"}} { + args := []string{"redact", id} + if c[0] != "" { + args = append(args, c[0]) + } + if got, err := call(args...); err != nil || got != "Team: masking "+c[2]+"\n" { + t.Fatalf("%v: %q %v", args, got, err) + } + } + call("redact", id, "off") + for _, args := range [][]string{{"redact"}, {"redact", id, "maybe"}, {"redact", id, "--help"}, {"redact", id, "on", "x"}, {"redact", "missing", "on"}, {"redact", "missing"}} { + if _, err := call(args...); err == nil { + t.Error("accepted", args) + } + } + if keys, _ = access.List(); keys[0].Redact != "off" { + t.Fatalf("a refused call changed it: %q", keys[0].Redact) + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 64a4efdbd..3a20fd6e4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2004,7 +2004,7 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { p, model, ok = provider.Resolve(to) } else { w, body = rw, b - r = withMaskedAs(r, ownMaskedAs()) + r = withMaskedAs(r, ownMaskedAs(r.Context())) defer done() } } @@ -2715,7 +2715,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro move(to, movedPrivacy) } else { capture.ResponseWriter, body, unmask, maskedHits = rw, b, done, hits - r = withMaskedAs(r, ownMaskedAs()) + r = withMaskedAs(r, ownMaskedAs(r.Context())) } } } diff --git a/internal/gateway/key_redact_test.go b/internal/gateway/key_redact_test.go new file mode 100644 index 000000000..a37d8e1c0 --- /dev/null +++ b/internal/gateway/key_redact_test.go @@ -0,0 +1,117 @@ +package gateway + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/settings" +) + +// y0ngb1n on X: each gateway key says whether Settings › Privacy's masking +// applies to its requests. Off sends them as written, on masks them even +// where the settings mask nothing, and follow, like a request with no +// key, does what the settings say. +func TestKeyRedactSetting(t *testing.T) { + _, seen, _ := maskOnceSetup(t) // masking on, the word "acmecorp" + keys, secrets := newCaller(t, "Trusted", "External", "Plain") + for i, mode := range []string{"off", "on", "follow"} { + if _, err := access.Update("redact-key", access.Change{Key: keys[i].ID, Redact: mode}); err != nil { + t.Fatal(err) + } + } + gw := lanServer(t, New()) + send := func(secret, model string) string { + t.Helper() + body := `{"model":"` + model + `","messages":[{"role":"user","content":"a note about acmecorp"}]}` + req, _ := http.NewRequest("POST", gw.URL+"/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + if secret != "" { + req.Header.Set("Authorization", "Bearer "+secret) + } + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + if res.StatusCode != 200 { + t.Fatalf("%d %s", res.StatusCode, b) + } + got, _ := seen() + return got + } + for i, c := range []struct { + name string + masked bool + }{{"off", false}, {"on", true}, {"follow", true}} { + if got := send(secrets[i], "fake/m1"); strings.Contains(got, "acmecorp") == c.masked { + t.Errorf("key %s: the vendor was sent %s", c.name, got) + } + } + + // off through a Remote magpie: this one masks nothing and says nothing + // was masked, so the remote masks by its own settings + if got := send(secrets[0], "office/fake/m1"); strings.Contains(got, "acmecorp") { + t.Errorf("an off key's request told the remote it was masked: %s", got) + } + + // the settings mask nothing: off and follow send as written, on masks + // secrets and personal data by the defaults + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + const mail = "write to jo@quill.dev" + for i, c := range []struct { + name string + masked bool + }{{"off", false}, {"on", true}, {"follow", false}} { + body := `{"model":"fake/m1","messages":[{"role":"user","content":"` + mail + `"}]}` + req, _ := http.NewRequest("POST", gw.URL+"/v1/chat/completions", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+secrets[i]) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + io.Copy(io.Discard, res.Body) + res.Body.Close() + got, _ := seen() + if strings.Contains(got, "jo@quill.dev") == c.masked { + t.Errorf("settings off, key %s: the vendor was sent %s", c.name, got) + } + } +} + +// A key's setting holds on every route that masks what goes to a vendor, +// not only chat: a web search's query is masked through maskedQuery, and +// a native call through maskTextHits. +func TestKeyRedactEveryRoute(t *testing.T) { + fresh(t) + if err := settings.Save(settings.Settings{Redact: true, RedactWords: []string{"acmecorp"}}); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { settings.Save(settings.Settings{}) }) + scanCount(t) + for _, c := range []struct { + mode string + masked bool + }{{"", true}, {"on", true}, {"off", false}} { + ctx := access.WithIdentity(context.Background(), access.Identity{KeyID: "k", Redact: c.mode}) + q, err := maskedQuery(ctx, "news about acmecorp", nil) + if err != nil || strings.Contains(q, "acmecorp") != !c.masked { + t.Errorf("search, key %q: %q %v", c.mode, q, err) + } + if _, got, _, err := maskTextHits(ctx, "news about acmecorp"); err != nil || strings.Contains(got, "acmecorp") != !c.masked { + t.Errorf("text, key %q: %q %v", c.mode, got, err) + } + } + // no key: the settings + q, _ := maskedQuery(context.Background(), "news about acmecorp", nil) + if strings.Contains(q, "acmecorp") { + t.Errorf("a request with no key went unmasked: %q", q) + } +} diff --git a/internal/gateway/native.go b/internal/gateway/native.go index cb2cf92e9..ae82c8a53 100644 --- a/internal/gateway/native.go +++ b/internal/gateway/native.go @@ -396,7 +396,7 @@ func (s *Server) nativeAny(w http.ResponseWriter, r *http.Request, p provider.Pr fail(http.StatusForbidden, msg) return } - if redactionWanted() && !p.SkipsRedaction() { + if redactionWantedFor(r.Context()) && !p.SkipsRedaction() { var v any dec := json.NewDecoder(bytes.NewReader(body)) dec.UseNumber() // a seed or an id goes as it came diff --git a/internal/gateway/redact.go b/internal/gateway/redact.go index f9e59cd9c..0ead6b35a 100644 --- a/internal/gateway/redact.go +++ b/internal/gateway/redact.go @@ -12,6 +12,7 @@ import ( "sync" "time" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/gwmw" "github.com/yetone/magpie/internal/lazyre" "github.com/yetone/magpie/internal/masking" @@ -20,6 +21,34 @@ import ( "github.com/yetone/magpie/internal/settings" ) +// maskingFor is the masker for a request whose caller is ctx's, and the +// ctx to mask on. A key's own setting (access.Key.Redact, y0ngb1n on X) +// holds where Settings › Privacy says otherwise: off sends the key's +// requests as they are, on masks them with the settings' own rules, or the +// default ones (masking.WithForced) where the settings mask nothing. A +// request with no key follows the settings. Every place that masks what +// goes to a vendor asks here. Fail closed: a forced pass needs a masker +// that reads ctx, and one that doesn't is an error. +func maskingFor(ctx context.Context) (context.Context, gwmw.Masker, error) { + switch access.Caller(ctx).Redact { + case access.RedactOff: + return ctx, nil, nil + case access.RedactOn: + if !redactionWanted() { + m, err := gwmw.Masking(true) + if err != nil { + return ctx, nil, err + } + if _, ok := m.(gwmw.ContextTeller); !ok { + return ctx, nil, gwmw.ErrUnmasked + } + return masking.WithForced(ctx), m, nil + } + } + m, err := gwmw.Masking(redactionWanted()) + return ctx, m, err +} + // redacted masks a request's secrets, as the settings say, before it goes // to a vendor, and wraps w so what the vendor answers has them back; done // writes what the wrapper still holds. Nothing masked, nothing wrapped. It @@ -34,7 +63,7 @@ func redacted(ctx context.Context, w http.ResponseWriter, body []byte) (http.Res // (noteMasked). A masker that waits (for the local model's turn) stops // waiting when ctx ends, and the request goes nowhere. func redactedHits(ctx context.Context, w http.ResponseWriter, body []byte) (http.ResponseWriter, []byte, func(), maskHits, error) { - m, err := gwmw.Masking(redactionWanted()) + ctx, m, err := maskingFor(ctx) if m == nil { return w, body, func() {}, maskHits{}, err } @@ -125,7 +154,7 @@ func maskedText(ctx context.Context, s string) (string, int, error) { // swapped. Its wait for the local model ends with ctx, as redactedHits' // does. func maskTextHits(ctx context.Context, s string) (gwmw.Masker, string, maskHits, error) { - m, err := gwmw.Masking(redactionWanted()) + ctx, m, err := maskingFor(ctx) if m == nil { return nil, s, maskHits{}, err } @@ -261,7 +290,7 @@ func maskedBefore(r *http.Request) (string, bool) { if c.maskedAs == "" || MaskRoute(strings.TrimSpace(settings.Shared().RedactRouteTo)) { return "", false } - fp := ownMaskedAs() + fp := ownMaskedAs(r.Context()) if fp == "" { return "", false } @@ -312,7 +341,12 @@ var buildRe = lazyre.New(`^v?0\.1\.(\d{1,7})(?:$|[-+])`) // settings (masking.Fingerprint) and the masker's code, this build's // version, since a newer one can find what an older one let by. "" when // it masks nothing. -func ownMaskedAs() string { +func ownMaskedAs(ctx context.Context) string { + if access.Caller(ctx).Redact != "" { + // a key's own setting: the settings' fingerprint isn't what masked + // it (off masked nothing, on may have masked by the defaults) + return "" + } fp := masking.Fingerprint(settings.Shared()) if fp == "" { return "" @@ -324,6 +358,16 @@ func ownMaskedAs() string { // masking itself is served by the redact plugin (plugins/redact); this is // the core's own reading, so a request isn't sent unmasked when the plugin // isn't there to mask it. +func redactionWantedFor(ctx context.Context) bool { + switch access.Caller(ctx).Redact { + case access.RedactOff: + return false + case access.RedactOn: + return true + } + return redactionWanted() +} + func redactionWanted() bool { return masking.Wanted(settings.Shared()) } diff --git a/internal/gateway/remote_magpie_once_test.go b/internal/gateway/remote_magpie_once_test.go index fc6857f7c..e19a2de66 100644 --- a/internal/gateway/remote_magpie_once_test.go +++ b/internal/gateway/remote_magpie_once_test.go @@ -1,6 +1,7 @@ package gateway import ( + "context" "io" "net/http" "net/http/httptest" @@ -105,7 +106,7 @@ func TestRemoteMagpieMasksWhatItIsNotToldWasMasked(t *testing.T) { body, _ := seen() return body } - own := ownMaskedAs() + own := ownMaskedAs(context.Background()) if own == "" { t.Fatal("no fingerprint with masking on") } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 368d1848d..7af5ada53 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3161,12 +3161,12 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } #gatewayKeys .amodels.key-models { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } /* a key's quotas and concurrency badges (#2216) take no room until the row is hovered, and give way before the row runs past a narrow window */ -#gatewayKeys .amodels:is(.key-quotas, .key-conc, .key-tier) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } +#gatewayKeys .amodels:is(.key-quotas, .key-conc, .key-tier, .key-redact) { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } /* unset, shown by a hover, they give way before the masked key does: the key squeezed by them on a narrow window slid its copy button under the pointer that came to drag the row */ -#gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier):not(.set) { flex-shrink: 8; } -#gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc, .key-tier):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } +#gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-redact):not(.set) { flex-shrink: 8; } +#gatewayKeys .acc:not(:hover) > :is(.key-quotas, .key-conc, .key-tier, .key-redact):not(.set, .open, :focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } /* the MCP servers a key held to some may use: cut, and gives way first */ #gatewayKeys .amodels.key-mcp { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* a read-only key's tag, always shown, never a button */ @@ -4574,8 +4574,8 @@ body.panel .modal { padding: 16px 12px; } body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .aspend, .abal):not(.set) { margin-left: 0 !important; } body.web .accts.keys .acc > .abal.abal-many { flex-shrink: 1 !important; padding-block: 2px !important; } body.web .accts.keys .key-acts > .text.quiet { margin-right: 0 !important; } - body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } - body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-redact) { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; } + body.web #gatewayKeys .acc > :is(.key-quotas, .key-conc, .key-tier, .key-redact):not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; } } /* Import from other apps: a checklist per app */ diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 482506abc..bdd992e2e 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2791,6 +2791,13 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "这个密钥的请求按此服务层级发出,无论请求指定什么", "This key's requests keep the service tier they ask for": "这个密钥的请求保持各自指定的服务层级", "{who}: service tier {tier}": "{who}:服务层级 {tier}", + "Masking on": "脱敏:开", + "Masking off": "脱敏:关", + "Follow Settings": "跟随设置", + "This key's requests are always masked": "这个密钥的请求始终脱敏", + "This key's requests are never masked": "这个密钥的请求从不脱敏", + "This key's requests are masked as Settings › Privacy says": "这个密钥的请求按设置 › 隐私的脱敏规则处理", + "{who}: masking {mode}": "{who}:脱敏 {mode}", "Provider's": "沿用提供商", "Any number at once": "同时任意多个", "A number of your own, up to 1000": "自定义数字,最大 1000", @@ -7873,6 +7880,13 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "這個金鑰的請求依此服務層級送出,無論請求指定什麼", "This key's requests keep the service tier they ask for": "這個金鑰的請求保持各自指定的服務層級", "{who}: service tier {tier}": "{who}:服務層級 {tier}", + "Masking on": "脫敏:開", + "Masking off": "脫敏:關", + "Follow Settings": "跟隨設定", + "This key's requests are always masked": "這個金鑰的請求一律脫敏", + "This key's requests are never masked": "這個金鑰的請求從不脫敏", + "This key's requests are masked as Settings › Privacy says": "這個金鑰的請求依設定 › 隱私的脫敏規則處理", + "{who}: masking {mode}": "{who}:脫敏 {mode}", "Provider's": "沿用提供商", "Any number at once": "同時任意多個", "A number of your own, up to 1000": "自定義數字,最大 1000", @@ -12933,6 +12947,13 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "このキーのリクエストは、指定にかかわらずこのサービス階層で送られます", "This key's requests keep the service tier they ask for": "このキーのリクエストは、指定されたサービス階層のまま送られます", "{who}: service tier {tier}": "{who}:サービス階層 {tier}", + "Masking on": "マスク オン", + "Masking off": "マスク オフ", + "Follow Settings": "設定に従う", + "This key's requests are always masked": "このキーのリクエストは常にマスクされます", + "This key's requests are never masked": "このキーのリクエストはマスクされません", + "This key's requests are masked as Settings › Privacy says": "このキーのリクエストは設定 › プライバシーのとおりにマスクされます", + "{who}: masking {mode}": "{who}:マスク {mode}", "Provider's": "プロバイダーに従う", "Any number at once": "同時数の制限なし", "A number of your own, up to 1000": "任意の数(最大 1000)", @@ -18024,6 +18045,13 @@ const I18N = { "This key's requests go at this service tier, whatever they ask": "Anfragen dieses Schlüssels laufen in dieser Service-Stufe, egal was sie anfordern", "This key's requests keep the service tier they ask for": "Anfragen dieses Schlüssels behalten die Service-Stufe, die sie anfordern", "{who}: service tier {tier}": "{who}: Service-Stufe {tier}", + "Masking on": "Maskierung an", + "Masking off": "Maskierung aus", + "Follow Settings": "Wie in den Einstellungen", + "This key's requests are always masked": "Anfragen dieses Schlüssels werden immer maskiert", + "This key's requests are never masked": "Anfragen dieses Schlüssels werden nie maskiert", + "This key's requests are masked as Settings › Privacy says": "Anfragen dieses Schlüssels werden maskiert, wie es Einstellungen › Datenschutz sagt", + "{who}: masking {mode}": "{who}: Maskierung {mode}", "Provider's": "Wie der Anbieter", "Any number at once": "Beliebig viele gleichzeitig", "A number of your own, up to 1000": "Eine eigene Zahl, bis 1000", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 9fcf9a0cd..dc5a62c78 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -234,7 +234,7 @@ function renderGatewayKeys() { tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id }); // the copy sits by the key it copies (the owner: stranded among the // badges it read as nobody's); Rotate and Remove wait in the row's menu - row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); + row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.browser ? [gatewayBrowserTag()] : k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), ...gatewayKeptOutBadge(k), ...gatewayMCPBadge(k), gatewayQuotasBadge(k), ...(k.browser || k.readOnly ? [] : [gatewayConcurrencyBadge(k), gatewayTierBadge(k), gatewayRedactBadge(k)]), gatewayLimitBadge(k), gatewayKeyMore(k)); const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u)); if (under.length) row.classList.add("with-limit"), row.append(...under); list.append(row); @@ -999,6 +999,36 @@ function gatewayTierBadge(k) { return b; } +// A key's masking (y0ngb1n on X): as Settings › Privacy says, always on, or +// off for a device the user trusts. A request with no key (this +// computer's own) follows the settings. +const KEY_REDACT = [ + { v: "", name: "Follow Settings", note: "" }, + { v: "on", name: "On", note: "" }, + { v: "off", name: "Off", note: "" }, +]; +function gatewayRedactBadge(k) { + const own = k.redact || ""; + const cur = KEY_REDACT.find((o) => o.v === own) || KEY_REDACT[0]; + const b = el("button", "amodels key-redact" + (own ? " set" : "")); + b.type = "button"; + b.textContent = t(own === "on" ? "Masking on" : own === "off" ? "Masking off" : "Masking"); + b.title = t(own === "on" ? "This key's requests are always masked" : own === "off" ? "This key's requests are never masked" : "This key's requests are masked as Settings › Privacy says"); + b.setAttribute("aria-label", t("Masking")); + b.setAttribute("aria-haspopup", "menu"); + b.setAttribute("aria-expanded", "false"); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, KEY_REDACT, cur.v, async (v) => { + if (v === cur.v) return; + const out = await gatewayKeyAction("redact-key", { key: k.id, redact: v }); + if (out) status(t("{who}: masking {mode}", { who: k.name, mode: t(KEY_REDACT.find((o) => o.v === v).name) }), "ok"); + }, "Masking", "sess-menu"); + }; + return b; +} + // ---- a gateway key's own limit (#585) ---- // "days" is every N days from when the limit is set or reset (#1509), diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index ff67245ad..36b16a722 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -229,6 +229,7 @@ function fixture(lang, theme, events, options = {}) { k.maxConcurrency = body.maxConcurrency || undefined; } if (action === "tier-key") k.serviceTier = body.serviceTier || undefined; + if (action === "redact-key") k.redact = body.redact === "on" || body.redact === "off" ? body.redact : undefined; if (action === "access-key") k.readOnly = body.readOnly || undefined; // a key put at a place in the list, as access.Update keeps it; // options.refuseMove: the store can't be written diff --git a/internal/gui/tests/gateway-key-redact.test.cjs b/internal/gui/tests/gateway-key-redact.test.cjs new file mode 100644 index 000000000..912205783 --- /dev/null +++ b/internal/gui/tests/gateway-key-redact.test.cjs @@ -0,0 +1,69 @@ +// A gateway key's masking (y0ngb1n on X): a badge on the key's row, shown +// always while set and on hover while not, opens the app's menu (no native +// select): as Settings say, On or Off. It sends "redact-key"; a read-only +// key has none. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const words = { + en: { label: "Masking", follow: "Follow Settings", on: "On", off: "Off", badgeOn: "Masking on", badgeOff: "Masking off" }, + zh: { label: "脱敏", follow: "跟随设置", on: "开启", off: "关闭", badgeOn: "脱敏:开", badgeOff: "脱敏:关" }, + "zh-TW": { label: "脫敏", follow: "跟隨設定", on: "開啟", off: "關閉", badgeOn: "脫敏:開", badgeOff: "脫敏:關" }, + ja: { label: "マスク", follow: "設定に従う", on: "オン", off: "オフ", badgeOn: "マスク オン", badgeOff: "マスク オフ" }, + de: { label: "Maskierung", follow: "Wie in den Einstellungen", on: "An", off: "Aus", badgeOn: "Maskierung an", badgeOff: "Maskierung aus" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${width} ${lang}: a key's masking is set from the app's menu`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + page.setDefaultNavigationTimeout(60000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { redact: "off" }, laptop: { readOnly: true } } })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .acc[data-key]").last().waitFor(); + const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`); + const badge = (id) => row(id).locator(".key-redact"); + const item = (name) => page.locator(".proto-menu .pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name}$`) }) }); + const sent = () => events.filter((e) => e.action === "redact-key").map((e) => e.body); + const reads = (id, text) => page.waitForFunction(([id, text]) => document.querySelector(`#gatewayKeys .acc[data-key="${id}"] .key-redact`)?.textContent === text, [id, text]); + + // set: said always, not only on hover; a read-only key has none + await page.mouse.move(0, 0); + assert.equal(await badge("server").textContent(), w.badgeOff); + assert.equal(await badge("server").evaluate((b) => getComputedStyle(b).opacity), "1"); + assert.equal(await badge("server").getAttribute("aria-label"), w.label); + assert.equal(await badge("laptop").count(), 0); + // unset: on hover only + assert.equal(await badge("work").evaluate((b) => getComputedStyle(b).opacity), "0"); + await row("work").hover(); + assert.equal(await badge("work").textContent(), w.label); + + await badge("work").click(); + await page.locator(".proto-menu").waitFor(); + assert.equal(await page.locator(".proto-menu .pm-head").textContent(), w.label); + await item(w.on).click(); + await reads("work", w.badgeOn); + assert.deepEqual(sent(), [{ key: "work", redact: "on" }]); + + await row("server").hover(); + await badge("server").click(); + await item(w.follow).click(); + await reads("server", w.label); + assert.deepEqual(sent().at(-1), { key: "server", redact: "" }); + + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + assert.equal(await page.locator("select").count(), 0, "no native select"); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/masking/masking.go b/internal/masking/masking.go index ebdc28f4c..8782e3fab 100644 --- a/internal/masking/masking.go +++ b/internal/masking/masking.go @@ -43,6 +43,15 @@ func WithRoute(ctx context.Context, route string) context.Context { return context.WithValue(ctx, routeKey{}, route) } +type forcedKey struct{} + +// WithForced is ctx for masking a request a gateway key holds to masking +// (access.RedactOn) whatever the settings say: where they mask nothing it +// is masked for secrets and personal data by the defaults. +func WithForced(ctx context.Context) context.Context { + return context.WithValue(ctx, forcedKey{}, true) +} + // optionsCtx is options with the model's wait ending with ctx, for the // route ctx has (WithRoute). func optionsCtx(ctx context.Context) redact.Options { @@ -50,6 +59,10 @@ func optionsCtx(ctx context.Context) redact.Options { o := redact.Options{Secrets: st.Redact, Personal: st.RedactPersonal, Kinds: st.RedactKinds, Words: st.RedactWords, WordsAnyCase: st.RedactWordsAnyCase, WordsWhole: st.RedactWordsWhole, Rules: st.RedactRules, Actions: st.RedactActions, Allow: st.RedactAllow, Shape: st.RedactShape} o.Route, _ = ctx.Value(routeKey{}).(string) + if forced, _ := ctx.Value(forcedKey{}).(bool); forced && !Wanted(st) { + o.Secrets, o.Personal = true, true + st.Redact, st.RedactPersonal = true, true + } if (st.Redact || st.RedactPersonal) && ModelWanted(st) { // until the model is on disk the rules mask alone, and nothing is // held back for a download (it is started here) diff --git a/plugins/redact/redact.go b/plugins/redact/redact.go index db1302850..8f2d36ab0 100644 --- a/plugins/redact/redact.go +++ b/plugins/redact/redact.go @@ -10,6 +10,9 @@ package redact import ( + "slices" + + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/gwmw" "github.com/yetone/magpie/internal/masking" "github.com/yetone/magpie/internal/pluginrt" @@ -43,5 +46,13 @@ func InUse() (int, error) { if masking.Wanted(st) { return 1, nil } + // a key held to masking (access.RedactOn) uses it with the setting off + keys, err := access.List() + if err != nil { + return 0, err + } + if slices.ContainsFunc(keys, func(k access.Key) bool { return k.Redact == access.RedactOn && !k.Off }) { + return 1, nil + } return 0, nil }