gateway: /v1/realtime passes a Realtime API session on to its provider (Qwen Token Plan's realtime voice)

gaubeebangeel (X) set up Qwen's Token Plan in magpie and couldn't use its
realtime voice: magpie had no /v1/realtime, so the WebSocket upgrade got a
404. Token Plan does cover realtime: qwen-audio-3.0-realtime-plus at
wss://<plan host>/api-ws/v1/realtime?model=… with the plan's sk-sp- key,
OpenAI Realtime events
(platform.qianwenai.com/docs/token-plan/best-practices/realtime-voice).

GET /v1/realtime and /realtime upgrade to a WebSocket after the same Front
guards as every route (lanGuard, corsGuard, keys, the rebinding check),
plus a same-origin check on the socket's Origin. The model resolves as on
the other routes (a bare id unlisted anywhere goes to the one DashScope
provider that is on), with key, model and account holds, and each try is
dialled in turn with the account's key. A DashScope base ending
/compatible-mode/v1 dials /api-ws/v1/realtime; any other base dials
base+/realtime (OpenAI). Frames go both ways as they are; a close goes on
with its code and reason. Text frames are masked going up and restored
coming down (audio appends and deltas are not), failing closed. Each
response.done's usage is recorded as a "realtime" call (cached input as
cache read). openai-insecure-api-key / organization / project
subprotocols never go upstream. Shutdown ends open sessions with 1001.
/realtime is a client route on magpie web's port (and in the LazyCat
manifest), and a read-only key is refused it.

Run (mote, at this tree):
- TestRealtime* (fake upstream WebSocket, no network): Token Plan path,
  echo, binary, close both ways, usage 60 in / 40 cache read / 20 out,
  OpenAI-style path, subprotocol filter, masking; guards: 426, 400, 404,
  Origin evil/null/localhost subdomain 403, rebound host, remote without
  key 401, key held to another provider 403, vendor 401 passed on.
- Broken by hand, each went red: subprotocol filter removed, masking off,
  cached tokens not subtracted.
- GOOS=linux and GOOS=windows go vet ./internal/gateway: clean.
- go test -count=1 -timeout 45m ./internal/gateway ./internal/masking
  ./internal/gui: the first run found TestClientPathCoversHandler,
  TestReadOnlyKeyEveryRoute and then TestLazyCatManifestListsTheClientRoutes
  red, all fixed here and rerun green. Otherwise ok. The log has one
  recovered "close of closed channel" in continuation_test.go:781's
  doneHold fake upstream (a test fake this change doesn't touch; in both
  runs), already filed as #6505 (and its duplicate #6690).
- Rebased on origin/main 6dbd6e5b1 and rerun at the rebased head: the
  TestRealtime* tests, the three route-list guard tests, gofmt -l, and
  GOOS=linux / GOOS=windows go vet ./internal/gateway.

