-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpProxy.java
More file actions
350 lines (317 loc) · 12.3 KB
/
HttpProxy.java
File metadata and controls
350 lines (317 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package org.codejive.tproxy;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Core HTTP/HTTPS proxy implementation. This proxy is purely concerned with proxying requests and
* has no knowledge of testing, recording, or replay functionality.
*
* <p>All additional functionality is implemented via interceptors.
*/
public class HttpProxy {
private static final Logger logger = LoggerFactory.getLogger(HttpProxy.class);
private final List<Interceptor> interceptors = new ArrayList<>();
private HttpClient httpClient;
private ProxyServer proxyServer;
private CertificateAuthority certificateAuthority;
private boolean running = false;
private boolean httpsInterceptionEnabled = false;
private Path caStorageDir;
private int port;
public HttpProxy() {
this.httpClient = buildHttpClient(null);
}
/**
* Add an interceptor to the proxy. Interceptors are invoked in the order they are added;
* earlier interceptors are "outermost" and see both the request and the final response
* (including short-circuited ones).
*
* @param interceptor the interceptor to add
* @return this proxy instance for chaining
*/
public HttpProxy addInterceptor(Interceptor interceptor) {
this.interceptors.add(interceptor);
logger.debug("Added interceptor: {}", interceptor.getClass().getSimpleName());
return this;
}
/**
* Remove all interceptors.
*
* @return this proxy instance for chaining
*/
public HttpProxy clearInterceptors() {
interceptors.clear();
logger.debug("Cleared all interceptors");
return this;
}
/**
* Enable HTTPS interception (Man-in-the-Middle mode).
*
* <p>When enabled, the proxy will decrypt HTTPS traffic by generating certificates on-the-fly,
* allowing interceptors to inspect and modify HTTPS requests and responses.
*
* <p>Must be called before {@link #start(int)}.
*
* @return this proxy instance for chaining
* @throws IllegalStateException if the proxy is already running
*/
public HttpProxy enableHttpsInterception() {
if (running) {
throw new IllegalStateException(
"Cannot enable HTTPS interception while proxy is running");
}
this.httpsInterceptionEnabled = true;
logger.info("HTTPS interception enabled");
return this;
}
/**
* Set the directory in which the CA keystore and certificate files are stored.
*
* <p>Must be called before {@link #start(int)}. If not set, defaults to the current directory.
*
* @param storageDir the directory for CA storage
* @return this proxy instance for chaining
* @throws IllegalStateException if the proxy is already running
*/
public HttpProxy caStorageDir(Path storageDir) {
if (running) {
throw new IllegalStateException(
"Cannot change CA storage directory while proxy is running");
}
this.caStorageDir = storageDir;
return this;
}
/**
* Disable HTTPS interception (pass-through mode).
*
* <p>When disabled (default), HTTPS traffic passes through encrypted without inspection.
*
* <p>Must be called before {@link #start(int)}.
*
* @return this proxy instance for chaining
* @throws IllegalStateException if the proxy is already running
*/
public HttpProxy disableHttpsInterception() {
if (running) {
throw new IllegalStateException(
"Cannot disable HTTPS interception while proxy is running");
}
this.httpsInterceptionEnabled = false;
logger.info("HTTPS interception disabled");
return this;
}
/**
* Execute a request through the proxy. The request will pass through all configured
* interceptors.
*
* @param request the request to execute
* @return the response
* @throws IOException if an I/O error occurs
*/
public ProxyResponse execute(ProxyRequest request) throws IOException {
logger.info("Executing request: {} {}", request.method(), request.uri());
try {
InterceptorChain chain = new InterceptorChain(interceptors, this::executeActualRequest);
return chain.proceed(request);
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IOException("Error executing request through interceptors", e);
}
}
/**
* Execute the actual HTTP request (without interceptors). This is the terminal operation in the
* interceptor chain.
*
* @param request the request to execute
* @return the response
*/
private ProxyResponse executeActualRequest(ProxyRequest request) {
logger.debug("Executing actual HTTP request: {} {}", request.method(), request.uri());
try {
// Filter headers for forwarding
Headers filteredHeaders = HeaderFilter.filterForForwarding(request.headers());
// Build HttpRequest
HttpRequest.Builder builder =
HttpRequest.newBuilder()
.uri(request.uri())
.method(
request.method(),
BodyPublishers.ofInputStream(() -> request.bodyStream()));
// Add headers (HttpClient sets Host and Content-Length automatically)
filteredHeaders.forEach(
entry -> {
String name = entry.getKey();
if (!"Host".equalsIgnoreCase(name)
&& !"Content-Length".equalsIgnoreCase(name)) {
entry.getValue().forEach(value -> builder.header(name, value));
}
});
HttpRequest httpRequest = builder.build();
// Execute request and stream response
HttpResponse<InputStream> httpResponse =
httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofInputStream());
// Convert response
Headers responseHeaders = convertResponseHeaders(httpResponse);
return ProxyResponse.fromStream(
httpResponse.statusCode(), responseHeaders, httpResponse.body());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Request interrupted: {} {}", request.method(), request.uri(), e);
return ProxyResponse.fromBytes(
503,
Headers.of("Content-Type", "text/plain"),
"Service Unavailable: Request interrupted".getBytes());
} catch (IOException e) {
logger.error("Error executing request: {} {}", request.method(), request.uri(), e);
return ProxyResponse.fromBytes(
502,
Headers.of("Content-Type", "text/plain"),
("Bad Gateway: " + e.getMessage()).getBytes());
}
}
/**
* Convert HttpResponse headers to our Headers model.
*
* @param httpResponse the HTTP response
* @return converted headers
*/
private Headers convertResponseHeaders(HttpResponse<InputStream> httpResponse) {
return Headers.of(httpResponse.headers().map());
}
/**
* Start the proxy server on the specified port.
*
* @param port the port to listen on
* @throws IOException if the server cannot be started
*/
public void start(int port) throws IOException {
if (running) {
throw new IllegalStateException("Proxy is already running");
}
this.port = port;
// Create Certificate Authority if HTTPS interception is enabled
if (httpsInterceptionEnabled && certificateAuthority == null) {
logger.info("Creating Certificate Authority for HTTPS interception");
certificateAuthority =
caStorageDir != null
? new CertificateAuthority(caStorageDir)
: new CertificateAuthority();
// Rebuild HTTP client with trust-all SSL for upstream HTTPS connections
this.httpClient = buildHttpClient(createTrustAllSslContext());
}
// Create and start the proxy server
proxyServer = new ProxyServer(this, port, httpsInterceptionEnabled, certificateAuthority);
proxyServer.start();
this.running = true;
logger.info(
"Proxy server started on port {} (HTTPS interception: {})",
port,
httpsInterceptionEnabled ? "enabled" : "disabled");
}
/** Stop the proxy server. */
public void stop() {
if (running) {
if (proxyServer != null) {
proxyServer.stop();
proxyServer = null;
}
running = false;
logger.info("Proxy server stopped");
}
}
/**
* Check if the proxy server is running.
*
* @return true if running, false otherwise
*/
public boolean running() {
return running;
}
/**
* Get the port the proxy is running on.
*
* @return the port number
*/
public int port() {
return port;
}
/**
* Get a ProxySelector configured to use this proxy.
*
* <p>Use this to configure HTTP clients or set as the system default:
*
* <pre>{@code
* // Configure a specific HttpClient
* HttpClient client = HttpClient.newBuilder()
* .proxy(proxy.asProxySelector())
* .build();
*
* // Or set as system default
* ProxySelector.setDefault(proxy.asProxySelector());
* }</pre>
*
* @return a ProxySelector that routes traffic through this proxy
* @throws IllegalStateException if the proxy is not running
*/
public ProxySelector asProxySelector() {
if (!running) {
throw new IllegalStateException("Proxy must be running to create ProxySelector");
}
return ProxySelector.of(new InetSocketAddress("localhost", port));
}
private static HttpClient buildHttpClient(SSLContext sslContext) {
HttpClient.Builder builder =
HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(30))
.followRedirects(HttpClient.Redirect.NEVER);
if (sslContext != null) {
builder.sslContext(sslContext);
}
return builder.build();
}
private static SSLContext createTrustAllSslContext() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(
null,
new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(
X509Certificate[] certs, String authType) {}
@Override
public void checkServerTrusted(
X509Certificate[] certs, String authType) {}
}
},
null);
return sslContext;
} catch (GeneralSecurityException e) {
throw new RuntimeException("Failed to create trust-all SSL context", e);
}
}
}