agent: a key of the gateway's own in place of magpie's still reaches magpie (#2510, PaulT on Discord)

PaulT made a key under Gateway keys and put it in Hermes's config.yaml
(providers.magpie.api_key) in place of `magpie`. Requests went through
magpie, but the picker said Hermes's api_key was changed and that
magpie's gateway won't take its requests.

The class: wiringOff, and the key checks of Codex
([model_providers.magpie] experimental_bearer_token), Qwen Code
(env.MAGPIE_API_KEY) and Reasonix (its env file), accepted only the exact
key magpie wrote. A sync also wrote `magpie` back over the user's key,
in mergeKept (every yamlKept/jsonKept agent) and in Reasonix's install.

keyHolds(v, want) is the one check now. Where want is a key magpie gives
for its gateway (gateway.Token, the LAN key, or a TokenFor), it takes any
v that access.Authenticate takes, the same test dsh has used since #1332.
It never stands in for a URL or another value. A key the gateway doesn't
take, or one turned off, is still drift and is still written over.

Run, at 8b84dc902 in its own worktree, with a sandbox HOME:
- TestHermesWithAGatewayKeyOfTheUsers: an issued key in Hermes's
  config.yaml is no drift and survives a sync. A key the gateway doesn't
  take is drift and is replaced by the sync.
- TestKeyHoldsTakesAGatewayKey: covers magpie's own key, TokenFor, a
  foreign key, an empty key, and a URL or mode value.
- Broken by hand: with keyHolds back to v == want, both tests are red
  ("a key the gateway issued is drift"). With mergeKept's keep removed,
  the sync test is red ("a sync wrote over the user's key: magpie").
- gofmt -l clean; go vet -tags nogui on darwin, linux and windows ok.
- go test -timeout 45m ./... (pipefail): every package ok except these:
  - internal/agent and internal/gateway ran out of the 45m budget twice.
    The load average was ~130-250, from other sessions on this machine.
    Each was then run in full in shards, every test from its own
    go test -list, each shard with its own 45m: agent 855 tests in 3
    shards, ok. gateway 2113 tests in 5 shards, ok.
  - internal/gui: TestPanelJoinsFullScreenSpaces, open as #2450 (macOS 26.2).
  - gateway's TestMaxRPMGroupPrefersMemberWithRoom: a 1s bar under load,
    open as #2520. It passed in the sharded run.
- Not tried: a real Hermes run. It re-bootstraps its launcher under a
  sandbox HERMES_HOME, so this was read from the config only.
This commit is contained in:
yetone
2026-10-16 20:08:01 +08:00
parent 9e5fd84bf6
commit d9b943555d
7 changed files with 122 additions and 6 deletions
+3 -2
View File
@@ -901,12 +901,13 @@ func sameHost(a, b string) bool { return hostOf(a) == hostOf(b) }
// gateway — pairs of key and value, read with get — and says which no longer
// holds, "" when all do. A URL is quoted; a key's value never is. A URL
// that reaches magpie another way (reachesMagpie: a reverse proxy, #1985)
// holds.
// holds. So does a key of the gateway's own the user put in place of
// magpie's (keyHolds).
func wiringOff(name, file string, get func(string) (string, bool), kvs ...string) string {
for i := 0; i+1 < len(kvs); i += 2 {
k, want := kvs[i], kvs[i+1]
v, _ := get(k)
if v == want || v != "" && reachesMagpie(v, want) {
if keyHolds(v, want) || v != "" && reachesMagpie(v, want) {
continue
}
where := name + "'s " + k + " (" + filepath.Base(file) + ")"
+1 -1
View File
@@ -1261,7 +1261,7 @@ func codexIn(at place) *Agent {
if err != nil {
return err.Error()
}
if t["base_url"] != at.v1() || t["experimental_bearer_token"] != at.gwKey() || t["wire_api"] != "responses" {
if t["base_url"] != at.v1() || !keyHolds(t["experimental_bearer_token"], at.gwKey()) || t["wire_api"] != "responses" {
return "Codex's [model_providers.magpie] no longer points at magpie's gateway (" + at.v1() + ")"
}
if c := get("model_catalog_json"); !ownCatalog(c) {
+18
View File
@@ -1,6 +1,8 @@
package agent
import (
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gateway"
)
@@ -63,3 +65,19 @@ func gatewayTakes(k string) bool {
_, ok := access.Authenticate(k)
return ok
}
// gatewayKey says want is a key magpie gives an agent for its gateway:
// gateway.Token, the LAN sharing key, or one naming the agent
// (gateway.TokenFor).
func gatewayKey(want string) bool {
return ourKey(want) || strings.HasPrefix(want, gateway.Token+"-") && !strings.ContainsAny(want, "/:")
}
// keyHolds says the value v an agent's config has where magpie wrote want
// still reaches magpie: want itself, or, where want is magpie's key for its
// gateway, a key of the gateway's own the user put there instead (Gateway
// keys), which the gateway takes just the same (PaulT on Discord: Hermes
// with a key of his own was said not to go through magpie).
func keyHolds(v, want string) bool {
return v == want || v != "" && gatewayKey(want) && gatewayTakes(v)
}
+90
View File
@@ -8,8 +8,10 @@ import (
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
"gopkg.in/yaml.v3"
)
@@ -357,3 +359,91 @@ func TestHermesKeepsTheUsersSettings(t *testing.T) {
}
check("pick")
}
// PaulT on Discord: a key made under Gateway keys, put in Hermes's
// config.yaml in place of magpie's, goes through magpie all the same, so
// the check is quiet and a sync keeps it. A key the gateway doesn't take
// still is drift.
func TestHermesWithAGatewayKeyOfTheUsers(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("HERMES_HOME", "")
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
if err := provider.Save(provider.Provider{ID: "deepseek", Name: "DeepSeek", Chat: "https://api.deepseek.com/v1", Key: "k", Models: []string{"pro"}}); err != nil {
t.Fatal(err)
}
dir := appdir.HermesHomeIn(home)
path := filepath.Join(dir, "config.yaml")
os.MkdirAll(dir, 0o755)
os.WriteFile(path, []byte("model:\n default: x\n"), 0o644)
a := hermes(home)
if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {
t.Fatal(err)
}
if d := a.Check(); d != "" {
t.Fatalf("as magpie wrote it: %s", d)
}
secret, err := access.Update("add-key", access.Change{Name: "hermes"})
if err != nil {
t.Fatal(err)
}
if err := edit.SetYAML(path, edit.KV{Path: "providers.magpie.api_key", Value: secret}); err != nil {
t.Fatal(err)
}
if d := a.Check(); d != "" {
t.Fatalf("a key the gateway issued is drift: %s", d)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if v, _ := edit.GetYAML(path, "providers.magpie.api_key"); v != secret {
t.Fatalf("a sync wrote over the user's key: %q", v)
}
if err := edit.SetYAML(path, edit.KV{Path: "providers.magpie.api_key", Value: "sk-not-this-gateways"}); err != nil {
t.Fatal(err)
}
if d := a.Check(); !strings.Contains(d, "api_key") {
t.Fatalf("a key the gateway doesn't take is not reported: %q", d)
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
if v, _ := edit.GetYAML(path, "providers.magpie.api_key"); v != gateway.Token {
t.Fatalf("a key the gateway doesn't take is kept: %q", v)
}
}
// keyHolds, which every agent's check of magpie's key goes through: a key
// of the gateway's own stands in for magpie's, never for a URL or another
// value, and one the gateway doesn't take doesn't.
func TestKeyHoldsTakesAGatewayKey(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
secret, err := access.Update("add-key", access.Change{Name: "mine"})
if err != nil {
t.Fatal(err)
}
for _, c := range []struct {
v, want string
ok bool
}{
{gateway.Token, gateway.Token, true},
{secret, gateway.Token, true},
{secret, gateway.TokenFor("alma"), true},
{"sk-other", gateway.Token, false},
{"", gateway.Token, false},
{secret, "http://127.0.0.1:3425/v1", false},
{secret, "chat_completions", false},
} {
if got := keyHolds(c.v, c.want); got != c.ok {
t.Errorf("keyHolds(%q, %q) = %v", c.v, c.want, got)
}
}
if d := wiringOff("X", "x.yaml", func(string) (string, bool) { return secret, true }, "api_key", gateway.Token); d != "" {
t.Fatalf("wiringOff: %s", d)
}
}
+1 -1
View File
@@ -351,7 +351,7 @@ func qwenIn(at place) *Agent {
if c == nil {
return ""
}
if v, ok := edit.GetJSON(path, qwenEnv); !ok || v != at.gwKey() {
if v, _ := edit.GetJSON(path, qwenEnv); !keyHolds(v, at.gwKey()) {
return "Qwen Code's " + qwenEnv + " (settings.json) no longer is magpie's key, so magpie's models have none"
}
if v, ok := edit.GetJSON(path, qwenAuth); !ok || v != "openai" {
+2 -2
View File
@@ -261,7 +261,7 @@ func reasonixIn(at place) *Agent {
}
currentState.AddedAccess = true
}
if token, _ := edit.GetEnvFile(env, reasonixKey); token != gwKey() {
if token, _ := edit.GetEnvFile(env, reasonixKey); !keyHolds(token, gwKey()) {
if err := edit.SetEnvFile(env, edit.KV{Path: reasonixKey, Value: gwKey()}); err != nil {
return err
}
@@ -331,7 +331,7 @@ func reasonixIn(at place) *Agent {
if p.Kind != "openai" || p.BaseURL != at.v1() && !reachesMagpie(p.BaseURL, at.v1()) {
return "Reasonix's magpie base_url or kind changed"
}
if token, _ := edit.GetEnvFile(env, reasonixKey); token != gwKey() {
if token, _ := edit.GetEnvFile(env, reasonixKey); !keyHolds(token, gwKey()) {
return "Reasonix's gateway credential changed"
}
if !slices.Contains(p.Models, ref) || cfg.Agent.Planner != nil && usesMagpie(*cfg.Agent.Planner) && !slices.Contains(p.Models, strings.TrimPrefix(*cfg.Agent.Planner, magpieID+"/")) {
+7
View File
@@ -221,6 +221,13 @@ func mergeKept(have, want map[string]any, own []string) map[string]any {
}
for k, h := range have {
if slices.Contains(own, k) {
// magpie's key for the gateway, where the user put a key of
// the gateway's own instead: theirs stays (keyHolds)
if hs, ok := h.(string); ok {
if ws, ok := want[k].(string); ok && hs != ws && keyHolds(hs, ws) {
out[k] = hs
}
}
continue
}
w, ok := want[k]