Skip to content

feat(go)!: redesign HTTP serving API with genkithttp and genkithttp/exp - #7443

Open
apascal07 wants to merge 1 commit into
ap/go-v2from
ap/go-v2-http-api
Open

apascal07 wants to merge 1 commit into
ap/go-v2from
ap/go-v2-http-api

Conversation

@apascal07

Copy link
Copy Markdown
Collaborator

Redesigns Genkit Go v2 HTTP serving on top of standard net/http (http.Handler), replacing genkit.Handler, genkit.HandlerFunc, go/plugins/server, genkit/exp route builders, and core.ContextProvider with two dedicated packages: stable genkithttp (github.com/genkit-ai/genkit-go/v2/genkithttp) and experimental genkithttp/exp (github.com/genkit-ai/genkit-go/v2/genkithttp/exp). Auth and request-scoped values now flow through standard HTTP middleware into r.Context(), paired with a generic genkit.NewContextKey[T] bridge for Dev UI (--context) and Dotprompt interoperability and an exported genkithttp.WriteError helper. Every wire protocol bug from v1 server.go (chunked/HTTP2 body decoding, Accept media-range parsing, HTTP/2-illegal SSE headers, wrapped ResponseWriter flushing, trace headers on SSE, heartbeats, and durable stream timeouts) is fixed, all callers/samples/plugins are migrated, and go/MIGRATION.md is updated with a migration section.

HTTP serving moves to genkithttp and genkithttp/exp

Stable HTTP serving lives in genkithttp, avoiding collision with stdlib net/http and decoupling the root genkit package from HTTP transport concerns. Experimental agent routing lives in genkithttp/exp (commonly aliased genkithttpx), keeping stable genkithttp decoupled from ai/exp. Both HandleAction and HandleAgent are package-level functions for consistency with the rest of Genkit Go.

Before:

mux := http.NewServeMux()
mux.HandleFunc("POST /story", genkit.Handler(storyFlow))
for _, r := range genkitx.AllAgentRoutes(g) {
	mux.HandleFunc(r.Pattern(), r.Handler())
}
log.Fatal(server.Start(ctx, "127.0.0.1:8080", mux))

After:

api := genkithttp.NewMux()
genkithttp.HandleAction(api, storyFlow)
genkithttpx.HandleAgent(api, weatherAgent)

mux := http.NewServeMux()
mux.HandleFunc("GET /health", healthHandler)
mux.Handle("/api/", http.StripPrefix("/api", requireAuth(api)))

handler := genkithttp.CORS(genkithttp.CORSOptions{
	AllowedOrigins: []string{"https://myapp.dev"},
})(mux)
log.Fatal(genkithttp.ListenAndServe(ctx, "", handler))

Mux implements http.Handler with strict exact-match routing (including action names with slashes like googleai/gemini-flash-latest): unknown paths return JSON 404 Not Found, and matched paths called with a non-POST method return JSON 405 Method Not Allowed with Allow: POST. Mux.Routes() returns a deterministic snapshot of mounted Route values (Method, Path, Action, Handler, Pattern()) for native per-route registration in Gin, Echo, Chi, or http.ServeMux.

genkithttpx.HandleAgent[S] builds directly on genkithttp.HandleAction and mounts the turn route alongside applicable companion routes (/getSnapshot, /waitForSnapshot, /abort), with opt-out options (HideGetSnapshot, HideWaitForSnapshot, HideAbort), WithPath, and WithRouteOptions (applying WithStreamManager only to the primary turn route).

Standard net/http middleware and ContextKey[T] replace ContextProvider

genkit.WithContextProviders, core.ContextProvider, and core.RequestData are deleted. Authentication and request-scoped values flow natively through standard net/http middleware into r.Context(), reaching flows, tools, prompts, SessionStore hooks, and StreamManager implementations.

Before:

authProvider, err := firebase.ContextProvider(ctx, g, policy)
mux.HandleFunc("POST /story", genkit.Handler(storyFlow,
	genkit.WithContextProviders(authProvider),
))

After:

var userKey = genkit.NewContextKey[User]("auth")

func requireAuth(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := verifyBearerToken(r.Context(), r.Header.Get("Authorization"))
		if err != nil {
			genkithttp.WriteError(w, status.PublicErrorf(status.ErrUnauthenticated, "sign in required"))
			return
		}
		next.ServeHTTP(w, r.WithContext(userKey.WithValue(r.Context(), user)))
	})
}

