library: a WSL agent under NAT is given a signed-in MCP server with the LAN key, so the gateway no longer answers its every call 401 (#1488, ggbdpq)

A server magpie signed in to (#615) is given to the agents at the
gateway's /mcp/<name>, at the address each reaches the gateway at. A WSL
distro under NAT reaches it at Windows' address, so its requests come
from another machine, and lanGuard refuses such a request without an
enabled gateway key with a 401, which an MCP client takes for the server
asking it to sign in. through() gave it no key. Its models already carry
the LAN sharing key there (keyAt, whqtian on Discord); the relay didn't.
The gateway's checks are unchanged: a request from another machine still
needs the key, and mcpProxy still lends a sign-in beyond loopback only
to a request that carried it (sharedWith).

What changed:
- agent.KeyAt exports keyAt: the LAN sharing key for an agent that
  reaches the gateway from another machine while sharing is on, else
  gateway.Token.
- through() gives such an agent Authorization: Bearer <that key>. The
  gateway takes it in lanGuard, and mcpProxy drops Authorization for
  magpie's token, so the server never sees it. An agent on loopback, and
  one in WSL while nothing is shared, stay keyless.
- access.LANChanged runs after sharing is turned on or off or its key is
  made anew; the library syncs again then when it relays any server, so
  the entry carries the key there is now without a visit to the Library.
- docs/subsystems/library.md says so.

Run:
- TestSignedInServerCarriesKeyBeyondLoopback (library: a FakeWSL distro
  routed via 172.20.0.1, LAN on) fails on the old through() ("claude@wsl:
  Ubuntu under NAT is given headers map[X-Team:acme], want the LAN key as
  its Authorization") and passes now; with the LANChanged call commented
  out it fails at "after a new key ... is given" the old key.
- TestMCPProxyFromWSLWithLANKey (gateway, through lanGuard as the server
  runs it): 401 without the key and the server not called, 200 with it,
  the server gets magpie's token and never the key.
- go test -tags nogui ./... under a temp HOME; gofmt -l; GOOS=linux and
  GOOS=windows go vet -tags nogui on the touched packages.
- Not tried on a real Windows + WSL NAT machine with a real OAuth MCP
  server; FakeWSL and httptest only.

Patch by ggbdpq in #1488; the LANChanged resync added on top.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
yetone
2026-10-10 18:09:59 +08:00
co-authored by ggbdpq
parent bfd5c82d1f
commit 91581fca27
6 changed files with 167 additions and 1 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
| Targets | `Targets` lists the detected agents (`agent.Detected`), plus apps like Claude Desktop, with where each keeps its instructions file (and an `Override` it reads instead), its MCP file and its skills folder. An agent in a running WSL distro has its places under the distro's home (`wslTargetOf`): Claude Code, Codex, Pi and OmO each by its own rule, and every agent that keeps all of them in its own folder (Hermes Agent, omp, OpenCode, Droid and the rest of `ownFolder`, #1323) by the same rule as on this machine, its MCP file marked as WSL's so a Windows program isn't given to it. | [`targets.go`](../../internal/library/targets.go) |
| Sync | `sync` writes each target's instructions and MCP servers. It then takes edits made in agents' skill copies into the library (`takeEdits`) and links or copies the skills. `~/.agents/skills` goes first, so an agent that reads it gets no second link. Then it syncs projects' skills. | [`sync.go`](../../internal/library/sync.go) |
| Instructions | magpie's part of an agent's instructions file sits between two marker lines. The rest of the file is the user's. Several named sets can be switched between (#106). | [`instructions.go`](../../internal/library/instructions.go) |
| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only. Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615). | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go) |
| MCP servers | A `Server` is a command or a URL (`http`, `sse`). `mcpFile` encodes it in each agent's own format (one `mcpFormat` per agent family) and merges it with the user's own fields for that entry. `Also` files get the same servers; `Extra` files are only read when importing. `CheckServers` connects as an agent would and keeps the result in memory only. Each step (initialize, notifications/initialized, tools/list; connect for SSE) has its own budget, 60s for a URL and 30s for a command (`remoteStep`, `stdioStep`), and a timeout names its `Step` and how long it `Waited`; a timeout isn't kept, so the next look asks again (#1467). A server that needs OAuth is signed in once in magpie, and agents reach it through the gateway's `/mcp/<name>` (#615); one that reaches the gateway from another machine (a WSL distro under NAT) is given it with the LAN sharing key as its `Authorization` (`agent.KeyAt`), as its models are, which the gateway takes in place of a sign-in and never passes on; turning sharing on or off, or a new key (`access.LANChanged`), writes such entries again. | [`mcp.go`](../../internal/library/mcp.go), [`mcp_check.go`](../../internal/library/mcp_check.go), [`mcp_signin.go`](../../internal/library/mcp_signin.go) |
| Skills | A skill is a folder with a `SKILL.md`. It comes from GitHub, from a folder on this machine (linked, so editing the folder edits the skill) or from the market. Each agent gets a link or a marked copy (#896, `SkillHow`). An agent in a WSL distro always gets a copy. A copy's mark keeps the hash of what was copied, so a sync knows a copy unchanged since then is current without reading its files (`copyIsFresh`, #1031); other copies are hashed. A skill an agent has of its own (`foundSkills`, the page's "In your agents") is brought in with `ImportSkill`, or taken out of every agent that has it with `RemoveFoundSkill` (#1303): its folders and copies of the very same files, its shared `~/.agents/skills` entry and a folder of it in the library's own folder go to the backups, its links are taken away, and a folder elsewhere it only links to, or another skill by that name, stays. | [`skills.go`](../../internal/library/skills.go), [`skill_how.go`](../../internal/library/skill_how.go), [`skill_edits.go`](../../internal/library/skill_edits.go), [`skill_from.go`](../../internal/library/skill_from.go) |
| Skills market | `MarketSkills` lists skills.sh's most installed and what its search finds. magpie's own skills (`featuredSkills`) go first, marked official: `magpie-quota`, in [magpie-community/plugins](https://github.com/magpie-community/plugins/tree/main/skills/magpie-quota), lets an agent read `magpie quota --json` and wait with `magpie quota wait`. Until skills.sh lists one it has no count of installs and no skills.sh link (`featured`). `InstallMarketSkill` installs any of them from its repository. | [`market.go`](../../internal/library/market.go) |
| Skills a repository added | A check for updates (`CheckSkills`) also asks, for each GitHub repository and ref the library has skills from, GitHub's list of its files (`repoTree`, one API request, free when the ETag still matches). Only when that list has a skill folder beside the installed ones (under `newBase`, their deepest common folder) that the library doesn't have and hasn't offered does `findNew` fetch the repository for the skills' names and descriptions. `SeenSkills` records per `repo@ref` the paths the install picker showed and the ones set aside, so they aren't offered again. The finds live in memory (`newFound`) and reach the page as `View.NewSkills`; `AddNewSkills` gives each to the agents that have its repository's other skills, and `IgnoreNewSkills` sets it aside (`/api/library/skills/{add-new,ignore-new}`). | [`skillnew.go`](../../internal/library/skillnew.go), [`skillcheck.go`](../../internal/library/skillcheck.go) |
+13
View File
@@ -442,9 +442,22 @@ func migrateLegacyLANKey() error {
return settings.Save(s)
}
// LANChanged is called after sharing is turned on or off, or its key made
// anew: what was given the key goes on with the one there is now (the
// library's MCP servers relayed to an agent in a WSL distro under NAT).
var LANChanged = func() {}
// ConfigureLAN starts sharing with a named key. Rotation preserves the key's
// identity, name and enabled state.
func ConfigureLAN(on, rotate bool) error {
if err := configureLAN(on, rotate); err != nil {
return err
}
LANChanged()
return nil
}
func configureLAN(on, rotate bool) error {
mu.Lock()
defer mu.Unlock()
if err := migrateLegacyLANKey(); err != nil {
+4
View File
@@ -20,6 +20,10 @@ func keyAt(gw string) string {
return gateway.Token
}
// KeyAt is keyAt, for what else magpie gives an agent that reaches the
// gateway at gw (the library's MCP servers relayed through it).
func KeyAt(gw string) string { return keyAt(gw) }
// gwKey is keyAt for the agent at p.
func (p place) gwKey() string { return keyAt(p.gw()) }
+43
View File
@@ -8,6 +8,7 @@ import (
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/mcpauth"
"github.com/yetone/magpie/internal/mcpauth/mcpauthtest"
)
@@ -132,6 +133,48 @@ func TestMCPProxyStaysHere(t *testing.T) {
}
}
// A WSL agent under NAT, at Windows' address, is lent the sign-in with the
// key the gateway is shared with as its Authorization (library's through),
// which the server never sees: it gets magpie's token. Without the key the
// call is a 401, which an MCP client takes for the server asking it to
// sign in.
func TestMCPProxyFromWSLWithLANKey(t *testing.T) {
fresh(t)
if err := access.ConfigureLAN(true, false); err != nil {
t.Fatal(err)
}
key := access.LANSecret()
f := mcpauthtest.New(t)
f.SignIn(t, "neon")
h := lanGuard(New().Handler())
call := func(auth string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", "/mcp/neon", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize"}`))
r.RemoteAddr = "172.20.0.5:40000"
r.Host = "172.20.0.1:3425"
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Accept", "application/json, text/event-stream")
if auth != "" {
r.Header.Set("Authorization", auth)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
if w := call(""); w.Code != http.StatusUnauthorized || len(f.Calls) != 0 {
t.Fatalf("without the key: %d, calls %v", w.Code, f.Calls)
}
w := call("Bearer " + key)
token, _ := mcpauth.Token(t.Context(), "neon")
if w.Code != 200 || f.Seen.Get("Authorization") != "Bearer "+token {
t.Fatalf("with the LAN key: %d %s, the server got Authorization %q", w.Code, w.Body, f.Seen.Get("Authorization"))
}
for k, v := range f.Seen {
if strings.Contains(strings.Join(v, " "), key) {
t.Fatalf("the server got the LAN key in %s", k)
}
}
}
// A web page can't borrow magpie's sign-ins through the browser: a request
// with an Origin, or one to a hostname of the page's own pointed at
// 127.0.0.1, is refused before it reaches the server.
+32
View File
@@ -5,8 +5,11 @@ import (
"errors"
"fmt"
"net/url"
"slices"
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/mcpauth"
)
@@ -19,6 +22,25 @@ import (
func init() {
mcpauth.Changed = func(string) { _, _ = Sync() }
// an agent beyond loopback is given a relayed server with the LAN key
// (through), which is the one there is no longer
access.LANChanged = func() {
if relaysAny() {
_, _ = Sync()
}
}
}
// relaysAny says whether any of the library's servers is given through the
// gateway: one magpie is signed in to.
func relaysAny() bool {
mu.Lock()
l, err := load()
mu.Unlock()
if err != nil {
return false
}
return slices.ContainsFunc(l.MCP, func(s *Server) bool { return s.Transport == "http" && mcpauth.SignedIn(s.Name, s.URL) })
}
// through is the server as an agent that reaches the gateway at base is
@@ -41,6 +63,16 @@ func through(s *Server, base string) *Server {
}
c.Headers[k] = v
}
if k := agent.KeyAt(base); k != gateway.Token {
// from another machine (a WSL distro under NAT) the gateway refuses
// a call without an enabled key, with a 401 the agent would take
// for the server asking it to sign in; the relay drops this
// Authorization for magpie's token
if c.Headers == nil {
c.Headers = map[string]string{}
}
c.Headers["Authorization"] = "Bearer " + k
}
return &c
}
+74
View File
@@ -0,0 +1,74 @@
package library
import (
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/mcpauth/mcpauthtest"
)
// A WSL agent under NAT reaches the gateway at Windows' address, where a
// request without an enabled gateway key is refused with a 401, which an
// MCP client takes for the server asking it to sign in. A server magpie
// signed in to is given to it at /mcp/<name> with the key the gateway is
// shared with, as its models are; this machine's agent stays keyless, and
// so does the WSL one while nothing is shared.
func TestSignedInServerCarriesKeyBeyondLoopback(t *testing.T) {
sandbox(t)
root := t.TempDir()
write(t, filepath.Join(root, "home", "me", ".claude", "settings.json"), "{}\n")
t.Cleanup(agent.FakeWSL(map[string]string{
"Ubuntu": "home:/home/me\ndir:.claude\nroute:default via 172.20.0.1 dev eth0\nnet:nat\n",
}, map[string]string{"Ubuntu": root}))
const wsl = "claude@wsl:Ubuntu"
if err := access.ConfigureLAN(true, false); err != nil {
t.Fatal(err)
}
key := access.LANSecret()
if key == "" {
t.Fatal("no LAN key")
}
f := mcpauthtest.New(t)
ok(t)(SaveServer("", Server{Name: "neon", Transport: "http", URL: f.URL, Headers: map[string]string{"X-Team": "acme"}, Agents: []string{"claude", wsl}}))
f.SignIn(t, "neon")
given := func(id string) *Server {
t.Helper()
tg := targetByID(id)
if tg == nil {
t.Fatalf("%s isn't a target: %v", id, ids(Targets()))
}
got, err := tg.MCP.read()
if err != nil {
t.Fatal(err)
}
return got["neon"]
}
s := given(wsl)
if s == nil || !strings.HasPrefix(s.URL, "http://172.20.0.1:") || !strings.HasSuffix(s.URL, "/mcp/neon") {
t.Fatalf("%s: %+v", wsl, s)
}
if s.Headers["Authorization"] != "Bearer "+key || s.Headers["X-Team"] != "acme" {
t.Fatalf("%s under NAT is given headers %v, want the LAN key as its Authorization", wsl, s.Headers)
}
if h := given("claude"); h == nil || h.Headers["Authorization"] != "" || h.Headers["X-Team"] != "acme" {
t.Fatalf("this machine's claude: %+v", h)
}
// a new key, and sharing turned off, reach the entry without a visit
// to the Library
if err := access.ConfigureLAN(true, true); err != nil {
t.Fatal(err)
}
if fresh := access.LANSecret(); fresh == key || given(wsl).Headers["Authorization"] != "Bearer "+fresh {
t.Fatalf("after a new key %s is given %v", wsl, given(wsl).Headers)
}
if err := access.ConfigureLAN(false, false); err != nil {
t.Fatal(err)
}
if s := given(wsl); s == nil || s.Headers["Authorization"] != "" {
t.Fatalf("nothing shared, yet %s is given %+v", wsl, s)
}
}