P3's third point (docs/subsystems/plugin-runtime.md). internal/gwmw has two
places, each with its own failure policy:
- Agent: a middleware on an agent's request in its own API and on its reply.
serveAgent runs each registered one. The JS gateway middleware is the one
there (middleware.Chain), registered by the new built-in plugin
`middleware`. Its place, API, limits and fail-open are unchanged. InUse is
middleware.On(). Off, no middleware runs.
- Masker: what goes to a vendor, masked, and the values back in what comes
back. The new built-in plugin `redact` serves masking.Masker (in
internal/masking, since settings imports redact). InUse is masking.Wanted.
It fails closed: masking asked for with no masker serving, or a masker that
panics, is a 503 "nothing was sent" at every call site that masked before
(serve, count_tokens, embeddings and audio, transcriptions, images, video,
search stand-ins and their queries, the Codex backend).
With no masker, or with no agent middleware while plugins.json has one on,
the gateway asks pluginrt.Refresh, at most once a second. A setting or
middleware added a moment ago serves the request that needs it.
pluginrt.KeepFresh also watches plugins.json now.
Run (on origin/main 95e7c6bcc + this change, with the next commit's two
test waits):
- go test -count=1 -timeout 60m ./...: all ok (gateway 682s, agent 617s)
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, Chromium and WebKit: builtins, plugin-kernel, i18n-keys, gui-de,
gui-ja, gui-zh-tw. builtins reaches the Usage row by wheel now, since the
page puts back a scroll that isn't the reader's.
Broken by hand, each went red:
- masking fails open with no masker (TestMaskingOnAndOff)
- a panic isn't recovered (TestSafelyTurnsAPanicIntoAnError, TestMaskingOnAndOff)
- no refresh asked (TestServedRefreshesOnce, TestMaskingOnAndOff)
- the plugins don't register (plugins/redact, plugins/middleware
TestOnServesOffDoesNot)
- InUse misses redactWords (plugins/redact TestInUse)
- maskedQuery fails open (TestMaskedQueryFailsClosed)
- middleware runs with the plugin off (TestMiddlewareOnAndOff/off)
- no refresh on a middleware miss (TestMiddlewareOnAndOff), want ignored
(TestAgentsWantedRefreshesWhenWanted)
Real use, sandbox HOME, magpie serve and a fake vendor that echoes:
- redact off with nothing asked: sent as written
- redactWords written, request at once: the vendor got {{TERM_…}} and the
agent got the word back; `plugin builtin off redact` refused while in use
- `magpie plugin add ./alias.middleware.js`: the next request is rewritten
(200, was 404). Removed: 404 again.
The first build left that request at 404 until a restart, since plugins.json
wasn't watched. That's fixed here.
Not tried: a real vendor account; the Windows box.
204 lines
6.6 KiB
Go
204 lines
6.6 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/gwmw"
|
|
"github.com/yetone/magpie/internal/masking"
|
|
"github.com/yetone/magpie/internal/middleware"
|
|
"github.com/yetone/magpie/internal/plugin"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// echoing is a vendor that keeps what it was sent and says the last
|
|
// message back.
|
|
type echoing struct {
|
|
mu sync.Mutex
|
|
sent []string
|
|
}
|
|
|
|
func (e *echoing) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
b, _ := io.ReadAll(r.Body)
|
|
e.mu.Lock()
|
|
e.sent = append(e.sent, string(b))
|
|
e.mu.Unlock()
|
|
var req struct {
|
|
Messages []struct{ Content string } `json:"messages"`
|
|
}
|
|
json.Unmarshal(b, &req)
|
|
said := ""
|
|
if n := len(req.Messages); n > 0 {
|
|
said = req.Messages[n-1].Content
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(map[string]any{"id": "x", "choices": []any{map[string]any{"index": 0, "message": map[string]any{"role": "assistant", "content": "you said " + said}, "finish_reason": "stop"}}})
|
|
}
|
|
|
|
func (e *echoing) count() int {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
return len(e.sent)
|
|
}
|
|
|
|
func (e *echoing) last() string {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
return e.sent[len(e.sent)-1]
|
|
}
|
|
|
|
// panicky is a masker that fails.
|
|
type panicky struct{ masking.Masker }
|
|
|
|
func (panicky) JSON([]byte) ([]byte, int) { panic("masker broke") }
|
|
|
|
// The middleware point's masker with plugins/redact on and off. On, a
|
|
// secret goes to the vendor as a placeholder and comes back as it was.
|
|
// Off, while the settings ask for masking, nothing is sent: the request is
|
|
// refused with 503 and the vendor never sees it, unless a refresh turns
|
|
// the plugin on, as the settings asking for masking do. A masker that
|
|
// panics refuses too. Off with nothing asked for, a request goes as it is.
|
|
func TestMaskingOnAndOff(t *testing.T) {
|
|
fresh(t)
|
|
const secret = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
|
|
v := &echoing{}
|
|
serveOn(t, "pa", "ka", []string{"m"}, v)
|
|
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := New()
|
|
ask := `{"model":"pa/m","messages":[{"role":"user","content":"key ` + secret + `"}]}`
|
|
masked := func(when string) {
|
|
t.Helper()
|
|
code, body := postAs(t, s, "", ask)
|
|
if code != 200 || strings.Contains(v.last(), secret) || !strings.Contains(body, "you said key "+secret) {
|
|
t.Fatalf("%s: %d %s, the vendor got %s", when, code, body, v.last())
|
|
}
|
|
}
|
|
refused := func(when string) {
|
|
t.Helper()
|
|
n := v.count()
|
|
code, body := postAs(t, s, "", ask)
|
|
if code != http.StatusServiceUnavailable || !strings.Contains(body, "nothing was sent") || v.count() != n {
|
|
t.Fatalf("%s: %d %s, the vendor was sent %d", when, code, body, v.count()-n)
|
|
}
|
|
}
|
|
masked("on")
|
|
t.Run("off", func(t *testing.T) {
|
|
withoutMasker(t)
|
|
gwmw.ForgetRefreshForTest()
|
|
refused("off")
|
|
// the settings ask for masking: the refresh turns it on
|
|
gwmw.ForgetRefreshForTest()
|
|
var remove func()
|
|
stop := gwmw.Refresh(func() { remove = gwmw.Mask(masking.Masker{}) })
|
|
masked("off, turned on by the refresh")
|
|
remove()
|
|
stop()
|
|
gwmw.ForgetRefreshForTest()
|
|
// nothing asked for: it goes as it is
|
|
if err := settings.Save(settings.Settings{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if code, body := postAs(t, s, "", ask); code != 200 || !strings.Contains(v.last(), secret) {
|
|
t.Fatalf("off, not asked for: %d %s, the vendor got %s", code, body, v.last())
|
|
}
|
|
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
})
|
|
t.Run("panics", func(t *testing.T) {
|
|
remove := gwmw.Mask(panicky{})
|
|
defer remove()
|
|
refused("a masker that panics")
|
|
})
|
|
masked("on again")
|
|
}
|
|
|
|
// The same for a web search's query, which goes to a search service, not
|
|
// a model: off with masking asked for, the search MCP's query isn't sent.
|
|
func TestMaskedQueryFailsClosed(t *testing.T) {
|
|
fresh(t)
|
|
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
const secret = "sk-proj-abcdEFGH1234ijklMNOP5678qrst"
|
|
if q, err := maskedQuery("find "+secret, nil); err != nil || strings.Contains(q, secret) {
|
|
t.Fatalf("on: %q %v", q, err)
|
|
}
|
|
withoutMasker(t)
|
|
gwmw.ForgetRefreshForTest()
|
|
if q, err := maskedQuery("find "+secret, nil); err == nil {
|
|
t.Fatalf("off: sent %q", q)
|
|
}
|
|
// one the user set to go unmasked keeps it, plugin or not
|
|
p := &provider.Provider{ID: "local", Unredacted: true, Chat: "http://127.0.0.1:1/v1"}
|
|
if q, err := maskedQuery("find "+secret, p); err != nil || q != "find "+secret {
|
|
t.Fatalf("off, to a provider set unmasked: %q %v", q, err)
|
|
}
|
|
}
|
|
|
|
// The middleware point's agent middleware with plugins/middleware on and
|
|
// off: on, a JS middleware in plugins.json rewrites the request; off, the
|
|
// gateway runs none, and the request is routed as the agent sent it.
|
|
func TestMiddlewareOnAndOff(t *testing.T) {
|
|
fresh(t)
|
|
v := &echoing{}
|
|
serveOn(t, "pa", "ka", []string{"m"}, v)
|
|
t.Cleanup(plugin.Settle)
|
|
mw := filepath.Join(t.TempDir(), "alias.middleware.js")
|
|
os.WriteFile(mw, []byte(`
|
|
export function onRequest(body, ctx) {
|
|
if (body.model === "fast") body.model = "pa/m";
|
|
return body;
|
|
}`), 0o644)
|
|
b, _ := json.Marshal(plugin.List{Plugins: []plugin.Entry{{Spec: mw}}})
|
|
os.MkdirAll(settings.Dir(), 0o755)
|
|
os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644)
|
|
middleware.Reload()
|
|
defer middleware.Reload()
|
|
if middleware.On() != 1 {
|
|
t.Fatalf("middleware on: %d", middleware.On())
|
|
}
|
|
s := New()
|
|
ask := `{"model":"fast","messages":[{"role":"user","content":"hi"}]}`
|
|
if code, body := postAs(t, s, "", ask); code != 200 {
|
|
t.Fatalf("on: %d %s", code, body)
|
|
}
|
|
t.Run("off", func(t *testing.T) {
|
|
withoutMiddleware(t)
|
|
calls := middleware.States()[mw].Calls
|
|
n := v.count()
|
|
if code, body := postAs(t, s, "", ask); code == 200 || v.count() != n {
|
|
t.Fatalf("off: %d %s, the vendor was sent %d", code, body, v.count()-n)
|
|
}
|
|
if got := middleware.States()[mw].Calls; got != calls {
|
|
t.Fatalf("off, the middleware ran: %d calls, was %d", got, calls)
|
|
}
|
|
})
|
|
// off while plugins.json has a middleware on: the gateway asks a
|
|
// refresh, which turns the plugin on for this request (the gateway's is
|
|
// pluginrt.Refresh), not after KeepFresh's next look
|
|
t.Run("off, then a refresh turns it on", func(t *testing.T) {
|
|
withoutMiddleware(t)
|
|
gwmw.ForgetRefreshForTest()
|
|
var remove func()
|
|
stop := gwmw.Refresh(func() { remove = gwmw.Use(middleware.Chain{}) })
|
|
defer stop()
|
|
if code, body := postAs(t, s, "", ask); code != 200 || remove == nil {
|
|
t.Fatalf("refreshed: %d %s", code, body)
|
|
}
|
|
remove()
|
|
})
|
|
if code, body := postAs(t, s, "", ask); code != 200 {
|
|
t.Fatalf("on again: %d %s", code, body)
|
|
}
|
|
}
|