feat(task): pass client request headers to task plugin drivers

Driver hooks saw only the Content-Type and Accept headers of the client
request. ctx.requestHeaders now carries every client header, with the
first value under its canonical name, except the headers that carry
gateway credentials: Authorization, Proxy-Authorization, Cookie,
X-Api-Key, X-Goog-Api-Key and Mj-Api-Secret. The gateway still forwards
none of them upstream; a driver copies only the headers its vendor
defines into its request.
This commit is contained in:
CaIon committed 2026-10-22 16:23:18 +08:00
1 parent 556517fa57
commit dbe97beb9b
4 files changed
+40 -1

No files matched your search

+1 -1
View File
@@ -59,7 +59,7 @@ export type UsageExample = {label: string; facts: Readonly<Record<string, string
export type UsageProfile = {models: readonly string[]; schema: Readonly<Record<string, UsageFieldSchema>>; examples?: readonly UsageExample[]};
export interface Meta {requiredCapabilities?: readonly HostCapability[]; submitResponseTypes?: readonly ("json" | "sse")[]; sortPriority?: number; website?: string; apiVersion: 1; key: string; name: string; icon?: string; description?: LocalizedText; version: string; author: {name: string; url?: string}; baseUrl?: string; channelTypes?: readonly number[]; models: readonly string[]; fetchMode: "per_task" | "batch"; allowedHosts?: readonly string[]; upstreams?: readonly UpstreamKind[]; routes?: readonly NativeRoute[]; protocols?: readonly ProtocolClaim[]; usageSchema?: Readonly<Record<string, UsageFieldSchema>>; usageExamples?: readonly UsageExample[]; usageProfiles?: readonly UsageProfile[]; auth?: "none" | "api_key" | "vertex_oauth" | {type: "none" | "api_key" | "oauth2_jwt"}}
export interface TaskView {task_id: string; status: string; progress?: string; fail_reason?: string; created_at?: number; updated_at?: number; data?: unknown; properties?: Record<string, unknown>}
export interface DriverContext {requestBody: unknown; requestHeaders: Readonly<Record<string, string>>; action: string; model: string; upstreamModel: string; baseUrl: string; apiKey?: string; authHeader: string; upstream: UpstreamContext; files: readonly FileReference[]; publicTaskId: string; originTasks?: readonly {taskId: string; upstreamTaskId: string; action: string; status: string; data: unknown}[]}
export interface DriverContext {requestBody: unknown; /** Client request headers, first value under the canonical name, without gateway credentials; Content-Type and Accept are always present. Older gateways pass only those two. */ requestHeaders: Readonly<Record<string, string>>; action: string; model: string; upstreamModel: string; baseUrl: string; apiKey?: string; authHeader: string; upstream: UpstreamContext; files: readonly FileReference[]; publicTaskId: string; originTasks?: readonly {taskId: string; upstreamTaskId: string; action: string; status: string; data: unknown}[]}
export interface TaskQueryContext {taskId: string; publicTaskId: string; action: string; model: string; upstreamModel: string; baseUrl: string; apiKey?: string; authHeader: string; auth?: unknown; upstream: UpstreamContext; data: unknown; state: unknown}
export interface BatchQueryContext {baseUrl: string; apiKey?: string; authHeader: string; auth?: unknown; upstream: UpstreamContext; tasks: readonly TaskQueryContext[]}
export type HookHTTPResponse = {readonly status: number; readonly headers: Readonly<Record<string, string>>}
+2
View File
@@ -471,6 +471,8 @@ The persisted field remains `task.data`; there is no `task.raw` alias. Driver ho
`ctx.upstream` is `{kind: "vendor"}` or `{kind: "new_api"}` on `DriverContext`, `TaskQueryContext`, `BatchQueryContext`, and the `buildContentRequest` context, for submission and for background polling alike. `new_api` means the executing channel is a type-60 New API channel, so the same plugin on the upstream gateway answers. In that case the driver prefixes the URLs it builds with its own native-route prefix (doubao `/doubao`, alibaba `/ali`, kling `/kling`, jimeng `/jimeng`), and the host has already set `authHeader` to `Bearer <channel key>` and `apiKey` to the channel key for every `meta.auth` type: the channel key of a New API channel is the gateway token, so the vendor auth scheme (`oauth2_jwt` token exchange, a vendor JWT built from `ak|sk`) is not run. With `vendor` nothing changes. The response the driver reads back is what its own native presenter renders on the gateway, where the host has replaced the private upstream id in `id` / `task_id` / `taskId` fields with the gateway's public task id; `parseSubmitResponse` must accept that shape, and the query URL must resolve on the plugin's own `query` route with that id. Kling and jimeng keep their `sk-` key-prefix heuristic for legacy channels pointed at a gateway; the explicit signal takes precedence when it says `new_api`. `ctx.upstream` is an additive apiVersion 1 extension; drivers must treat a missing field as `vendor`.
`ctx.requestHeaders` on `DriverContext` holds the client's request headers, the first value of each under its canonical name (`TypeSafe-Danger-Zone-Long-Context` arrives as `Typesafe-Danger-Zone-Long-Context`), so drivers compare names case-insensitively. `Content-Type` and `Accept` are always present, empty when the client sent none. The headers that carry gateway credentials (`Authorization`, `Proxy-Authorization`, `Cookie`, `X-Api-Key`, `X-Goog-Api-Key`, `Mj-Api-Secret`) are left out. The host forwards none of them upstream; a driver copies only the headers its vendor defines into its request descriptor. Polling contexts have no client request and carry no headers. Gateways released before this extension pass only `Content-Type` and `Accept`.
## Polling contract
Query and parse hooks use `TaskQueryContext`, not `DriverContext`. The host rebuilds that context from the persisted task row. There is no query-side `requestBody`.
+10
View File
@@ -98,6 +98,10 @@ type taskResult struct {
var taskArtifactKeyPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$`)
// gatewayCredentialHeaders carry the client's gateway credentials. Driver
// hooks receive every other request header.
var gatewayCredentialHeaders = []string{"Authorization", "Proxy-Authorization", "Cookie", "X-Api-Key", "X-Goog-Api-Key", "Mj-Api-Secret"}
const maxTaskArtifacts = 64
// maxTaskPluginPersistedJSONBytes is the shared ceiling for taskData and plugin state.
@@ -1571,6 +1575,12 @@ func (a *TaskAdaptor) submitContext(c *gin.Context, info *relaycommon.RelayInfo)
routeRequest.Query[key] = append([]string(nil), values...)
}
}
for name, values := range c.Request.Header {
name = http.CanonicalHeaderKey(name)
if len(values) > 0 && !slices.Contains(gatewayCredentialHeaders, name) {
requestHeaders[name] = values[0]
}
}
requestHeaders["Content-Type"] = c.GetHeader("Content-Type")
requestHeaders["Accept"] = c.GetHeader("Accept")
if strings.Contains(c.GetHeader("Content-Type"), "multipart/form-data") {
@@ -1703,6 +1703,33 @@ func TestSubmitContextOriginTasksNilDataOnInvalidJSON(t *testing.T) {
assert.Nil(t, originTasks[0]["data"])
}
func TestSubmitContextExposesClientHeadersWithoutCredentials(t *testing.T) {
plugin, err := pluginruntime.NewRegistry().Register(mockPlugin, pluginruntime.Options{})
require.NoError(t, err)
adaptor := New(plugin)
info := &relaycommon.RelayInfo{ChannelMeta: &relaycommon.ChannelMeta{ChannelBaseUrl: "https://provider.example"}, TaskRelayInfo: &relaycommon.TaskRelayInfo{}}
adaptor.Init(info)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/vendor/v1/jobs", nil)
c.Request.Header.Set("Content-Type", "application/json")
c.Request.Header.Set("TypeSafe-Danger-Zone-Long-Context", "true")
c.Request.Header.Add("X-Trace", "first")
c.Request.Header.Add("X-Trace", "second")
for _, name := range []string{"Authorization", "Proxy-Authorization", "Cookie", "X-Api-Key", "X-Goog-Api-Key", "Mj-Api-Secret"} {
c.Request.Header.Set(name, "gateway-secret")
}
headers := adaptor.submitContext(c, info)["requestHeaders"]
assert.Equal(t, map[string]string{
"Content-Type": "application/json",
"Accept": "",
"Typesafe-Danger-Zone-Long-Context": "true",
"X-Trace": "first",
}, headers)
assert.Equal(t, headers, adaptor.submitContext(nil, info)["requestHeaders"], "hooks without a client request see the submission headers")
}
func TestSubmitContextNormalizesRequestBodyOnEveryCall(t *testing.T) {
plugin, err := pluginruntime.NewRegistry().Register(mockPlugin, pluginruntime.Options{})
require.NoError(t, err)