diff --git a/docs/subsystems/library.md b/docs/subsystems/library.md index 6e6948ce7..c6d5bfed6 100644 --- a/docs/subsystems/library.md +++ b/docs/subsystems/library.md @@ -42,6 +42,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it. - An update from GitHub never silently replaces a skill changed here. It is refused, or skipped in an update of several, until the user says to replace it, and the version replaced goes to the backups. - A copy's mark establishes that it is unchanged only after its whole folder was scanned. If a subtree or its metadata can't be read, the copy stays in place and the sync reports a `Problem`; it isn't replaced, relinked or removed. A later sync tries again once it can be read. The same scan failure stops replacing a project's or Claude Desktop's copy. - A failure for one agent is a `Problem` in the result. It doesn't stop the others. +- An MCP OAuth sign-in canceled or timed out before its callback commits never saves a late token or changes an existing sign-in. The callback's write and the flow's ending share a lock (`flow.keep` in [`mcpauth.go`](../../internal/mcpauth/mcpauth.go)); if the write wins first, it completes and tells the agents before saying done. A cancellation is not a sign-out of credentials already committed. - A server an agent can't reach is not written there, and `mcpFile.supports` says why. For example, Claude Desktop takes no remote server, and Codex, Goose, dsh, Grok, Command Code and Zed take no SSE. - A server's headers (remote) or environment (command) can name a variable as `${NAME}` (#1250). `library.json` keeps the placeholder, and `refsOf` gives each MCP format the agent's own syntax, with the agent's source cited beside it: `${NAME}` for most, `{env:NAME}` for OpenCode and MiMo, `${env:NAME}` for Cursor, and Codex's own keys (`bearer_token_env_var`, `env_http_headers`, `env_vars`). Goose gets `${NAME}` plus `env_keys`. dsh (DeepSeek Harness) gets a `!!js` expression it evaluates as it loads the server (#1435): a whole `${NAME}` is `!!js process.env.NAME`, and a value mixing text and variables is the text as JSON string literals joined with `(process.env.NAME ?? "")`, so the user's text is never run as code and an unset variable inside it is empty. A whole variable that isn't set makes dsh leave the server out as invalid. magpie reads only those forms back as `${NAME}`; any other `!!js` keeps the entry the user's. An agent with no syntax (Claude Desktop, Antigravity, Kimi, Cline, ZCode, Zed, Devin, Alma, Pi with pi-mcp-extension) is never written the value: `refsProblem` makes `supports` refuse the server, a magpie entry already there is taken out, and `AgentView.NoEnvRefs` greys its chip with the reason. Codex and Goose's extra keys are magpie's only while the server names a variable there (`refKeys`), so the user's own `env_vars` or `env_keys` are kept. `CheckServers` expands the variable from magpie's own environment, and one that isn't set is `novar`, naming it. It starts a command server in home, with `PWD` set to it (not on Windows), as an agent started from home would, never in magpie's own working folder: a magpie started from the Windows Start menu has `C:\Windows\system32`, where a server that writes into `.` exits before it answers (#1727, `TestCheckStdio`). - A server's tools turned off on the page (nf1qaz2w on Discord) are kept by their names as the server gives them, in `Server.DisabledTools`, and written only to the agents that read a setting for it (`toolsOffOf`), each in its own form, checked against its source: diff --git a/internal/mcpauth/mcpauth.go b/internal/mcpauth/mcpauth.go index 17d91336c..2883287c4 100644 --- a/internal/mcpauth/mcpauth.go +++ b/internal/mcpauth/mcpauth.go @@ -908,16 +908,10 @@ func StartWith(ctx context.Context, name, serverURL string, app *App) (State, er if t.Scope != "" { r2.Scope = t.Scope } - if err := update(func(m map[string]*Record) bool { m[name] = &r2; return true }); err != nil { - f.finish(State{State: "failed", Error: err.Error()}) + if err := f.keep(name, r2); err != nil { page(w, http.StatusOK, "Magpie couldn't keep the sign-in: "+err.Error()) return } - // the agents are given magpie's address before the sign-in is said done - if Changed != nil { - Changed(name) - } - f.finish(State{State: "done"}) page(w, http.StatusOK, "Magpie is signed in to "+name+". Every agent given it in the Library uses this sign-in. You can close this tab.") }) f.srv = &http.Server{Handler: mux, ReadHeaderTimeout: 10 * time.Second} @@ -941,6 +935,31 @@ func (f *flow) status() State { return f.st } +// keep commits the callback only while the flow is still live. Cancel or +// timeout and the write take the same lock, so a late token cannot save a +// sign-in the user already ended, or replace their previous sign-in. +func (f *flow) keep(name string, r Record) error { + f.mu.Lock() + if f.finished { + f.mu.Unlock() + return errors.New("the sign-in has ended; start it again") + } + err := update(func(m map[string]*Record) bool { m[name] = &r; return true }) + f.finished = true + f.mu.Unlock() + if err != nil { + f.end(State{State: "failed", Error: err.Error()}) + return err + } + // The commit won over cancellation; give the agents the new address + // outside the flow's lock, before saying the sign-in is done. + if Changed != nil { + Changed(name) + } + f.end(State{State: "done"}) + return nil +} + func (f *flow) finish(st State) { f.mu.Lock() if f.finished { @@ -948,6 +967,13 @@ func (f *flow) finish(st State) { return } f.finished = true + f.mu.Unlock() + f.end(st) +} + +// end is called once by the operation that claimed finished. +func (f *flow) end(st State) { + f.mu.Lock() f.st.State, f.st.Error = st.State, st.Error f.mu.Unlock() close(f.done) diff --git a/internal/mcpauth/mcpauth_cancel_test.go b/internal/mcpauth/mcpauth_cancel_test.go new file mode 100644 index 000000000..46ac03979 --- /dev/null +++ b/internal/mcpauth/mcpauth_cancel_test.go @@ -0,0 +1,101 @@ +package mcpauth_test + +import ( + "bytes" + "io" + "net/http" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/mcpauth" + "github.com/yetone/magpie/internal/mcpauth/mcpauthtest" + "github.com/yetone/magpie/internal/settings" +) + +type heldTokenResponse struct { + base http.RoundTripper + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (h *heldTokenResponse) RoundTrip(r *http.Request) (*http.Response, error) { + resp, err := h.base.RoundTrip(r) + if err == nil && r.URL.Path == "/oauth/token" { + h.once.Do(func() { close(h.entered) }) + <-h.release + } + return resp, err +} + +// Cancel must still win after the browser claims its callback, while the +// token endpoint's successful reply is in flight. +func TestCanceledMCPCallbackDoesNotSave(t *testing.T) { + for _, previous := range []bool{false, true} { + name := "new sign-in" + if previous { + name = "existing sign-in" + } + t.Run(name, func(t *testing.T) { + home(t) + f := mcpauthtest.New(t) + if previous { + f.SignIn(t, "demo") + } + path := filepath.Join(settings.Dir(), "mcp-signins.json") + before, err := os.ReadFile(path) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + h := &heldTokenResponse{ + base: http.DefaultTransport, + entered: make(chan struct{}), + release: make(chan struct{}), + } + oldClient, oldChanged := mcpauth.Client, mcpauth.Changed + mcpauth.Client = &http.Client{Transport: h} + var changed atomic.Int32 + mcpauth.Changed = func(string) { changed.Add(1) } + t.Cleanup(func() { + mcpauth.Client, mcpauth.Changed = oldClient, oldChanged + }) + st, err := mcpauth.Start(t.Context(), "demo", f.URL) + if err != nil { + t.Fatal(err) + } + defer mcpauth.Cancel(st.ID) + done := make(chan error, 1) + go func() { + resp, err := http.Get(st.URL) + if err == nil { + _, err = io.Copy(io.Discard, resp.Body) + resp.Body.Close() + } + done <- err + }() + <-h.entered + mcpauth.Cancel(st.ID) + got, _ := mcpauth.Progress(st.ID) + if got.State != "canceled" { + t.Errorf("state after cancellation = %q", got.State) + } + close(h.release) + if err := <-done; err != nil { + t.Fatal(err) + } + after, err := os.ReadFile(path) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + if !bytes.Equal(before, after) { + t.Errorf("canceled callback saved credentials: previous sign-in = %v", previous) + } + if got := changed.Load(); got != 0 { + t.Errorf("canceled callback redistributed credentials %d times", got) + } + }) + } +}