core.NewContextKey[T](name) (re-exported as genkit.NewContextKey[T]) retrieves typed values stored via WithValue with zero JSON overhead, and falls back to JSON-unmarshaling core.FromContext(ctx)[name] when flows run through the Dev UI or CLI --context. Plain Go context.WithValue continues to work natively. plugins/firebase replaces ContextProvider with firebase.AuthMiddleware and firebase.AuthKey.

Wire protocol fixes and durable streaming hardening

  • Chunked & HTTP/2 request bodies: DecodeRequest reads r.Body whenever r.Body != nil && r.Body != http.NoBody (fixing the v1 r.ContentLength > 0 bug that silently dropped bodies when ContentLength == -1), enforces WithMaxBodyBytes (default 10 MiB, returning HTTP 413), treats io.EOF as an empty request, and returns HTTP 400 on malformed JSON.
  • Method & media-range compliance: Non-POST requests return 405 with Allow: POST. WantsStream parses all Accept headers for media type text/event-stream (ignoring parameters such as ; charset=utf-8 or ;q=0.9) and validates ?stream=<bool> (returning 400 on invalid values).
  • HTTP/2-safe SSE & wrapped writers: SSE responses emit Content-Type: text/event-stream, Cache-Control: no-cache, no-transform, and X-Accel-Buffering: no (dropping RFC 9113-forbidden Connection and Transfer-Encoding headers). SSEWriter uses http.NewResponseController to clear write deadlines and flush through middleware-wrapped ResponseWriter implementations.
  • Keepalive heartbeats & trace headers: Thread-safe : keepalive\n\n frames are emitted every WithHeartbeat interval (default 15s, 0 disables). X-Genkit-Trace-Id and X-Genkit-Span-Id are written on both unary and SSE responses (via tracing.WithTelemetryCallback before committing SSE headers).
  • Pre-stream vs. mid-stream error handling: Request decoding, ?stream= parsing, and bidi init checks run before committing SSE headers. WithOnError receives the original unredacted error on both pre-stream and mid-stream failures; WithErrorEncoder (default WriteError) runs only on pre-stream failures while mid-stream failures emit redacted data: {"error": ...} frames.
  • Durable streaming hardening: r.Context() (including auth/tenant values) propagates to StreamManager.Open and StreamManager.Subscribe. Detached durable runs detach cleanly from the HTTP ResponseWriter on client disconnect and are bounded by WithStreamTimeout (default 10m).
  • Fail-fast construction: NewHandler, NewMux, HandleAction, and HandleAgent panic immediately on nil actions/agents/muxes, invalid options/paths, or duplicate routes.

Standalone ListenAndServe and CORS replace plugins/server

plugins/server is deleted and removed from go.work and samples/go.mod. genkithttp.ListenAndServe replaces server.Start, defaulting empty addresses to 0.0.0.0:$PORT (or 0.0.0.0:3400), setting ReadHeaderTimeout (default 10s) while leaving WriteTimeout unset (0) for long-lived SSE streams, and draining in-flight requests gracefully on ctx cancellation or SIGINT/SIGTERM (default 30s). genkithttp.CORS provides composable net/http CORS middleware pre-configured with Genkit's request and exposed headers.

API surface

// Added: package genkithttp (github.com/genkit-ai/genkit-go/v2/genkithttp)
const (
	HeaderTraceID  = "X-Genkit-Trace-Id"
	HeaderSpanID   = "X-Genkit-Span-Id"
	HeaderStreamID = "X-Genkit-Stream-Id"
)
DefaultAllowedHeaders() []string
DefaultExposedHeaders() []string
NewHandler(a api.Action, opts ...HandlerOption) http.Handler
type Mux struct{ ... }
NewMux(opts ...MuxOption) *Mux
(*Mux).ServeHTTP(w http.ResponseWriter, r *http.Request)
(*Mux).Routes() []Route
HandleAction(m *Mux, a api.Action, opts ...RouteOption)
type Route struct { Method, Path, Action string; Handler http.Handler }
(Route).Pattern() string
type HandlerOption, MuxOption, RouteOption, SharedOption, ServerOption
WithStreamManager(sm streaming.StreamManager) SharedOption
WithMaxBodyBytes(n int64) SharedOption
WithHeartbeat(d time.Duration) SharedOption
WithStreamTimeout(d time.Duration) SharedOption
WithOnError(fn func(ctx context.Context, r *http.Request, err error)) SharedOption
WithErrorEncoder(fn func(w http.ResponseWriter, r *http.Request, err error)) SharedOption
WithBasePath(prefix string) MuxOption
WithPath(path string) RouteOption
type CORSOptions struct{ ... }
CORS(opts CORSOptions) func(http.Handler) http.Handler
WithShutdownTimeout(d time.Duration) ServerOption
WithReadHeaderTimeout(d time.Duration) ServerOption
ListenAndServe(ctx context.Context, addr string, h http.Handler, opts ...ServerOption) error
type Request struct { Data, Init json.RawMessage }
DecodeRequest(w http.ResponseWriter, r *http.Request, maxBytes int64) (*Request, error)
WantsStream(r *http.Request) (bool, error)
WriteResult(w http.ResponseWriter, result any) error
WriteError(w http.ResponseWriter, err error)
type SSEWriter struct{ ... } // NewSSEWriter, Start, Started, WriteMessage, WriteResult, WriteError, WriteComment, StartHeartbeat, Close

