|
| 1 | +package net.snowflake.client.core; |
| 2 | + |
| 3 | +import com.amazonaws.Request; |
| 4 | +import com.amazonaws.handlers.RequestHandler2; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.HashMap; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.Set; |
| 11 | +import java.util.stream.Collectors; |
| 12 | +import net.snowflake.client.jdbc.HttpHeadersCustomizer; |
| 13 | +import net.snowflake.client.log.SFLogger; |
| 14 | +import net.snowflake.client.log.SFLoggerFactory; |
| 15 | +import org.apache.http.Header; |
| 16 | +import org.apache.http.HttpException; |
| 17 | +import org.apache.http.HttpRequest; |
| 18 | +import org.apache.http.HttpRequestInterceptor; |
| 19 | +import org.apache.http.protocol.HttpContext; |
| 20 | + |
| 21 | +/** |
| 22 | + * Implements Apache HttpClient's {@link HttpRequestInterceptor} to provide a mechanism for adding |
| 23 | + * custom HTTP headers to outgoing requests made by the Snowflake JDBC driver. |
| 24 | + * |
| 25 | + * <p>This class iterates through a list of user-provided {@link HttpHeadersCustomizer} |
| 26 | + * implementations. For each customizer, it checks if it applies to the current request. If it does, |
| 27 | + * it retrieves new headers from the customizer and adds them to the request, ensuring that existing |
| 28 | + * driver-set headers are not overridden. |
| 29 | + * |
| 30 | + * <p>For Apache HttpClient, retry detection is handled by checking the {@link |
| 31 | + * AttributeEnhancingHttpRequestRetryHandler#EXECUTION_COUNT_ATTRIBUTE} attribute in the {@link |
| 32 | + * HttpContext} set by {@link AttributeEnhancingHttpRequestRetryHandler} to honor the {@code |
| 33 | + * invokeOnce()} contract of the customizer. |
| 34 | + * |
| 35 | + * @see HttpHeadersCustomizer |
| 36 | + */ |
| 37 | +public class HeaderCustomizerHttpRequestInterceptor extends RequestHandler2 |
| 38 | + implements HttpRequestInterceptor { |
| 39 | + private static final SFLogger logger = |
| 40 | + SFLoggerFactory.getLogger(HeaderCustomizerHttpRequestInterceptor.class); |
| 41 | + private final List<HttpHeadersCustomizer> headersCustomizers; |
| 42 | + |
| 43 | + public HeaderCustomizerHttpRequestInterceptor(List<HttpHeadersCustomizer> headersCustomizers) { |
| 44 | + if (headersCustomizers != null) { |
| 45 | + this.headersCustomizers = new ArrayList<>(headersCustomizers); // Defensive copy |
| 46 | + } else { |
| 47 | + this.headersCustomizers = new ArrayList<>(); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Processes an Apache HttpClient {@link HttpRequest} before it is sent. It iterates through |
| 53 | + * registered {@link HttpHeadersCustomizer}s, checks applicability, retrieves new headers, |
| 54 | + * verifies against overriding driver headers, and adds them to the request. Handles the {@code |
| 55 | + * invokeOnce()} flag based on the "execution-count" attribute in the {@link HttpContext}. |
| 56 | + * |
| 57 | + * @param httpRequest The HTTP request to process. |
| 58 | + * @param httpContext The context for the HTTP request execution, used to retrieve retry count. |
| 59 | + * @throws DriverHeaderOverridingNotAllowedException If a customizer attempts to override a |
| 60 | + * driver-set header. |
| 61 | + */ |
| 62 | + @Override |
| 63 | + public void process(HttpRequest httpRequest, HttpContext httpContext) |
| 64 | + throws HttpException, IOException { |
| 65 | + if (this.headersCustomizers.isEmpty()) { |
| 66 | + return; |
| 67 | + } |
| 68 | + String httpMethod = httpRequest.getRequestLine().getMethod(); |
| 69 | + String uri = httpRequest.getRequestLine().getUri(); |
| 70 | + Map<String, List<String>> currentHeaders = extractHeaders(httpRequest); |
| 71 | + // convert header names to lower case for case in-sensitive lookup |
| 72 | + Set<String> protectedHeaders = |
| 73 | + currentHeaders.keySet().stream().map(String::toLowerCase).collect(Collectors.toSet()); |
| 74 | + Object executionCount = |
| 75 | + httpContext.getAttribute( |
| 76 | + AttributeEnhancingHttpRequestRetryHandler.EXECUTION_COUNT_ATTRIBUTE); |
| 77 | + // If count is null or 0, it's the first attempt. Otherwise, it's a retry. |
| 78 | + boolean isRetry = (executionCount != null && (Integer) executionCount > 0); |
| 79 | + |
| 80 | + for (HttpHeadersCustomizer customizer : this.headersCustomizers) { |
| 81 | + if (customizer.applies(httpMethod, uri, currentHeaders)) { |
| 82 | + if (customizer.invokeOnce() && isRetry) { |
| 83 | + logger.debug( |
| 84 | + "{} customizer should only run on the first attempt and this is a {} retry. Skipping.", |
| 85 | + customizer.getClass(), |
| 86 | + executionCount); |
| 87 | + continue; |
| 88 | + } |
| 89 | + Map<String, List<String>> newHeaders = customizer.newHeaders(); |
| 90 | + |
| 91 | + throwIfExistingHeadersAreModified(protectedHeaders, newHeaders.keySet(), customizer); |
| 92 | + |
| 93 | + for (Map.Entry<String, List<String>> entry : newHeaders.entrySet()) { |
| 94 | + for (String value : entry.getValue()) { |
| 95 | + httpRequest.addHeader(entry.getKey(), value); |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + @Override |
| 103 | + public void beforeRequest(Request<?> request) { |
| 104 | + super.beforeRequest(request); |
| 105 | + if (this.headersCustomizers.isEmpty()) { |
| 106 | + return; |
| 107 | + } |
| 108 | + String httpMethod = request.getHttpMethod().name(); |
| 109 | + String uri = request.getEndpoint().toString(); |
| 110 | + Map<String, List<String>> currentHeaders = extractHeaders(request); |
| 111 | + Set<String> protectedHeaders = |
| 112 | + currentHeaders.keySet().stream() |
| 113 | + .map(String::toLowerCase) |
| 114 | + .collect(Collectors.toSet()); // convert to lower case for case in-sensitive lookup |
| 115 | + |
| 116 | + for (HttpHeadersCustomizer customizer : this.headersCustomizers) { |
| 117 | + if (customizer.applies(httpMethod, uri, currentHeaders)) { |
| 118 | + Map<String, List<String>> newHeaders = customizer.newHeaders(); |
| 119 | + |
| 120 | + throwIfExistingHeadersAreModified(protectedHeaders, newHeaders.keySet(), customizer); |
| 121 | + |
| 122 | + for (Map.Entry<String, List<String>> entry : newHeaders.entrySet()) { |
| 123 | + for (String value : entry.getValue()) { |
| 124 | + request.addHeader(entry.getKey(), value); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private static Map<String, List<String>> extractHeaders(HttpRequest request) { |
| 132 | + Map<String, List<String>> headerMap = new HashMap<>(); |
| 133 | + for (Header header : request.getAllHeaders()) { |
| 134 | + headerMap.computeIfAbsent(header.getName(), k -> new ArrayList<>()).add(header.getValue()); |
| 135 | + } |
| 136 | + return headerMap; |
| 137 | + } |
| 138 | + |
| 139 | + private static Map<String, List<String>> extractHeaders(Request<?> request) { |
| 140 | + Map<String, List<String>> headerMap = new HashMap<>(); |
| 141 | + for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) { |
| 142 | + headerMap.computeIfAbsent(entry.getKey(), k -> new ArrayList<>()).add(entry.getValue()); |
| 143 | + } |
| 144 | + return headerMap; |
| 145 | + } |
| 146 | + |
| 147 | + /** |
| 148 | + * Checks if any header names from the customizer's new headers attempt to override existing |
| 149 | + * driver-set headers. Compares header names case-insensitively. |
| 150 | + * |
| 151 | + * @param protectedHeaders A set of lowercase header names initially present on the request. |
| 152 | + * @param newHeaders A set of header names provided by the customizer. |
| 153 | + * @param customizer The customizer attempting to add headers, for logging/exception messages. |
| 154 | + * @throws DriverHeaderOverridingNotAllowedException If an override is detected. |
| 155 | + */ |
| 156 | + private static void throwIfExistingHeadersAreModified( |
| 157 | + Set<String> protectedHeaders, Set<String> newHeaders, HttpHeadersCustomizer customizer) { |
| 158 | + for (String headerName : newHeaders) { |
| 159 | + if (headerName != null && protectedHeaders.contains(headerName.toLowerCase())) { |
| 160 | + logger.debug( |
| 161 | + "Customizer {} attempted to override existing driver header: {}", |
| 162 | + customizer.getClass().getName(), |
| 163 | + headerName); |
| 164 | + throw new DriverHeaderOverridingNotAllowedException(headerName); |
| 165 | + } |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + public static class DriverHeaderOverridingNotAllowedException extends RuntimeException { |
| 170 | + public DriverHeaderOverridingNotAllowedException(String header) { |
| 171 | + super(String.format("Driver headers overriding not allowed. Tried for header: %s", header)); |
| 172 | + } |
| 173 | + } |
| 174 | +} |
0 commit comments