Not run: the full ./... suite at any head (mote at load ~22-33 of 18, mica ~66 of
12). Not tried with a real Token Plan account or a real Realtime client.
This commit is contained in:
yetone
2026-11-16 15:31:53 +08:00
parent 6dbd6e5b1c
commit 56c988cb5e
9 changed files with 1061 additions and 6 deletions
+1
View File
@@ -3903,6 +3903,7 @@ application:
- /decisions
- /audio
- /videos
- /realtime
- /muse-code/models
- /backend-api/codex
- /alpha/search
File diff suppressed because one or more lines are too long
+1
View File
@@ -241,6 +241,7 @@ func TestForeignPagesRefused(t *testing.T) {
{"POST", "/v1/decisions", `{"model":"plan/m1","input":"hi","questions":[{"type":"predicate","instructions":"is it?"}]}`},
{"POST", "/v1/audio/transcriptions", "--b\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nplan/m1\r\n--b--\r\n"},
{"POST", "/v1/audio/speech", `{"model":"plan/m1","input":"hi","voice":"coral"}`},
{"GET", "/v1/realtime?model=plan/m1", ""},
{"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`},
{"POST", "/v1/videos", `{"model":"plan/m1","prompt":"hi"}`},
{"POST", CodexPath + "/responses", `{"model":"plan/m1","input":"hi"}`},
+10 -3
View File
@@ -601,6 +601,8 @@ type Server struct {
unread unreadConns
// sockets are the Responses WebSockets being served (responses_ws.go)
sockets clientSockets
// realtimes are the Realtime API sessions being served (realtime.go)
realtimes realtimeSessions
// what it serves other computers TLS with, nil without (tls.go)
tls *tlsServer
// the images described for models that can't see them (vision.go);
@@ -981,7 +983,10 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
// a socket's connection was taken from the server (hijacked), so
// Shutdown doesn't wait for it: each ends after its turn in flight
sockets := make(chan struct{})
go func() { defer close(sockets); s.sockets.drain(c) }()
// a realtime session has no turn to wait for: it is closed going
// away, and its client opens a new one
s.realtimes.end()
go func() { defer close(sockets); s.sockets.drain(c); s.realtimes.wait(c) }()
if err := srv.Shutdown(c); err != nil {
// the requests still answering are cut where they are, and
// an agent streaming one reads a reply broken off (Codex:
@@ -1152,6 +1157,8 @@ func (s *Server) routes() *routeMux {
// speech to text, for a client's voice input (#2053)
mux.HandleFunc("POST /v1/audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions"))
mux.HandleFunc("POST /audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions"))
mux.HandleFunc("GET /v1/realtime", s.realtime)
mux.HandleFunc("GET /realtime", s.realtime)
mux.HandleFunc("POST /v1/audio/translations", s.transcribe("/audio/translations", "translations"))
mux.HandleFunc("POST /audio/translations", s.transcribe("/audio/translations", "translations"))
mux.HandleFunc("POST /v1/audio/speech", s.speak)
@@ -1187,7 +1194,7 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("GET /v1beta/models", s.geminiModels)
mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/decisions, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*")
writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/decisions, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech, /v1/realtime (WebSocket) and /v1beta/models/*")
})
return mux
}
@@ -1216,7 +1223,7 @@ var catalogSize stamped[struct{}, int]
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window,
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, SessionsMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
"apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", NativePath + "{provider}/{path}", "/v1/embeddings", "/v1/rerank", "/v1/decisions", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/realtime", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", StatuslinePath, "/v1/magpie/trace", OwnMCPPath, SearchMCPPath, VisionMCPPath, MemoryMCPPath, SessionsMCPPath, ImageMCPPath, BrowserMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
// which process serves, for another magpie on this computer to name it
// on its Routing page (#2606); not told to another machine
if local(r) {
+2 -1
View File
@@ -441,6 +441,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) {
{"POST", "/v1/images/generations"}, {"POST", "/v1/images/edits"},
{"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"}, {"POST", "/v1/decisions"},
{"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/audio/speech"},
{"GET", "/v1/realtime?model=m"}, {"GET", "/realtime?model=m"},
{"POST", "/v1/videos"}, {"GET", "/v1/videos/v1"}, {"GET", "/v1/videos/v1/content"},
{"POST", "/_magpie/claude-mcp/tok"}, {"POST", "/mcp/neon"},
{"POST", CodexPath + "/responses"}, {"GET", CodexCatalogPath},
@@ -450,7 +451,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) {
call := func(method, path, from string, hdr ...string) (int, string) {
r := httptest.NewRequest(method, path, strings.NewReader("{}"))
r.RemoteAddr = from
if path == "/v1/responses" || path == "/responses" {
if path == "/v1/responses" || path == "/responses" || strings.Contains(path, "realtime?") {
r.Header.Set("Connection", "Upgrade")
r.Header.Set("Upgrade", "websocket")
r.Header.Set("Sec-WebSocket-Version", "13")
+1 -1
View File
@@ -26,7 +26,7 @@ func (s *Server) Front() http.Handler {
var clientPrefixes = []string{
"/v1", "/v1beta",
"/models", "/chat/completions", "/responses", "/messages",
"/images", "/embeddings", "/rerank", "/decisions", "/audio", "/videos",
"/images", "/embeddings", "/rerank", "/decisions", "/audio", "/videos", "/realtime",
"/muse-code/models", CodexPath, AlphaSearchPath, "/mcp",
// the key page (KeyPagePath): a key's holder opens it at the address
// they give their agents
+1
View File
@@ -56,6 +56,7 @@ var readOnlyRefused = []string{
"POST /v1/audio/transcriptions", "POST /audio/transcriptions",
"POST /v1/audio/translations", "POST /audio/translations",
"POST /v1/audio/speech", "POST /audio/speech",
"GET /v1/realtime", "GET /realtime",
"POST /v1/videos", "POST /videos", "GET /v1/videos/{id}", "GET /videos/{id}",
"GET /v1/videos/{id}/content", "GET /videos/{id}/content",
"POST " + NativePath + "{provider}/{path...}", "GET " + NativePath + "{provider}/{path...}", "DELETE " + NativePath + "{provider}/{path...}",
+647
View File
@@ -0,0 +1,647 @@
package gateway
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"slices"
"strings"
"sync"
"time"
"github.com/coder/websocket"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
// The Realtime API over a WebSocket: GET /v1/realtime?model=… with
// Upgrade: websocket, as OpenAI's Realtime API and DashScope's (Qwen's)
// realtime models take it (gaubeebangeel on X: a Qwen Token Plan's
// realtime voice through magpie). Alibaba sells the Token Plan's
// realtime voice model, qwen-audio-3.0-realtime-plus, on the plan's own
// host at /api-ws/v1/realtime with the plan's sk-sp- key
// (platform.qianwenai.com/docs/token-plan/best-practices/realtime-voice).
//
// The session goes to one model's provider, over its keys or accounts as
// a chat would, and is passed on frame by frame both ways; magpie reads
// the frames only to mask what goes out (as the settings say), put the
// masked values back in what comes in, and count each response.done's
// usage. The upgrade comes through the whole handler, so the allow list,
// the gateway key and its models and accounts, the Origin and Host
// checks judge it as they judge any request; a page from another origin
// can't open one at all (a browser's WebSocket isn't held by CORS), and a
// session opened with a key ends when the key is no longer on.
//
// A provider's realtime address is its OpenAI-style base's: DashScope's
// (…/compatible-mode/v1) at /api-ws/v1/realtime on the same host, any
// other at base + /realtime (OpenAI's /v1/realtime).
var (
// realtimeDial bounds the upstream handshake
realtimeDial = 30 * time.Second
// realtimeKeyCheck is how often a session opened with a gateway key
// looks whether the key is still on
realtimeKeyCheck = 5 * time.Second
)
// realtimeReadLimit is the largest frame read either way: a few seconds
// of base64 audio is well under it.
const realtimeReadLimit = 32 << 20
// realtimeSessions are the sessions being served; their connections were
// taken from the server (hijacked), so they are closed when it ends.
type realtimeSessions struct {
mu sync.Mutex
m map[*websocket.Conn]bool
closing bool
// running counts the handlers serving a session, for end's caller to
// wait for (wait); idle is closed when it is back at none
running int
idle chan struct{}
}
func (rs *realtimeSessions) enter() {
rs.mu.Lock()
rs.running++
rs.mu.Unlock()
}
func (rs *realtimeSessions) leave() {
rs.mu.Lock()
defer rs.mu.Unlock()
if rs.running--; rs.running == 0 && rs.idle != nil {
close(rs.idle)
rs.idle = nil
}
}
func (rs *realtimeSessions) add(c *websocket.Conn) bool {
rs.mu.Lock()
defer rs.mu.Unlock()
if rs.closing {
return false
}
if rs.m == nil {
rs.m = map[*websocket.Conn]bool{}
}
rs.m[c] = true
return true
}
func (rs *realtimeSessions) remove(c *websocket.Conn) {
rs.mu.Lock()
defer rs.mu.Unlock()
delete(rs.m, c)
}
func (rs *realtimeSessions) ending() bool {
rs.mu.Lock()
defer rs.mu.Unlock()
return rs.closing
}
// end closes every session going away; a client opens a new one to the
// gateway serving the port then.
func (rs *realtimeSessions) end() {
rs.mu.Lock()
rs.closing = true
all := make([]*websocket.Conn, 0, len(rs.m))
for c := range rs.m {
all = append(all, c)
}
rs.mu.Unlock()
for _, c := range all {
go c.Close(websocket.StatusGoingAway, "magpie is restarting")
}
}
// wait waits for every session's handler to have returned, or ctx.
func (rs *realtimeSessions) wait(ctx context.Context) {
rs.mu.Lock()
if rs.running == 0 {
rs.mu.Unlock()
return
}
if rs.idle == nil {
rs.idle = make(chan struct{})
}
idle := rs.idle
rs.mu.Unlock()
select {
case <-idle:
case <-ctx.Done():
}
}
// realtime serves GET /v1/realtime.
func (s *Server) realtime(w http.ResponseWriter, r *http.Request) {
if !wantsSocket(r) {
w.Header().Set("Upgrade", "websocket")
writeError(w, provider.Chat, http.StatusUpgradeRequired, "the Realtime API is a WebSocket: open GET /v1/realtime?model=<provider>/<model> with Upgrade: websocket")
return
}
s.realtimes.enter()
defer s.realtimes.leave()
start := time.Now()
asked := strings.TrimSpace(r.URL.Query().Get("model"))
who := callerOf(r)
call := Call{Time: start, From: provider.Chat, To: provider.Chat, Agent: who.agent, Via: who.via, Model: asked, headers: headerLogOf(r.Context())}
usage.Saw(agentOf(r))
refuse := func(code int, msg string) {
call.Status, call.Error, call.Millis = code, msg, time.Since(start).Milliseconds()
writeError(w, provider.Chat, code, msg)
s.record(call)
}
// a page of another origin (the library's check, made before anything
// is dialled): corsGuard let a page on this computer by, which a
// browser's WebSocket isn't held from by CORS
if !sameOriginSocket(r) {
refuse(http.StatusForbidden, "magpie opens a realtime session only for a client that isn't a web page, or a page at magpie's own address")
return
}
if s.realtimes.ending() {
refuse(http.StatusServiceUnavailable, "magpie is restarting")
return
}
if asked == "" {
refuse(http.StatusBadRequest, "name the model: /v1/realtime?model=<provider>/<model> (qwen-token-plan/qwen-audio-3.0-realtime-plus, openai/gpt-realtime)")
return
}
if msg, off := idOff(asked); off {
refuse(http.StatusForbidden, msg)
return
}
if _, _, isGroup := provider.FindGroup(asked); isGroup {
refuse(http.StatusBadRequest, "a realtime session goes to one model: name a model, not the routing group "+asked)
return
}
p, model, code, msg := resolveRealtimeModel(asked)
if code != 0 {
refuse(code, msg)
return
}
if msg, off := modelOff(p, model, asked); off {
refuse(http.StatusForbidden, msg)
return
}
if keyWho, held := keyHolds(r); held && !modelAllowed(keyWho, p, model) {
st, msg := keyModelRefusal(w, keyWho, asked)
refuse(st, msg)
return
}
tries, code, msg := s.onKeys(r, p, model, asked)
if code != 0 {
refuse(code, msg)
return
}
if keyWho, held := accountHolds(r); held {
tries = slices.DeleteFunc(tries, func(c candidate) bool { return !accountAllowed(keyWho, c) })
if len(tries) == 0 {
refuse(http.StatusForbidden, keyAccountsError(keyWho, asked))
return
}
}
tries = probeOne(tries) // of those resting, only the one back soonest (#1799)
// the session lives past the handshake: its context ends when the
// handler returns
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
offered := realtimeSubprotocols(r.Header)
var up *websocket.Conn
var c candidate
var skipped []string
for i, try := range tries {
last := i == len(tries)-1
call.Provider, call.Model = try.p.ID, asked
u, why := realtimeURL(try.p, try.model)
var err error
code := http.StatusBadRequest
if why != "" {
err = errors.New(why)
} else {
up, code, err = s.dialRealtime(ctx, r, try.p, u, offered)
}
if err == nil {
c = try
break
}
if !last && r.Context().Err() == nil {
skipped = append(skipped, try.label()+": "+err.Error())
continue
}
call.Fallback = strings.Join(skipped, "; ")
msg := err.Error()
if len(skipped) > 0 {
msg += " (tried first: " + call.Fallback + ")"
}
refuse(code, msg)
return
}
call.Fallback = strings.Join(skipped, "; ")
defer up.CloseNow()
up.SetReadLimit(realtimeReadLimit)
// what goes out is masked, unless the provider is set to go unmasked;
// fails closed before the client is answered
var mask *realtimeMask
if !c.unmasked() {
mctx, m, err := maskingFor(r.Context())
if err != nil {
up.Close(websocket.StatusGoingAway, "")
refuse(maskStatus(err), err.Error())
return
}
if m != nil {
mask = &realtimeMask{ctx: mctx, m: m}
}
}
var accept []string
if sp := up.Subprotocol(); sp != "" {
accept = []string{sp}
}
client, err := websocket.Accept(w, r, &websocket.AcceptOptions{Subprotocols: accept})
if err != nil {
up.Close(websocket.StatusGoingAway, "")
call.Status, call.Error, call.Millis = http.StatusBadRequest, "the client's WebSocket handshake failed: "+err.Error(), time.Since(start).Milliseconds()
s.record(call)
return
}
defer client.CloseNow()
client.SetReadLimit(realtimeReadLimit)
if !s.realtimes.add(client) {
client.Close(websocket.StatusGoingAway, "magpie is restarting")
up.Close(websocket.StatusGoingAway, "")
return
}
defer s.realtimes.remove(client)
// a session opened with a gateway key ends once the key isn't on
if keyWho := access.Caller(r.Context()); keyWho.KeyID != "" {
go func() {
t := time.NewTicker(realtimeKeyCheck)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
if !access.Current(keyWho) {
log.Printf("realtime: the gateway key %s is no longer on, so its session to %s is closed", keyWho.KeyName, c.p.ID)
go up.Close(websocket.StatusPolicyViolation, "")
client.Close(websocket.StatusPolicyViolation, "the gateway key this session was opened with is no longer on")
return
}
}
}
}()
}
sess := &realtimeSession{s: s, r: r, c: c, asked: asked, mask: mask}
status, why := sess.pipe(ctx, client, up)
call.Status, call.Millis, call.Usage = status, time.Since(start).Milliseconds(), sess.total
call.Error = cmpOr(why, sess.lastErr)
s.record(call)
}
// sameOriginSocket: the upgrade has no Origin (a program's client), or
// one at the address it was sent to, as coder/websocket's own check
// takes it.
func sameOriginSocket(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return true
}
u, err := url.Parse(origin)
return err == nil && u.Host != "" && strings.EqualFold(u.Host, r.Host)
}
// realtimeSubprotocols are the subprotocols the client offered, less
// the ones a browser carries an OpenAI key or organization in, which are
// never passed on.
func realtimeSubprotocols(h http.Header) []string {
var out []string
for _, v := range h.Values("Sec-WebSocket-Protocol") {
for _, p := range strings.Split(v, ",") {
p = strings.TrimSpace(p)
if p == "" || strings.HasPrefix(p, "openai-insecure-api-key.") || strings.HasPrefix(p, "openai-organization.") || strings.HasPrefix(p, "openai-project.") {
continue
}
out = append(out, p)
}
}
return out
}
// resolveRealtimeModel finds the model's provider as a chat's is found;
// a bare id no provider lists (the Token Plan's hosts list nothing) goes
// to the one DashScope provider turned on, when there is one.
func resolveRealtimeModel(asked string) (provider.Provider, string, int, string) {
if p, model, ok := provider.Resolve(asked); ok {
return p, model, 0, ""
}
if off, isOff := provider.SwitchedOff(asked); isOff {
return provider.Provider{}, "", http.StatusNotFound, switchedOff(off, asked)
}
if strings.Contains(asked, "/") {
return provider.Provider{}, "", http.StatusNotFound, unknownModel(asked, "")
}
var found []provider.Provider
for _, p := range provider.All() {
if p.On() && !p.DecideOnly() && dashScopeBase(p.OpenAIBase()) {
found = append(found, p)
}
}
switch len(found) {
case 1:
return found[0], asked, 0, ""
case 0:
return provider.Provider{}, "", http.StatusNotFound, unknownModel(asked, "")
}
ids := make([]string, len(found))
for i, p := range found {
ids[i] = p.ID + "/" + asked
}
return provider.Provider{}, "", http.StatusNotFound, fmt.Sprintf("more than one provider may serve %s: name one, as %s", asked, strings.Join(ids, " or "))
}
func dashScopeBase(base string) bool {
return strings.HasSuffix(strings.TrimRight(base, "/"), "/compatible-mode/v1")
}
// realtimeURL is where the provider takes a realtime session for model,
// or why it takes none.
func realtimeURL(p provider.Provider, model string) (string, string) {
base := strings.TrimRight(p.OpenAIBase(), "/")
if base == "" {
return "", p.Name + " has no OpenAI-style API, so no Realtime API"
}
u, err := url.Parse(base)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
return "", p.Name + "'s address isn't one a WebSocket is opened at"
}
if dashScopeBase(base) {
u.Path = strings.TrimSuffix(strings.TrimRight(u.Path, "/"), "/compatible-mode/v1") + "/api-ws/v1/realtime"
} else {
u.Path = strings.TrimRight(u.Path, "/") + "/realtime"
}
q := u.Query()
q.Set("model", model)
u.RawQuery = q.Encode()
return u.String(), ""
}
// dialRealtime opens the session at the provider's realtime address,
// signed as its requests are. Its connection lives as long as ctx; the
// handshake has realtimeDial. A refusal's code is the vendor's.
func (s *Server) dialRealtime(ctx context.Context, r *http.Request, p provider.Provider, u string, subprotocols []string) (*websocket.Conn, int, error) {
ctx = s.metered(p.Via(ctx), p, "") // counted against its MaxRPM (rpm.go)
dctx, cancel := context.WithCancel(ctx)
timer := time.AfterFunc(realtimeDial, cancel)
defer timer.Stop()
req, err := http.NewRequestWithContext(dctx, http.MethodGet, u, nil)
if err != nil {
cancel()
return nil, http.StatusBadRequest, err
}
stampUA(dctx, p, req.Header)
if p.IsRemoteMagpie() {
req.Header.Set("User-Agent", "magpie/"+Version)
passOnCaller(dctx, req)
}
// OpenAI's beta Realtime API asks for its header
if v := r.Header.Get("OpenAI-Beta"); v != "" {
req.Header.Set("OpenAI-Beta", v)
}
if err := p.Sign(dctx, req, provider.Chat, nil); err != nil {
cancel()
return nil, http.StatusBadGateway, err
}
conn, res, err := websocket.Dial(dctx, u, &websocket.DialOptions{
HTTPClient: &http.Client{Transport: s.client.Transport, CheckRedirect: provider.KeepsCredentials},
HTTPHeader: req.Header,
Subprotocols: subprotocols,
})
if err != nil {
timedOut := !timer.Stop() && ctx.Err() == nil
cancel()
host := provider.HostOf(u)
if res != nil && res.StatusCode >= 300 {
var b []byte
if res.Body != nil {
b, _ = io.ReadAll(io.LimitReader(res.Body, 64<<10))
res.Body.Close()
}
hint := ""
if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed {
hint = " — " + p.Name + " may not serve the Realtime API"
}
return nil, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", host, res.StatusCode, http.StatusText(res.StatusCode), vendorSaid(vendorMessage(bytes.TrimSpace(b))), hint)
}
if timedOut {
return nil, http.StatusGatewayTimeout, fmt.Errorf("%s didn't open the session in %s", host, realtimeDial)
}
return nil, http.StatusBadGateway, fmt.Errorf("%s: %v", host, err)
}
// the connection is the session's: cancel ends it with ctx
context.AfterFunc(ctx, cancel)
return conn, http.StatusSwitchingProtocols, nil
}
// realtimeMask masks the client's frames and puts the values back in the
// vendor's.
type realtimeMask struct {
ctx context.Context
m gwmw.Masker
}
// out is a client's frame masked, or the error to hold it back for.
func (rm *realtimeMask) out(b []byte) ([]byte, error) {
got, err := gwmw.Safely(func() []byte {
var hits []gwmw.Hit
switch t := rm.m.(type) {
case gwmw.ContextTeller:
b, hits = t.JSONHitsContext(rm.ctx, b)
case gwmw.Teller:
b, hits = t.JSONHits(b)
default:
b, _ = rm.m.JSON(b)
return b
}
if err := blocked(hitsOf(hits)); err != nil {
panic(err)
}
return b
})
return got, err
}
// in is a vendor's frame with the masked values back.
func (rm *realtimeMask) in(b []byte) []byte {
return []byte(rm.m.Restore(string(b), true))
}
// audioFrame: a frame that carries base64 audio and nothing else, which
// isn't masked (a run of base64 can look like a key) or read for values.
func audioFrame(typ string) bool {
return typ == "input_audio_buffer.append" || strings.HasSuffix(typ, "audio.delta")
}
type realtimeSession struct {
s *Server
r *http.Request
c candidate
asked string
mask *realtimeMask
mu sync.Mutex
total Usage
lastErr string
}
// pipe passes frames both ways until one side ends, then closes the
// other with the same code; it gives the session's status and, for one
// that broke, why.
func (rs *realtimeSession) pipe(ctx context.Context, client, up *websocket.Conn) (int, string) {
type end struct {
fromClient bool
err error
}
ends := make(chan end, 2)
go func() { ends <- end{true, rs.copy(ctx, client, up, true)} }()
go func() { ends <- end{false, rs.copy(ctx, up, client, false)} }()
e := <-ends
code, reason := websocket.CloseStatus(e.err), ""
var ce websocket.CloseError
if errors.As(e.err, &ce) {
reason = ce.Reason
}
status, why := http.StatusOK, ""
host := provider.HostOf(rs.c.p.OpenAIBase())
var held realtimeHeld
switch {
case errors.As(e.err, &held):
// a frame masking held back: the session ends, nothing of it sent
status, why = maskStatus(held.err), held.err.Error()
code, reason = websocket.StatusPolicyViolation, trimReason(why)
case code == -1 || code == websocket.StatusNoStatusRcvd || code == websocket.StatusAbnormalClosure || code == websocket.StatusTLSHandshake:
if e.fromClient {
code, reason = websocket.StatusGoingAway, ""
} else {
status, why = http.StatusBadGateway, host+" ended the session: "+e.err.Error()
code, reason = websocket.StatusInternalError, trimReason(why)
}
case !e.fromClient && code != websocket.StatusNormalClosure && code != websocket.StatusGoingAway:
status, why = http.StatusBadGateway, fmt.Sprintf("%s closed the session %d %s", host, code, reason)
}
// both closed at once: each waits for its peer's close frame
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); client.Close(code, reason) }()
go func() { defer wg.Done(); up.Close(code, reason) }()
wg.Wait()
<-ends
return status, why
}
// trimReason fits a close frame's reason, 123 bytes at most.
func trimReason(s string) string {
if len(s) <= 123 {
return s
}
s = s[:120]
for len(s) > 0 && !utf8Start(s[len(s)-1]) {
s = s[:len(s)-1]
}
if len(s) > 0 {
s = s[:len(s)-1]
}
return s + "…"
}
func utf8Start(b byte) bool { return b&0xC0 != 0x80 }
// realtimeHeld is a client's frame masking wouldn't let go.
type realtimeHeld struct{ err error }
func (h realtimeHeld) Error() string { return h.err.Error() }
// copy passes from's frames to to, masking a client's and counting the
// vendor's usage, until from ends.
func (rs *realtimeSession) copy(ctx context.Context, from, to *websocket.Conn, fromClient bool) error {
for {
typ, b, err := from.Read(ctx)
if err != nil {
return err
}
if typ == websocket.MessageText {
kind := gjson.GetBytes(b, "type").String()
switch {
case audioFrame(kind):
case fromClient && rs.mask != nil:
if b, err = rs.mask.out(b); err != nil {
return realtimeHeld{err}
}
case !fromClient:
rs.heard(kind, b)
if rs.mask != nil {
b = rs.mask.in(b)
}
}
}
if err := to.Write(ctx, typ, b); err != nil {
return err
}
}
}
// heard counts a vendor event: a response.done's usage is recorded as a
// call of its own in the usage ledger, an error kept for the record.
func (rs *realtimeSession) heard(kind string, b []byte) {
switch kind {
case "error":
rs.mu.Lock()
rs.lastErr = gjson.GetBytes(b, "error.message").String()
rs.mu.Unlock()
case "response.done":
u := gjson.GetBytes(b, "response.usage")
if !u.Exists() {
return
}
in, out := int(u.Get("input_tokens").Int()), int(u.Get("output_tokens").Int())
cached := int(u.Get("input_token_details.cached_tokens").Int())
if cached == 0 {
cached = int(u.Get("input_tokens_details.cached_tokens").Int())
}
cached = min(cached, in)
in -= cached // the ledger's input leaves out what was read from the cache
rs.mu.Lock()
rs.total.Input += in
rs.total.Output += out
rs.total.CacheRead += cached
rs.mu.Unlock()
c := rs.c
keyID, keyName := "", ""
if c.p.Account == nil && c.p.Key != "" {
keyID, keyName = provider.KeyID(c.p.Key), c.p.KeyName
}
who := callerOf(rs.r)
status := http.StatusOK
if st := gjson.GetBytes(b, "response.status").String(); st == "failed" {
status = http.StatusBadGateway
}
appendUsage(rs.r, usage.Record{Operation: "realtime", Time: time.Now(), Agent: who.agent, Via: who.via, Provider: c.p.ID, Host: c.p.Where(), Model: c.model, Requested: rs.asked,
ProviderKeyID: keyID, ProviderKeyName: keyName, ProviderAccount: accountOf(c.p),
Input: in, Output: out, CacheRead: cached, Status: status, Session: sessionOf(rs.r.Header)})
}
}
+357
View File
@@ -0,0 +1,357 @@
package gateway
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/coder/websocket"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
)
// rtUp is a realtime vendor: DashScope's /api-ws/v1/realtime and OpenAI's
// /v1/realtime. Each text frame comes back as {"type":"echo","got":…},
// a binary frame as it came, a response.create gets a response.done with
// usage, and {"type":"close.me"} closes the session 1000 "bye".
type rtUp struct {
mu sync.Mutex
opened []*http.Request
frames []string
closed chan websocket.StatusCode // how each session's client side ended
url string
}
func (u *rtUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api-ws/v1/realtime" && r.URL.Path != "/v1/realtime" {
http.Error(w, `{"error":{"message":"no such path"}}`, http.StatusNotFound)
return
}
if r.Header.Get("Authorization") != "Bearer sk-sp-k" {
http.Error(w, `{"error":{"message":"bad key"}}`, http.StatusUnauthorized)
return
}
u.mu.Lock()
u.opened = append(u.opened, r.Clone(context.Background()))
u.mu.Unlock()
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{Subprotocols: []string{"realtime"}})
if err != nil {
return
}
defer c.CloseNow()
ctx := context.Background()
for {
typ, b, err := c.Read(ctx)
if err != nil {
u.closed <- websocket.CloseStatus(err)
return
}
if typ == websocket.MessageBinary {
c.Write(ctx, typ, b)
continue
}
u.mu.Lock()
u.frames = append(u.frames, string(b))
u.mu.Unlock()
switch gjson.GetBytes(b, "type").String() {
case "close.me":
c.Close(websocket.StatusNormalClosure, "bye")
u.closed <- websocket.StatusNormalClosure
return
case "response.create":
c.Write(ctx, websocket.MessageText, []byte(`{"type":"response.audio.delta","delta":"QUJD"}`))
c.Write(ctx, websocket.MessageText, []byte(`{"type":"response.done","response":{"status":"completed","usage":{"input_tokens":100,"output_tokens":20,"input_token_details":{"cached_tokens":40}}}}`))
default:
c.Write(ctx, websocket.MessageText, []byte(`{"type":"echo","got":`+string(b)+`}`))
}
}
}
func (u *rtUp) sessions() int {
u.mu.Lock()
defer u.mu.Unlock()
return len(u.opened)
}
// rtServe has a Token Plan provider at the fake's DashScope base and an
// OpenAI-style one at its /v1, and the gateway served as the real server
// does; every session ends before the test's folders go.
func rtServe(t *testing.T) (*rtUp, *Server, *httptest.Server) {
t.Helper()
fresh(t)
u := &rtUp{closed: make(chan websocket.StatusCode, 16)}
up := httptest.NewServer(u)
t.Cleanup(up.Close)
u.url = up.URL
for _, p := range []provider.Provider{
{ID: "plan", Name: "Plan", Key: "sk-sp-k", Chat: up.URL + "/compatible-mode/v1", Models: []string{"qwen-audio-3.0-realtime-plus"}},
{ID: "oa", Name: "OA", Key: "sk-sp-k", Chat: up.URL + "/v1", Models: []string{"gpt-realtime"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s, ts := sockServer(t)
t.Cleanup(func() {
s.realtimes.end()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
s.realtimes.wait(ctx)
})
return u, s, ts
}
func rtDial(t *testing.T, ts *httptest.Server, path string, h http.Header, protos ...string) (*websocket.Conn, *http.Response, error) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
c, resp, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(ts.URL, "http")+path, &websocket.DialOptions{HTTPHeader: h, Subprotocols: protos})
if err == nil {
t.Cleanup(func() { c.CloseNow() })
}
return c, resp, err
}
func rtRead(t *testing.T, c *websocket.Conn) (websocket.MessageType, string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
typ, b, err := c.Read(ctx)
if err != nil {
t.Fatalf("read: %v", err)
}
return typ, string(b)
}
func rtSend(t *testing.T, c *websocket.Conn, typ websocket.MessageType, s string) {
t.Helper()
if err := c.Write(context.Background(), typ, []byte(s)); err != nil {
t.Fatal(err)
}
}
func rtClosed(t *testing.T, u *rtUp) websocket.StatusCode {
t.Helper()
select {
case st := <-u.closed:
return st
case <-time.After(30 * time.Second):
t.Fatal("the vendor's side never ended")
return 0
}
}
// A Token Plan's realtime model: the session opens at the plan host's
// /api-ws/v1/realtime with the plan's key and the provider's own model id,
// text and audio frames go both ways as they are, a response.done's usage
// is recorded, and the vendor's close reaches the client with its code.
func TestRealtimeTokenPlanSession(t *testing.T) {
u, _, ts := rtServe(t)
c, resp, err := rtDial(t, ts, "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus", nil)
if err != nil {
t.Fatalf("%v %v", err, resp)
}
if u.sessions() != 1 {
t.Fatalf("%d sessions", u.sessions())
}
got := u.opened[0]
if got.URL.Path != "/api-ws/v1/realtime" || got.URL.Query().Get("model") != "qwen-audio-3.0-realtime-plus" {
t.Fatalf("opened %s", got.URL)
}
update := `{"type":"session.update","session":{"modalities":["text","audio"],"voice":"Cherry"}}`
rtSend(t, c, websocket.MessageText, update)
if typ, b := rtRead(t, c); typ != websocket.MessageText || gjson.Get(b, "got").Raw != update {
t.Fatalf("echo %v %s", typ, b)
}
rtSend(t, c, websocket.MessageBinary, "\x00\x01pcm")
if typ, b := rtRead(t, c); typ != websocket.MessageBinary || b != "\x00\x01pcm" {
t.Fatalf("binary %v %q", typ, b)
}
rtSend(t, c, websocket.MessageText, `{"type":"input_audio_buffer.append","audio":"UklGRg=="}`)
rtRead(t, c)
rtSend(t, c, websocket.MessageText, `{"type":"response.create"}`)
if _, b := rtRead(t, c); b != `{"type":"response.audio.delta","delta":"QUJD"}` {
t.Fatalf("delta %s", b)
}
if _, b := rtRead(t, c); gjson.Get(b, "type").String() != "response.done" {
t.Fatalf("done %s", b)
}
rtSend(t, c, websocket.MessageText, `{"type":"close.me"}`)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, _, err = c.Read(ctx)
var ce websocket.CloseError
if !errors.As(err, &ce) || ce.Code != websocket.StatusNormalClosure || ce.Reason != "bye" {
t.Fatalf("the client's session ended %v", err)
}
rtClosed(t, u)
var recs []usage.Record
for i := 0; i < 250; i++ {
if recs = usage.Load(time.Time{}); len(recs) >= 1 {
break
}
time.Sleep(20 * time.Millisecond)
}
if len(recs) != 1 || recs[0].Operation != "realtime" || recs[0].Provider != "plan" || recs[0].Model != "qwen-audio-3.0-realtime-plus" ||
recs[0].Requested != "plan/qwen-audio-3.0-realtime-plus" || recs[0].Input != 60 || recs[0].CacheRead != 40 || recs[0].Output != 20 || recs[0].Status != 200 {
t.Fatalf("usage %+v", recs)
}
}
// An OpenAI-style provider's session opens at base + /realtime; the
// client's subprotocols go on, less one carrying a key, and the vendor's
// choice comes back. A bare id no provider lists goes to the one
// DashScope provider. The client closing ends the vendor's side too.
func TestRealtimeOpenAIStyleAndClientClose(t *testing.T) {
u, _, ts := rtServe(t)
c, resp, err := rtDial(t, ts, "/v1/realtime?model=oa/gpt-realtime", http.Header{"OpenAI-Beta": {"realtime=v1"}}, "realtime", "openai-insecure-api-key.sk-leak")
if err != nil {
t.Fatalf("%v %v", err, resp)
}
got := u.opened[0]
if got.URL.Path != "/v1/realtime" || got.URL.Query().Get("model") != "gpt-realtime" || got.Header.Get("OpenAI-Beta") != "realtime=v1" {
t.Fatalf("opened %s %v", got.URL, got.Header)
}
if p := got.Header.Get("Sec-WebSocket-Protocol"); strings.Contains(p, "sk-leak") || !strings.Contains(p, "realtime") {
t.Fatalf("the vendor was offered %q", p)
}
if c.Subprotocol() != "realtime" {
t.Fatalf("subprotocol %q", c.Subprotocol())
}
c.Close(websocket.StatusNormalClosure, "")
if st := rtClosed(t, u); st != websocket.StatusNormalClosure {
t.Fatalf("the vendor's side ended %d", st)
}
c, resp, err = rtDial(t, ts, "/realtime?model=qwen3-livetranslate-flash-realtime", nil)
if err != nil {
t.Fatalf("%v %v", err, resp)
}
if got := u.opened[1]; got.URL.Path != "/api-ws/v1/realtime" || got.URL.Query().Get("model") != "qwen3-livetranslate-flash-realtime" {
t.Fatalf("opened %s", got.URL)
}
c.Close(websocket.StatusNormalClosure, "")
rtClosed(t, u)
}
// Every guard an HTTP request meets holds a realtime session: no Upgrade
// is told what to send, no model and an unknown one are refused, a web
// page elsewhere, a sandboxed frame (Origin null), a localhost subdomain
// and a rebound name can't open one, a remote caller needs a key, a key
// held to other models is refused, and a vendor's refusal comes back as
// its status. None reaches the vendor but the last.
func TestRealtimeGuards(t *testing.T) {
u, _, ts := rtServe(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
budget.Forget()
keys, secrets := newCaller(t, "Laptop", "Held")
if _, err := access.Update("models-key", access.Change{Key: keys[1].ID, Models: []string{"oa/*"}}); err != nil {
t.Fatal(err)
}
res, err := http.Get(ts.URL + "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus")
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode != http.StatusUpgradeRequired || !strings.Contains(string(b), "WebSocket") {
t.Errorf("a plain GET: %d %s", res.StatusCode, b)
}
remote := func(secret string) http.Header {
h := http.Header{"X-Test-Remote": {"192.168.1.9:5000"}}
if secret != "" {
h.Set("Authorization", "Bearer "+secret)
}
return h
}
const plan = "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus"
refused := func(what, path string, h http.Header, want int) {
t.Helper()
_, resp, err := rtDial(t, ts, path, h)
if err == nil {
t.Errorf("%s opened a session", what)
return
}
if resp == nil || resp.StatusCode != want {
t.Errorf("%s: %v %v, want %d", what, err, resp, want)
}
}
refused("no model", "/v1/realtime", nil, http.StatusBadRequest)
refused("an unknown model", "/v1/realtime?model=nope/x", nil, http.StatusNotFound)
for _, origin := range []string{"https://evil.example", "null", "http://evil.localhost:3425"} {
refused("Origin "+origin, plan, http.Header{"Origin": {origin}}, http.StatusForbidden)
}
_, resp, err := rtDial(t, ts, plan, http.Header{
"X-Test-Host": {"rebind.attacker.example:3425"},
"User-Agent": {"Mozilla/5.0 (Macintosh) Chrome/140"}, "Sec-Fetch-Site": {"same-origin"}, "Sec-Fetch-Mode": {"websocket"},
})
if err == nil || resp == nil || resp.StatusCode < 400 {
t.Errorf("a rebound page: %v %v", err, resp)
}
refused("a remote caller without a key", plan, remote(""), http.StatusUnauthorized)
refused("a key held to other models", plan, remote(secrets[1]), http.StatusForbidden)
if u.sessions() != 0 {
t.Fatalf("a refused session reached the vendor")
}
// a key: served
c, resp, err := rtDial(t, ts, plan, remote(secrets[0]))
if err != nil {
t.Fatalf("keyed: %v %v", err, resp)
}
c.Close(websocket.StatusNormalClosure, "")
rtClosed(t, u)
// the vendor refusing the key: its status and message
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "sk-sp-wrong", Chat: u.url + "/compatible-mode/v1", Models: []string{"qwen-audio-3.0-realtime-plus"}}); err != nil {
t.Fatal(err)
}
_, resp, err = rtDial(t, ts, plan, nil)
if err == nil || resp == nil || resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("a refused key: %v %v", err, resp)
}
b, _ = io.ReadAll(resp.Body)
if !strings.Contains(string(b), "bad key") {
t.Errorf("the vendor's message: %s", b)
}
}
// With secrets kept, a client's text frame goes out masked and the
// vendor's frames get the values back; an audio frame goes as it is.
func TestRealtimeMasked(t *testing.T) {
u, _, ts := rtServe(t)
if err := settings.Save(settings.Settings{Redact: true}); err != nil {
t.Fatal(err)
}
c, resp, err := rtDial(t, ts, "/v1/realtime?model=plan/qwen-audio-3.0-realtime-plus", nil)
if err != nil {
t.Fatalf("%v %v", err, resp)
}
secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20)
rtSend(t, c, websocket.MessageText, `{"type":"conversation.item.create","item":{"type":"message","role":"user","content":[{"type":"input_text","text":"key `+secret+`"}]}}`)
_, b := rtRead(t, c)
if !strings.Contains(b, secret) {
t.Errorf("the echo didn't get the value back: %s", b)
}
u.mu.Lock()
sent := u.frames[0]
u.mu.Unlock()
if strings.Contains(sent, secret) || !strings.Contains(sent, "key ") {
t.Fatalf("the vendor was sent %s", sent)
}
c.Close(websocket.StatusNormalClosure, "")
rtClosed(t, u)
}