// Added: package exp (github.com/genkit-ai/genkit-go/v2/genkithttp/exp)
type AgentOption
WithPath(path string) AgentOption
HideGetSnapshot() AgentOption
HideWaitForSnapshot() AgentOption
HideAbort() AgentOption
WithRouteOptions(opts ...genkithttp.RouteOption) AgentOption
HandleAgent[S any](m *genkithttp.Mux, agent *aix.Agent[S], opts ...AgentOption)

// Added: core & genkit
type core.ContextKey[T any] // re-exported as genkit.ContextKey[T]
core.NewContextKey[T any](name string) ContextKey[T] // re-exported as genkit.NewContextKey[T]
(ContextKey[T]).Name() string
(ContextKey[T]).WithValue(ctx context.Context, val T) context.Context
(ContextKey[T]).FromContext(ctx context.Context) (T, bool)

// Changed: plugins/firebase
firebase.AuthKey // genkit.ContextKey[*auth.Token]("auth")
firebase.AuthPolicy = func(ctx context.Context, token AuthContext, r *http.Request) error
firebase.AuthMiddleware(ctx context.Context, g *genkit.Genkit, policy AuthPolicy) (func(http.Handler) http.Handler, error)

// Deleted
genkit.Handler, genkit.HandlerFunc, genkit.HandlerOption, genkit.WithContextProviders, genkit.WithStreamManager
core.ContextProvider, core.RequestData
genkitx.Route, genkitx.AgentRoutes, genkitx.AllAgentRoutes, genkitx.FlowRoutes, genkitx.AllFlowRoutes
firebase.ContextProvider

// Deleted plugins
plugins/server

What is deliberately left out

  • No framework-specific router plugins. Building on http.Handler and Mux.Routes() lets net/http, Chi, Gin, Echo, and Gorilla mount Genkit routes directly without maintaining adapter modules.
  • No Go 1.27 generic methods on *Mux. HandleAction and HandleAgent[S] are package-level functions for consistency with the rest of Genkit Go until generic methods are adopted across the SDK.

@github-actions github-actions Bot added docs Improvements or additions to documentation go labels Dec 3, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread go/genkithttp/cors.go
Comment on lines +86 to +96
if allowCredentials && origin != "" {
allowOrigin = origin
varyOrigin = true
} else {
allowOrigin = "*"
}
} else if origin != "" && slices.Contains(allowedOrigins, origin) {
allowOrigin = origin
varyOrigin = true
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

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 genkit-bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few comments

Details

Run d268058f-08c3-4e98-b020-47db9721100b · Cloud Run logs · Dashboard

Comment thread go/genkithttp/handler.go
}
done := make(chan runOutcome, 1)

go func() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread go/genkithttp/handler.go
Comment on lines +255 to +259
if runErr != nil {
_ = durableStream.Error(runCtx, runErr)
} else {
_ = durableStream.Done(runCtx, res.Output)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread go/core/context.go
Comment on lines +88 to +93
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})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread go/genkithttp/mux.go
Comment on lines +156 to +162
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Comment thread go/genkithttp/cors.go
Comment on lines +97 to +101
if allowOrigin != "" {
w.Header().Set("Access-Control-Allow-Origin", allowOrigin)
if varyOrigin {
w.Header().Add("Vary", "Origin")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread go/genkithttp/wire.go
if err := s.startLocked(); err != nil {
return err
}
if _, err := fmt.Fprintf(s.w, ": %s\n\n", comment); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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 {

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation go

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants