|
| 1 | +package intercept |
| 2 | + |
| 3 | +import "net/http" |
| 4 | + |
| 5 | +// hopByHopHeaders are connection-level headers specific to the connection |
| 6 | +// between client and AI Bridge, not meant for the upstream. |
| 7 | +// See https://www.rfc-editor.org/rfc/rfc2616#section-13.5.1 |
| 8 | +var hopByHopHeaders = []string{ |
| 9 | + "Connection", |
| 10 | + "Keep-Alive", |
| 11 | + "Proxy-Authenticate", |
| 12 | + "Proxy-Authorization", |
| 13 | + "Te", |
| 14 | + "Trailer", |
| 15 | + "Transfer-Encoding", |
| 16 | + "Upgrade", |
| 17 | +} |
| 18 | + |
| 19 | +// nonForwardedHeaders are transport-level headers managed by aibridge or |
| 20 | +// Go's HTTP transport that must not be forwarded to the upstream provider. |
| 21 | +var nonForwardedHeaders = []string{ |
| 22 | + "Host", |
| 23 | + "Accept-Encoding", |
| 24 | + "Content-Length", |
| 25 | +} |
| 26 | + |
| 27 | +// authHeaders are headers that carry authentication credentials from the |
| 28 | +// client. These are stripped because the SDK re-injects the correct |
| 29 | +// provider credentials (API key or per-user token). |
| 30 | +var authHeaders = []string{ |
| 31 | + "Authorization", |
| 32 | + "X-Api-Key", |
| 33 | +} |
| 34 | + |
| 35 | +// SanitizeClientHeaders returns a copy of the client headers with hop-by-hop, |
| 36 | +// transport, and auth headers removed. |
| 37 | +func SanitizeClientHeaders(clientHeaders http.Header) http.Header { |
| 38 | + sanitized := clientHeaders.Clone() |
| 39 | + for _, h := range hopByHopHeaders { |
| 40 | + sanitized.Del(h) |
| 41 | + } |
| 42 | + for _, h := range nonForwardedHeaders { |
| 43 | + sanitized.Del(h) |
| 44 | + } |
| 45 | + for _, h := range authHeaders { |
| 46 | + sanitized.Del(h) |
| 47 | + } |
| 48 | + return sanitized |
| 49 | +} |
| 50 | + |
| 51 | +// BuildUpstreamHeaders produces the header set for an upstream SDK request. |
| 52 | +// It starts from the sanitized client headers, then preserves specific |
| 53 | +// headers from the SDK-built request that must not be overwritten. |
| 54 | +func BuildUpstreamHeaders(sdkHeader http.Header, clientHeaders http.Header, authHeaderName string) http.Header { |
| 55 | + headers := SanitizeClientHeaders(clientHeaders) |
| 56 | + |
| 57 | + // Preserve the auth header set by the SDK from the provider configuration. |
| 58 | + if v := sdkHeader.Get(authHeaderName); v != "" { |
| 59 | + headers.Set(authHeaderName, v) |
| 60 | + } |
| 61 | + |
| 62 | + // Preserve actor headers injected by aibridge as per-request SDK options. |
| 63 | + for name, values := range sdkHeader { |
| 64 | + if IsActorHeader(name) { |
| 65 | + headers[name] = values |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return headers |
| 70 | +} |
0 commit comments