Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request migrates HTTP serving from the core genkit package and the plugins/server plugin to the new framework-agnostic genkithttp and genkithttp/exp packages, introducing a new Mux, NewHandler, and ListenAndServe utility. It also adds typed ContextKeys for request-scoped context propagation. A security issue was identified in the new CORS middleware, where reflecting the Origin header when AllowCredentials is enabled with a wildcard origin configuration allows unauthorized credentialed cross-origin requests.
| if allowCredentials && origin != "" { | ||
| allowOrigin = origin | ||
| varyOrigin = true | ||
| } else { | ||
| allowOrigin = "*" | ||
| } | ||
| } else if origin != "" && slices.Contains(allowedOrigins, origin) { | ||
| allowOrigin = origin | ||
| varyOrigin = true | ||
| } | ||
|
|
There was a problem hiding this comment.
Reflecting the Origin header when AllowCredentials is enabled and AllowedOrigins contains "*" (wildcard) creates a security vulnerability. It allows any third-party website to make credentialed cross-origin requests to this server, bypassing the browser's same-origin policy.
To prevent this, wildcard origins should not be reflected when credentials are allowed. We should prioritize explicit origin checks first, and only fall back to wildcard matching if credentials are not enabled.
if origin != "" && slices.Contains(allowedOrigins, origin) {
allowOrigin = origin
varyOrigin = true
} else if allowAll {
if allowCredentials {
allowOrigin = ""
} else {
allowOrigin = "*"
}
}
genkit-bot
left a comment
There was a problem hiding this comment.
A few comments
Details
Run d268058f-08c3-4e98-b020-47db9721100b · Cloud Run logs · Dashboard
| } | ||
| done := make(chan runOutcome, 1) | ||
|
|
||
| go func() { |
There was a problem hiding this comment.
[Blocker] Unlike the previous inline runWithDurableStreaming (where net/http.Server recovered per-request panics), serveDurableStream executes wire.RunActionWithOptionalInit in a new goroutine without recover(). Because tracing.RunInNewSpan re-panics and core.Action.RunJSON does not recover panics, any panic inside a durable-streaming flow will crash the entire server process instead of failing the request.
Add a deferred recover() inside this goroutine that converts the panic into status.Errorf(status.ErrPanic, ...) (matching core/bidi_action.go), records it on durableStream.Error, and sends the error on done so ServeHTTP does not hang waiting for an outcome.
| if runErr != nil { | ||
| _ = durableStream.Error(runCtx, runErr) | ||
| } else { | ||
| _ = durableStream.Done(runCtx, res.Output) | ||
| } |
There was a problem hiding this comment.
[Blocker] When WithStreamTimeout expires, runCtx is already done (context.DeadlineExceeded), so passing runCtx to durableStream.Error causes context-aware backends such as FirestoreStreamManager.Error (docRef.Update(ctx, ...)) to fail immediately. The terminal error event and updated expiresAt are never persisted, leaving reconnecting subscribers hanging until storage-side timeout.
Derive a fresh context from context.WithoutCancel(runCtx) (with a short bounded timeout) when calling durableStream.Error and durableStream.Done so request values still propagate while the terminal write can complete. It is also worth logging runErr (and persistence failures) when the client has already disconnected (case <-ctx.Done():), since nobody reads done on that path.
| func (k ContextKey[T]) WithValue(ctx context.Context, val T) context.Context { | ||
| if k.key == nil { | ||
| panic("core.ContextKey.WithValue: zero ContextKey; construct with NewContextKey") | ||
| } | ||
| return context.WithValue(ctx, k.key, contextKeyValue[T]{val: val}) | ||
| } |
There was a problem hiding this comment.
[Blocker] ContextKey.WithValue only writes under k.key, whereas Dotprompt rendering (renderDotpromptToMessages in go/ai/prompt.go) reads only core.FromContext(ctx). Because firebase.AuthMiddleware now stores the verified token via AuthKey.WithValue instead of populating core.ActionContext, Dotprompt templates accessing the auth context key (or any other named ContextKey) over HTTP will no longer see those values, contradicting the Dotprompt interoperability documented on ContextKey and genkit.NewContextKey.
If named ContextKey values are meant to be visible to Dotprompt templates, consider attaching a lightweight immutable (name, val) chain in WithValue when k.name != "" and merging it in renderDotpromptToMessages (keeping ContextKey.FromContext isolated between distinct keys with the same name). Otherwise, clarify the one-way Dev UI fallback in the docs and keep AuthMiddleware populating ActionContext if Dotprompt template access is required.
| func (m *Mux) writeNotFound(w http.ResponseWriter, r *http.Request) { | ||
| err := status.PublicErrorf(status.ErrNotFound, "not found") | ||
| if m.cfg.onError != nil { | ||
| m.cfg.onError(r.Context(), r, err) | ||
| } | ||
| m.cfg.encodeError(w, r, err) | ||
| } |
There was a problem hiding this comment.
[Blocker] Mux.writeNotFound returns a JSON wire.Error ({"status":"NOT_FOUND","message":"not found"}), which breaks ai/exp's httpTransport.responseError (go/ai/exp/remote.go) missing-route detection. responseError decodes any application/json wire.Error as an action-level NOT_FOUND and only maps non-JSON router 404s to UNIMPLEMENTED.
When an agent is served via genkithttp.Mux and genkithttpx.HandleAgent without /abort (non-abortable store or HideAbort) or without /getSnapshot (HideGetSnapshot), NewRemoteAgent will now receive NOT_FOUND instead of UNIMPLEMENTED. In go/middleware/exp/agents_async.go, NOT_FOUND on snapshot reads is interpreted as "no record of this task exists, delegate again" rather than an unsupported route. Please reconcile Mux's missing-route response with remote.go and add a test covering a remote agent calling an unmounted companion route on genkithttp.Mux.
| if allowOrigin != "" { | ||
| w.Header().Set("Access-Control-Allow-Origin", allowOrigin) | ||
| if varyOrigin { | ||
| w.Header().Add("Vary", "Origin") | ||
| } |
There was a problem hiding this comment.
When an explicit AllowedOrigins allowlist is configured (!allowAll), the response varies by Origin even when the request's Origin does not match or is absent. Because Vary: Origin is only added inside if allowOrigin != "", a shared cache or CDN can cache a headerless response for a same-origin or disallowed-origin request (such as a GET or OPTIONS route on the wrapped outer mux) and serve it to an allowed origin without CORS headers. Adding Vary: Origin whenever !allowAll avoids that cache issue.
| if err := s.startLocked(); err != nil { | ||
| return err | ||
| } | ||
| if _, err := fmt.Fprintf(s.w, ": %s\n\n", comment); err != nil { |
There was a problem hiding this comment.
WriteComment is an exported helper, so interpolating comment directly into ": %s\n\n" allows any \r or \n in comment to break out of the SSE comment line and inject arbitrary SSE fields (data:, event:, id:). Normalizing line breaks keeps multi-line or untrusted comments safe on the wire.
| if _, err := fmt.Fprintf(s.w, ": %s\n\n", comment); err != nil { | |
| sanitized := strings.NewReplacer("\r\n", "\n: ", "\r", "\n: ", "\n", "\n: ").Replace(comment) | |
| if _, err := fmt.Fprintf(s.w, ": %s\n\n", sanitized); err != nil { |
Redesigns Genkit Go v2 HTTP serving on top of standard
net/http(http.Handler), replacinggenkit.Handler,genkit.HandlerFunc,go/plugins/server,genkit/exproute builders, andcore.ContextProviderwith two dedicated packages: stablegenkithttp(github.com/genkit-ai/genkit-go/v2/genkithttp) and experimentalgenkithttp/exp(github.com/genkit-ai/genkit-go/v2/genkithttp/exp). Auth and request-scoped values now flow through standard HTTP middleware intor.Context(), paired with a genericgenkit.NewContextKey[T]bridge for Dev UI (--context) and Dotprompt interoperability and an exportedgenkithttp.WriteErrorhelper. Every wire protocol bug from v1server.go(chunked/HTTP2 body decoding,Acceptmedia-range parsing, HTTP/2-illegal SSE headers, wrappedResponseWriterflushing, trace headers on SSE, heartbeats, and durable stream timeouts) is fixed, all callers/samples/plugins are migrated, andgo/MIGRATION.mdis updated with a migration section.HTTP serving moves to
genkithttpandgenkithttp/expStable HTTP serving lives in
genkithttp, avoiding collision with stdlibnet/httpand decoupling the rootgenkitpackage from HTTP transport concerns. Experimental agent routing lives ingenkithttp/exp(commonly aliasedgenkithttpx), keeping stablegenkithttpdecoupled fromai/exp. BothHandleActionandHandleAgentare package-level functions for consistency with the rest of Genkit Go.Before:
After:
Muximplementshttp.Handlerwith strict exact-match routing (including action names with slashes likegoogleai/gemini-flash-latest): unknown paths return JSON404 Not Found, and matched paths called with a non-POSTmethod return JSON405 Method Not AllowedwithAllow: POST.Mux.Routes()returns a deterministic snapshot of mountedRoutevalues (Method,Path,Action,Handler,Pattern()) for native per-route registration in Gin, Echo, Chi, orhttp.ServeMux.genkithttpx.HandleAgent[S]builds directly ongenkithttp.HandleActionand mounts the turn route alongside applicable companion routes (/getSnapshot,/waitForSnapshot,/abort), with opt-out options (HideGetSnapshot,HideWaitForSnapshot,HideAbort),WithPath, andWithRouteOptions(applyingWithStreamManageronly to the primary turn route).Standard
net/httpmiddleware andContextKey[T]replaceContextProvidergenkit.WithContextProviders,core.ContextProvider, andcore.RequestDataare deleted. Authentication and request-scoped values flow natively through standardnet/httpmiddleware intor.Context(), reaching flows, tools, prompts,SessionStorehooks, andStreamManagerimplementations.Before:
After:
core.NewContextKey[T](name)(re-exported asgenkit.NewContextKey[T]) retrieves typed values stored viaWithValuewith zero JSON overhead, and falls back to JSON-unmarshalingcore.FromContext(ctx)[name]when flows run through the Dev UI or CLI--context. Plain Gocontext.WithValuecontinues to work natively.plugins/firebasereplacesContextProviderwithfirebase.AuthMiddlewareandfirebase.AuthKey.Wire protocol fixes and durable streaming hardening
DecodeRequestreadsr.Bodywheneverr.Body != nil && r.Body != http.NoBody(fixing the v1r.ContentLength > 0bug that silently dropped bodies whenContentLength == -1), enforcesWithMaxBodyBytes(default 10 MiB, returning HTTP413), treatsio.EOFas an empty request, and returns HTTP400on malformed JSON.POSTrequests return405withAllow: POST.WantsStreamparses allAcceptheaders for media typetext/event-stream(ignoring parameters such as; charset=utf-8or;q=0.9) and validates?stream=<bool>(returning400on invalid values).Content-Type: text/event-stream,Cache-Control: no-cache, no-transform, andX-Accel-Buffering: no(dropping RFC 9113-forbiddenConnectionandTransfer-Encodingheaders).SSEWriteruseshttp.NewResponseControllerto clear write deadlines and flush through middleware-wrappedResponseWriterimplementations.: keepalive\n\nframes are emitted everyWithHeartbeatinterval (default15s,0disables).X-Genkit-Trace-IdandX-Genkit-Span-Idare written on both unary and SSE responses (viatracing.WithTelemetryCallbackbefore committing SSE headers).?stream=parsing, and bidiinitchecks run before committing SSE headers.WithOnErrorreceives the original unredacted error on both pre-stream and mid-stream failures;WithErrorEncoder(defaultWriteError) runs only on pre-stream failures while mid-stream failures emit redacteddata: {"error": ...}frames.r.Context()(including auth/tenant values) propagates toStreamManager.OpenandStreamManager.Subscribe. Detached durable runs detach cleanly from the HTTPResponseWriteron client disconnect and are bounded byWithStreamTimeout(default10m).NewHandler,NewMux,HandleAction, andHandleAgentpanic immediately on nil actions/agents/muxes, invalid options/paths, or duplicate routes.Standalone
ListenAndServeandCORSreplaceplugins/serverplugins/serveris deleted and removed fromgo.workandsamples/go.mod.genkithttp.ListenAndServereplacesserver.Start, defaulting empty addresses to0.0.0.0:$PORT(or0.0.0.0:3400), settingReadHeaderTimeout(default10s) while leavingWriteTimeoutunset (0) for long-lived SSE streams, and draining in-flight requests gracefully onctxcancellation orSIGINT/SIGTERM(default30s).genkithttp.CORSprovides composablenet/httpCORS middleware pre-configured with Genkit's request and exposed headers.API surface
What is deliberately left out
http.HandlerandMux.Routes()letsnet/http, Chi, Gin, Echo, and Gorilla mount Genkit routes directly without maintaining adapter modules.*Mux.HandleActionandHandleAgent[S]are package-level functions for consistency with the rest of Genkit Go until generic methods are adopted across the SDK.