-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathhttpclientexec.py
More file actions
450 lines (385 loc) · 14.9 KB
/
Copy pathhttpclientexec.py
File metadata and controls
450 lines (385 loc) · 14.9 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
"""
WAF Stressor - HTTP Client and Request Execution
Production-ready HTTP client with comprehensive error handling and rate limiting
© GHOSTSHINOBI 2025
"""
import httpx
import hashlib
import time
import json
from typing import Optional, Dict, Any
from urllib.parse import urlencode
from core import RequestConfig, HTTPMethod, TestConfig
class SecureHTTPClient:
"""
Production-grade HTTP client with:
- Rate limiting with exponential backoff
- Budget enforcement
- Retry logic with 429 handling
- Full HTTP method support (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)
- WebDAV method support (PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, UNLOCK, TRACE)
- TLS verification control
- Connection pooling and keepalive
- Comprehensive error handling
"""
# WebDAV and extended HTTP methods
WEBDAV_METHODS = ['PROPFIND', 'PROPPATCH', 'MKCOL', 'COPY', 'MOVE', 'LOCK', 'UNLOCK', 'TRACE']
def __init__(self, config: TestConfig):
self.config = config
self.client = self._create_client()
self.request_count = 0
self.last_request_time = 0.0
self.retry_count = 0
self.blocked_count = 0
self.error_count = 0
def _create_client(self) -> httpx.Client:
"""Create HTTP client with security defaults and connection pooling"""
return httpx.Client(
timeout=httpx.Timeout(
connect=5.0,
read=self.config.timeout,
write=self.config.timeout,
pool=10.0
),
verify=self.config.verify_tls,
follow_redirects=self.config.follow_redirects,
max_redirects=self.config.max_redirects,
headers={
'User-Agent': self.config.user_agent,
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
**self.config.custom_headers
},
limits=httpx.Limits(
max_connections=10,
max_keepalive_connections=5,
keepalive_expiry=30.0
),
http2=False # HTTP/1.1 for better compatibility with WAF testing
)
def execute_request(self, request: RequestConfig) -> httpx.Response:
"""
Execute HTTP request with full error handling and retry logic
Returns httpx.Response object directly for engine processing
"""
# Rate limiting
self._apply_rate_limit()
# Budget check (only if budget > 0)
if self.config.budget > 0 and self.request_count >= self.config.budget:
raise RuntimeError(f"Budget exceeded: {self.config.budget} requests")
# Retry logic with exponential backoff
max_retries = self.config.rate_limit.max_retries
retry_delay = self.config.rate_limit.retry_delay
backoff_base = self.config.rate_limit.exponential_backoff_base
last_exception = None
for attempt in range(max_retries + 1):
try:
# Execute request
response = self._dispatch_request(request)
# Increment counter on successful dispatch
self.request_count += 1
# Handle 429 Too Many Requests with backoff
if response.status_code == 429 and self.config.rate_limit.backoff_on_429:
if attempt < max_retries:
retry_after = float(response.headers.get('Retry-After', retry_delay))
time.sleep(retry_after)
retry_delay *= backoff_base
self.retry_count += 1
continue
# Track blocked responses
if response.status_code in {403, 406, 418, 429, 503, 520, 521, 522, 523, 524, 525}:
self.blocked_count += 1
return response
except httpx.TimeoutException as e:
last_exception = e
if attempt < max_retries:
time.sleep(retry_delay)
retry_delay *= backoff_base
self.retry_count += 1
else:
self.error_count += 1
raise
except httpx.ConnectError as e:
last_exception = e
if attempt < max_retries:
time.sleep(retry_delay)
retry_delay *= backoff_base
self.retry_count += 1
else:
self.error_count += 1
raise
except httpx.HTTPStatusError as e:
# HTTP errors with valid response (4xx, 5xx)
self.request_count += 1
return e.response
except httpx.HTTPError as e:
last_exception = e
if attempt < max_retries:
time.sleep(retry_delay)
retry_delay *= backoff_base
self.retry_count += 1
else:
self.error_count += 1
raise
# Fallback after all retries exhausted
self.error_count += 1
if last_exception:
raise last_exception
raise RuntimeError("Max retries exceeded with unknown error")
def _dispatch_request(self, request: RequestConfig) -> httpx.Response:
"""
Dispatch request based on HTTP method
Handles all standard methods + WebDAV extensions
"""
method = request.method.value.upper()
# Prepare common params
params = {
'url': request.url,
'headers': self._prepare_headers(request),
'timeout': request.timeout,
}
# Handle body for methods that support it
body_methods = {'POST', 'PUT', 'PATCH'}
if method in body_methods or method in self.WEBDAV_METHODS:
if request.body:
params['content'] = request.body.encode('utf-8')
elif request.json_data:
params['json'] = request.json_data
# Method-specific handling
if method == 'GET':
return self.client.get(**params)
elif method == 'HEAD':
return self.client.head(**params)
elif method == 'OPTIONS':
return self.client.options(**params)
elif method == 'POST':
return self.client.post(**params)
elif method == 'PUT':
return self.client.put(**params)
elif method == 'PATCH':
return self.client.patch(**params)
elif method == 'DELETE':
return self.client.delete(**params)
elif method in self.WEBDAV_METHODS:
# WebDAV methods via generic request()
return self.client.request(method=method, **params)
else:
# Fallback for any custom methods
return self.client.request(method=method, **params)
def _prepare_headers(self, request: RequestConfig) -> Dict[str, str]:
"""Prepare and merge request headers with proper case handling"""
headers = dict(self.client.headers)
# Merge request-specific headers (case-insensitive replacement)
if request.headers:
for key, value in request.headers.items():
# Remove any existing case-insensitive versions
for existing_key in list(headers.keys()):
if existing_key.lower() == key.lower():
del headers[existing_key]
headers[key] = value
# Auto-set Content-Type if body present and not set
has_content_type = any(k.lower() == 'content-type' for k in headers.keys())
if request.body and not has_content_type:
headers['Content-Type'] = 'application/x-www-form-urlencoded'
elif request.json_data and not has_content_type:
headers['Content-Type'] = 'application/json'
# Set Content-Length for body requests
if request.body:
headers['Content-Length'] = str(len(request.body.encode('utf-8')))
return headers
def _apply_rate_limit(self) -> None:
"""
Apply token bucket rate limiting
Enforces requests_per_second with sub-second precision
"""
if self.last_request_time > 0:
elapsed = time.time() - self.last_request_time
min_interval = 1.0 / self.config.rate_limit.requests_per_second
# Enforce rate limit
if elapsed < min_interval:
sleep_time = min_interval - elapsed
time.sleep(sleep_time)
self.last_request_time = time.time()
def get_stats(self) -> Dict[str, Any]:
"""Return client statistics for monitoring"""
return {
'total_requests': self.request_count,
'blocked_requests': self.blocked_count,
'error_requests': self.error_count,
'retry_count': self.retry_count,
'success_rate': round(
(self.request_count - self.error_count) / max(self.request_count, 1) * 100, 2
),
'budget_remaining': max(0, self.config.budget - self.request_count) if self.config.budget > 0 else 'unlimited'
}
def close(self) -> None:
"""Close HTTP client and cleanup resources"""
try:
self.client.close()
except Exception:
pass
def __enter__(self):
"""Context manager entry"""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager exit - always cleanup"""
self.close()
return False # Don't suppress exceptions
# ============================================================================
# REQUEST BUILDER UTILITIES
# ============================================================================
class RequestBuilder:
"""
Fluent request builder for all HTTP methods
Provides convenient factory methods for common request types
"""
@staticmethod
def build_get_request(
url: str,
headers: Optional[Dict[str, str]] = None,
params: Optional[Dict[str, str]] = None
) -> RequestConfig:
"""Build GET request with optional query parameters"""
if params:
separator = '&' if '?' in url else '?'
url = f"{url}{separator}{urlencode(params)}"
return RequestConfig(
url=url,
method=HTTPMethod.GET,
headers=headers or {}
)
@staticmethod
def build_head_request(url: str, headers: Optional[Dict[str, str]] = None) -> RequestConfig:
"""Build HEAD request (metadata only, no body)"""
return RequestConfig(
url=url,
method=HTTPMethod.HEAD,
headers=headers or {}
)
@staticmethod
def build_options_request(url: str, headers: Optional[Dict[str, str]] = None) -> RequestConfig:
"""Build OPTIONS request (discover allowed methods)"""
return RequestConfig(
url=url,
method=HTTPMethod.OPTIONS,
headers=headers or {}
)
@staticmethod
def build_post_request(
url: str,
body: Optional[str] = None,
json_data: Optional[Dict] = None,
headers: Optional[Dict[str, str]] = None
) -> RequestConfig:
"""Build POST request with form or JSON body"""
req_headers = headers or {}
if json_data:
req_headers['Content-Type'] = 'application/json'
return RequestConfig(
url=url,
method=HTTPMethod.POST,
headers=req_headers,
json_data=json_data
)
if body and 'Content-Type' not in req_headers:
req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
return RequestConfig(
url=url,
method=HTTPMethod.POST,
headers=req_headers,
body=body
)
@staticmethod
def build_put_request(
url: str,
body: Optional[str] = None,
json_data: Optional[Dict] = None,
headers: Optional[Dict[str, str]] = None
) -> RequestConfig:
"""Build PUT request for resource update"""
req_headers = headers or {}
if json_data:
req_headers['Content-Type'] = 'application/json'
return RequestConfig(
url=url,
method=HTTPMethod.PUT,
headers=req_headers,
json_data=json_data
)
if body and 'Content-Type' not in req_headers:
req_headers['Content-Type'] = 'application/json'
return RequestConfig(
url=url,
method=HTTPMethod.PUT,
headers=req_headers,
body=body
)
@staticmethod
def build_patch_request(
url: str,
body: Optional[str] = None,
json_data: Optional[Dict] = None,
headers: Optional[Dict[str, str]] = None
) -> RequestConfig:
"""Build PATCH request for partial update"""
req_headers = headers or {}
if json_data:
req_headers['Content-Type'] = 'application/json'
return RequestConfig(
url=url,
method=HTTPMethod.PATCH,
headers=req_headers,
json_data=json_data
)
if body and 'Content-Type' not in req_headers:
req_headers['Content-Type'] = 'application/json'
return RequestConfig(
url=url,
method=HTTPMethod.PATCH,
headers=req_headers,
body=body
)
@staticmethod
def build_delete_request(url: str, headers: Optional[Dict[str, str]] = None) -> RequestConfig:
"""Build DELETE request"""
return RequestConfig(
url=url,
method=HTTPMethod.DELETE,
headers=headers or {}
)
@staticmethod
def build_json_request(
url: str,
method: HTTPMethod = HTTPMethod.POST,
json_data: Optional[Dict] = None,
headers: Optional[Dict[str, str]] = None
) -> RequestConfig:
"""Build JSON request for any method"""
req_headers = headers or {}
req_headers['Content-Type'] = 'application/json'
req_headers['Accept'] = 'application/json'
return RequestConfig(
url=url,
method=method,
headers=req_headers,
json_data=json_data
)
@staticmethod
def build_form_request(
url: str,
form_data: Dict[str, str],
method: HTTPMethod = HTTPMethod.POST,
headers: Optional[Dict[str, str]] = None
) -> RequestConfig:
"""Build form-encoded request"""
req_headers = headers or {}
req_headers['Content-Type'] = 'application/x-www-form-urlencoded'
body = urlencode(form_data)
return RequestConfig(
url=url,
method=method,
headers=req_headers,
body=body
)
__all__ = ['SecureHTTPClient', 'RequestBuilder']