@@ -31,6 +31,34 @@ const workaroundForNodeMetrics = req => {
3131 }
3232} ;
3333
34+ function k8sResponse ( k8sResponse ) {
35+ if (
36+ k8sResponse . headers &&
37+ ( k8sResponse . headers [ 'Content-Type' ] ?. includes ( '\\' ) ||
38+ k8sResponse . headers [ 'content-encoding' ] ?. includes ( '\\' ) )
39+ )
40+ return throwInternalServerError (
41+ 'Response headers are potentially dangerous' ,
42+ ) ;
43+
44+ // change all 503 into 502
45+ const statusCode =
46+ k8sResponse . statusCode === 503 ? 502 : k8sResponse . statusCode ;
47+
48+ // Ensure charset is specified in content type
49+ let contentType = k8sResponse . headers [ 'Content-Type' ] || 'text/json' ;
50+ if ( ! contentType . includes ( 'charset=' ) ) {
51+ contentType += '; charset=utf-8' ;
52+ }
53+
54+ res . writeHead ( statusCode , {
55+ 'Content-Type' : contentType ,
56+ 'Content-Encoding' : k8sResponse . headers [ 'content-encoding' ] || '' ,
57+ 'X-Content-Type-Options' : 'nosniff' ,
58+ } ) ;
59+ k8sResponse . pipe ( res ) ;
60+ }
61+
3462export const makeHandleRequest = ( ) => {
3563 const isDev = process . env . NODE_ENV !== 'production' ;
3664 const isTrackingEnabled =
@@ -102,7 +130,7 @@ export const makeHandleRequest = () => {
102130 ( k8sResponse . headers [ 'Content-Type' ] ?. includes ( '\\' ) ||
103131 k8sResponse . headers [ 'content-encoding' ] ?. includes ( '\\' ) )
104132 )
105- return throwInternalServerError (
133+ return respondWithInternalError (
106134 'Response headers are potentially dangerous' ,
107135 ) ;
108136
@@ -123,16 +151,15 @@ export const makeHandleRequest = () => {
123151 } ) ;
124152 k8sResponse . pipe ( res ) ;
125153 } ) ;
126- k8sRequest . on ( 'error' , throwInternalServerError ) ; // no need to sanitize the error here as the http.request() will never throw a vulnerable error
127-
154+ k8sRequest . on ( 'error' , respondWithInternalError ) ; // no need to sanitize the error here as the http.request() will never throw a vulnerable error
128155 if ( Buffer . isBuffer ( req . body ) ) {
129- k8sRequest . end ( req . body ) ;
156+ // If body is buffer it means it's not a json, don't pass it further.
157+ k8sRequest . end ( '' ) ;
130158 } else {
131- // If there's no body, pipe the request (for streaming)
132- req . pipe ( k8sRequest ) ;
159+ k8sRequest . end ( JSON . stringify ( req . body ) ) ;
133160 }
134161
135- function throwInternalServerError ( originalError ) {
162+ function respondWithInternalError ( originalError ) {
136163 req . log . warn ( originalError ) ;
137164 res . contentType ( 'text/plain; charset=utf-8' ) ;
138165 res
0 commit comments