|
| 1 | +package com.ecwid.apiclient.v3.httptransport.impl |
| 2 | + |
| 3 | +import org.apache.http.Header |
| 4 | +import org.apache.http.HttpStatus |
| 5 | +import org.apache.http.client.methods.HttpGet |
| 6 | +import org.apache.http.client.methods.HttpHead |
| 7 | +import org.apache.http.client.methods.HttpUriRequest |
| 8 | +import org.apache.http.client.methods.RequestBuilder |
| 9 | +import org.apache.http.impl.client.DefaultRedirectStrategy |
| 10 | +import org.apache.http.protocol.HttpContext |
| 11 | + |
| 12 | +/** |
| 13 | + * List of headers that can be passed to a redirect location. |
| 14 | + * We should NOT expose any custom headers and Authorization header to external sources |
| 15 | + */ |
| 16 | +private val allowedHeaders = setOf( |
| 17 | + "Accept", |
| 18 | + "Accept-Charset", |
| 19 | + "Accept-Encoding", |
| 20 | + "Accept-Language", |
| 21 | + "Access-Control-Request-Method", |
| 22 | + "Access-Control-Request-Headers", |
| 23 | + "Cache-Control", |
| 24 | + "Connection", |
| 25 | + "Content-Encoding", |
| 26 | + "Content-Length", |
| 27 | + "Content-Type", |
| 28 | + "Date", |
| 29 | + "Host", |
| 30 | + "HTTP2-Settings", |
| 31 | + "If-Match", |
| 32 | + "If-Modified-Since", |
| 33 | + "If-None-Match", |
| 34 | + "If-Unmodified-Since", |
| 35 | + "Origin", |
| 36 | + "Referer", |
| 37 | + "User-Agent", |
| 38 | + "X-Forwarded-For", |
| 39 | + "X-Forwarded-Host", |
| 40 | + "X-Forwarded-Proto" |
| 41 | +) |
| 42 | + |
| 43 | +class RemoveDisallowedHeadersRedirectStrategy : DefaultRedirectStrategy() { |
| 44 | + override fun getRedirect( |
| 45 | + request: org.apache.http.HttpRequest, |
| 46 | + response: org.apache.http.HttpResponse, |
| 47 | + context: HttpContext? |
| 48 | + ): HttpUriRequest { |
| 49 | + val uri = getLocationURI(request, response, context) |
| 50 | + val method = request.requestLine.method |
| 51 | + return if (method.equals(HttpHead.METHOD_NAME, ignoreCase = true)) { |
| 52 | + object : HttpHead(uri) { |
| 53 | + override fun setHeaders(headers: Array<out Header>) { |
| 54 | + super.setHeaders(headers.filter { it.name in allowedHeaders }.toTypedArray()) |
| 55 | + } |
| 56 | + } |
| 57 | + } else { |
| 58 | + val httpGet = object : HttpGet(uri) { |
| 59 | + override fun setHeaders(headers: Array<out Header>) { |
| 60 | + super.setHeaders(headers.filter { it.name in allowedHeaders }.toTypedArray()) |
| 61 | + } |
| 62 | + } |
| 63 | + if (method.equals(HttpGet.METHOD_NAME, ignoreCase = true)) { |
| 64 | + httpGet |
| 65 | + } else { |
| 66 | + val status = response.statusLine.statusCode |
| 67 | + if (status == HttpStatus.SC_TEMPORARY_REDIRECT || status == SC_PERMANENT_REDIRECT) { |
| 68 | + RequestBuilder.copy(request).setUri(uri).build() |
| 69 | + } else { |
| 70 | + httpGet |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments