irimi-sdk 0.2.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- irimi/__init__.py +4 -0
- irimi/_aiohttp_patch.py +371 -0
- irimi/_aiohttp_serving.py +216 -0
- irimi/_atomic_total.py +14 -0
- irimi/_bodies.py +64 -0
- irimi/_credential_headers.py +52 -0
- irimi/_decorators.py +236 -0
- irimi/_delivery.py +70 -0
- irimi/_divergence.py +60 -0
- irimi/_drops.py +24 -0
- irimi/_errors.py +14 -0
- irimi/_exporter.py +193 -0
- irimi/_function_answers.py +87 -0
- irimi/_git.py +37 -0
- irimi/_httpx_patch.py +236 -0
- irimi/_interception.py +174 -0
- irimi/_labeled_calls.py +116 -0
- irimi/_llm_providers.py +57 -0
- irimi/_object_fields.py +32 -0
- irimi/_outbound_calls.py +190 -0
- irimi/_patching.py +58 -0
- irimi/_rebuilding.py +97 -0
- irimi/_recorded_calls.py +231 -0
- irimi/_recording.py +122 -0
- irimi/_recording_loader.py +63 -0
- irimi/_replay_child.py +156 -0
- irimi/_replay_decisions.py +120 -0
- irimi/_replay_fields.py +16 -0
- irimi/_replay_proxy.py +328 -0
- irimi/_replay_refusals.py +5 -0
- irimi/_response_recording.py +74 -0
- irimi/_sdk.py +318 -0
- irimi/_serialisation.py +114 -0
- irimi/_status_reasons.py +10 -0
- irimi/_unpatched_clients.py +105 -0
- irimi/_url_credentials.py +11 -0
- irimi/_urllib3_patch.py +465 -0
- irimi/_urllib3_serving.py +81 -0
- irimi/_wire/__init__.py +56 -0
- irimi/_wire/call_roles.py +32 -0
- irimi/_wire/events.py +209 -0
- irimi/_wire/field_names.py +80 -0
- irimi/_wire/json_value.py +3 -0
- irimi/_wire/markers.py +49 -0
- irimi/py.typed +0 -0
- irimi_sdk-0.2.0.dev0.dist-info/METADATA +81 -0
- irimi_sdk-0.2.0.dev0.dist-info/RECORD +48 -0
- irimi_sdk-0.2.0.dev0.dist-info/WHEEL +4 -0
irimi/_replay_proxy.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import atexit
|
|
4
|
+
import functools
|
|
5
|
+
import http.client
|
|
6
|
+
import io
|
|
7
|
+
import os
|
|
8
|
+
import select
|
|
9
|
+
import socket
|
|
10
|
+
import socketserver
|
|
11
|
+
import threading
|
|
12
|
+
import urllib.request
|
|
13
|
+
from collections import Counter
|
|
14
|
+
from collections.abc import Callable, MutableMapping
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from http.server import BaseHTTPRequestHandler
|
|
17
|
+
from typing import Any
|
|
18
|
+
from urllib.parse import urlsplit
|
|
19
|
+
|
|
20
|
+
from irimi._bodies import copy_body
|
|
21
|
+
from irimi._interception import Interception, OpenCall
|
|
22
|
+
from irimi._outbound_calls import (
|
|
23
|
+
CallOutcome,
|
|
24
|
+
Headers,
|
|
25
|
+
OutboundCall,
|
|
26
|
+
OutboundResponse,
|
|
27
|
+
find_address,
|
|
28
|
+
)
|
|
29
|
+
from irimi._replay_refusals import ReplayRefusal
|
|
30
|
+
from irimi._sdk import Replay
|
|
31
|
+
from irimi._wire import field_names
|
|
32
|
+
|
|
33
|
+
PROXY_VARIABLES = (
|
|
34
|
+
"HTTP_PROXY",
|
|
35
|
+
"HTTPS_PROXY",
|
|
36
|
+
"ALL_PROXY",
|
|
37
|
+
"http_proxy",
|
|
38
|
+
"https_proxy",
|
|
39
|
+
"all_proxy",
|
|
40
|
+
)
|
|
41
|
+
BYPASS_VARIABLES = ("NO_PROXY", "no_proxy")
|
|
42
|
+
LOOPBACK_HOST = "127.0.0.1"
|
|
43
|
+
OK = 200
|
|
44
|
+
BAD_REQUEST = 400
|
|
45
|
+
FORBIDDEN = 403
|
|
46
|
+
BAD_GATEWAY = 502
|
|
47
|
+
TUNNEL_READ_SIZE = 64 * 1024
|
|
48
|
+
SHUTDOWN_POLL_SECONDS = 0.1
|
|
49
|
+
UNFORWARDED_HEADERS = frozenset(
|
|
50
|
+
{
|
|
51
|
+
"connection",
|
|
52
|
+
"keep-alive",
|
|
53
|
+
"proxy-connection",
|
|
54
|
+
"proxy-authorization",
|
|
55
|
+
"te",
|
|
56
|
+
"trailer",
|
|
57
|
+
"transfer-encoding",
|
|
58
|
+
"upgrade",
|
|
59
|
+
"content-length",
|
|
60
|
+
"host",
|
|
61
|
+
}
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class LiveCalls:
|
|
66
|
+
def __init__(self) -> None:
|
|
67
|
+
self._open_counts: Counter[tuple[str, int]] = Counter()
|
|
68
|
+
self._lock = threading.Lock()
|
|
69
|
+
|
|
70
|
+
def open(self, host: str, port: int) -> None:
|
|
71
|
+
with self._lock:
|
|
72
|
+
self._open_counts[(host, port)] += 1
|
|
73
|
+
|
|
74
|
+
def close(self, host: str, port: int) -> None:
|
|
75
|
+
with self._lock:
|
|
76
|
+
self._open_counts[(host, port)] -= 1
|
|
77
|
+
if self._open_counts[(host, port)] <= 0:
|
|
78
|
+
del self._open_counts[(host, port)]
|
|
79
|
+
|
|
80
|
+
def is_open(self, host: str, port: int) -> bool:
|
|
81
|
+
with self._lock:
|
|
82
|
+
return self._open_counts.get((host, port), 0) > 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass(frozen=True)
|
|
86
|
+
class ProxyAnswer:
|
|
87
|
+
status: int
|
|
88
|
+
headers: Headers
|
|
89
|
+
body: bytes
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class ReplayProxy:
|
|
93
|
+
def __init__(self, live_calls: LiveCalls, replay: Replay) -> None:
|
|
94
|
+
self.live_calls = live_calls
|
|
95
|
+
self._replay = replay
|
|
96
|
+
shared = replay.interception
|
|
97
|
+
self.interception = Interception(shared.recorder, shared.report_failure, replay.decider)
|
|
98
|
+
|
|
99
|
+
def start(self) -> str:
|
|
100
|
+
server = _ProxyServer(
|
|
101
|
+
functools.partial(_ProxyHandler, self), self.interception.report_failure
|
|
102
|
+
)
|
|
103
|
+
thread = threading.Thread(
|
|
104
|
+
target=server.serve_forever,
|
|
105
|
+
args=(SHUTDOWN_POLL_SECONDS,),
|
|
106
|
+
name="irimi replay proxy",
|
|
107
|
+
daemon=True,
|
|
108
|
+
)
|
|
109
|
+
thread.start()
|
|
110
|
+
atexit.register(_stop_serving, server)
|
|
111
|
+
return f"http://{LOOPBACK_HOST}:{server.server_address[1]}"
|
|
112
|
+
|
|
113
|
+
def begin_caught_call(self, call: OutboundCall) -> OpenCall | None:
|
|
114
|
+
with self.interception.recorder.make_current(self._replay.running_workflow):
|
|
115
|
+
return self.interception.begin(call, (field_names.CAUGHT_BY_PROXY,))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def catch_escaping_calls(live_calls: LiveCalls, replay: Replay, server_url: str) -> None:
|
|
119
|
+
try:
|
|
120
|
+
proxy_url = ReplayProxy(live_calls, replay).start()
|
|
121
|
+
except OSError as error:
|
|
122
|
+
raise ReplayRefusal(
|
|
123
|
+
f"the replay could not start the proxy that catches unpatched clients: {error}"
|
|
124
|
+
) from error
|
|
125
|
+
set_proxy_variables(os.environ, proxy_url, server_url)
|
|
126
|
+
urllib.request.install_opener(urllib.request.build_opener())
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def set_proxy_variables(
|
|
130
|
+
environment: MutableMapping[str, str], proxy_url: str, server_url: str
|
|
131
|
+
) -> None:
|
|
132
|
+
for name in PROXY_VARIABLES:
|
|
133
|
+
environment[name] = proxy_url
|
|
134
|
+
server_address = urlsplit(server_url).netloc.rpartition("@")[2]
|
|
135
|
+
for name in BYPASS_VARIABLES:
|
|
136
|
+
environment[name] = server_address
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class _ProxyServer(socketserver.ThreadingTCPServer):
|
|
140
|
+
daemon_threads = True
|
|
141
|
+
|
|
142
|
+
def __init__(
|
|
143
|
+
self,
|
|
144
|
+
handler: Callable[..., socketserver.BaseRequestHandler],
|
|
145
|
+
report_failure: Callable[[str], None],
|
|
146
|
+
) -> None:
|
|
147
|
+
self._report_failure = report_failure
|
|
148
|
+
super().__init__((LOOPBACK_HOST, 0), handler)
|
|
149
|
+
|
|
150
|
+
def handle_error(self, request: object, client_address: object) -> None:
|
|
151
|
+
self._report_failure("handle a call the replay proxy caught")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _stop_serving(server: _ProxyServer) -> None:
|
|
155
|
+
server.shutdown()
|
|
156
|
+
server.server_close()
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class _ProxyHandler(BaseHTTPRequestHandler):
|
|
160
|
+
protocol_version = "HTTP/1.1"
|
|
161
|
+
|
|
162
|
+
def __init__(self, proxy: ReplayProxy, *arguments: Any) -> None:
|
|
163
|
+
self._proxy = proxy
|
|
164
|
+
super().__init__(*arguments)
|
|
165
|
+
|
|
166
|
+
def handle(self) -> None:
|
|
167
|
+
try:
|
|
168
|
+
super().handle()
|
|
169
|
+
except ConnectionError:
|
|
170
|
+
return
|
|
171
|
+
|
|
172
|
+
def log_message(self, format: str, *arguments: Any) -> None:
|
|
173
|
+
return
|
|
174
|
+
|
|
175
|
+
def do_CONNECT(self) -> None:
|
|
176
|
+
self.close_connection = True
|
|
177
|
+
try:
|
|
178
|
+
host, port = find_address("//" + self.path)
|
|
179
|
+
except ValueError:
|
|
180
|
+
self.send_error(BAD_REQUEST)
|
|
181
|
+
return
|
|
182
|
+
if self._proxy.live_calls.is_open(host, port):
|
|
183
|
+
self._tunnel(host, port)
|
|
184
|
+
return
|
|
185
|
+
self._refuse_connection()
|
|
186
|
+
|
|
187
|
+
def _handle_plain_request(self) -> None:
|
|
188
|
+
self.close_connection = True
|
|
189
|
+
try:
|
|
190
|
+
host, port = find_address(self.path)
|
|
191
|
+
body = self._read_body()
|
|
192
|
+
except ValueError:
|
|
193
|
+
self.send_error(BAD_REQUEST)
|
|
194
|
+
return
|
|
195
|
+
if urlsplit(self.path).scheme != "http":
|
|
196
|
+
self.send_error(BAD_REQUEST, "only absolute http:// requests can be proxied")
|
|
197
|
+
return
|
|
198
|
+
if self._proxy.live_calls.is_open(host, port):
|
|
199
|
+
self._forward_and_answer(host, port, body)
|
|
200
|
+
return
|
|
201
|
+
self._answer_caught_request(host, port, body)
|
|
202
|
+
|
|
203
|
+
do_GET = _handle_plain_request
|
|
204
|
+
do_HEAD = _handle_plain_request
|
|
205
|
+
do_POST = _handle_plain_request
|
|
206
|
+
do_PUT = _handle_plain_request
|
|
207
|
+
do_PATCH = _handle_plain_request
|
|
208
|
+
do_DELETE = _handle_plain_request
|
|
209
|
+
do_OPTIONS = _handle_plain_request
|
|
210
|
+
do_TRACE = _handle_plain_request
|
|
211
|
+
|
|
212
|
+
def _answer_caught_request(self, host: str, port: int, body: bytes | None) -> None:
|
|
213
|
+
interception = self._proxy.interception
|
|
214
|
+
call = OutboundCall(self.command, self.path, self._read_headers(), body or None, False)
|
|
215
|
+
open_call = self._proxy.begin_caught_call(call)
|
|
216
|
+
if open_call is None:
|
|
217
|
+
self.send_error(FORBIDDEN)
|
|
218
|
+
return
|
|
219
|
+
served = open_call.served_response
|
|
220
|
+
if served is not None:
|
|
221
|
+
interception.end_served(open_call)
|
|
222
|
+
self._answer(ProxyAnswer(served.status, served.headers, served.body))
|
|
223
|
+
return
|
|
224
|
+
try:
|
|
225
|
+
answer = self._forward(host, port, body)
|
|
226
|
+
except (OSError, http.client.HTTPException) as error:
|
|
227
|
+
interception.end(open_call, CallOutcome(None, None, False, error))
|
|
228
|
+
self.send_error(BAD_GATEWAY)
|
|
229
|
+
return
|
|
230
|
+
response = OutboundResponse(answer.status, answer.headers)
|
|
231
|
+
interception.end(open_call, CallOutcome(response, copy_body(answer.body), True, None))
|
|
232
|
+
self._answer(answer)
|
|
233
|
+
|
|
234
|
+
def _forward_and_answer(self, host: str, port: int, body: bytes | None) -> None:
|
|
235
|
+
try:
|
|
236
|
+
answer = self._forward(host, port, body)
|
|
237
|
+
except (OSError, http.client.HTTPException):
|
|
238
|
+
self.send_error(BAD_GATEWAY)
|
|
239
|
+
return
|
|
240
|
+
self._answer(answer)
|
|
241
|
+
|
|
242
|
+
def _forward(self, host: str, port: int, body: bytes | None) -> ProxyAnswer:
|
|
243
|
+
target = urlsplit(self.path)
|
|
244
|
+
origin_form = (target.path or "/") + (f"?{target.query}" if target.query else "")
|
|
245
|
+
connection = http.client.HTTPConnection(host, port)
|
|
246
|
+
try:
|
|
247
|
+
connection.putrequest(self.command, origin_form, skip_accept_encoding=True)
|
|
248
|
+
for name, value in self._read_headers():
|
|
249
|
+
if name.lower() not in UNFORWARDED_HEADERS:
|
|
250
|
+
connection.putheader(name, value)
|
|
251
|
+
if body is not None:
|
|
252
|
+
connection.putheader("content-length", str(len(body)))
|
|
253
|
+
connection.endheaders(body)
|
|
254
|
+
answer = connection.getresponse()
|
|
255
|
+
return ProxyAnswer(answer.status, tuple(answer.getheaders()), answer.read())
|
|
256
|
+
finally:
|
|
257
|
+
connection.close()
|
|
258
|
+
|
|
259
|
+
def _answer(self, answer: ProxyAnswer) -> None:
|
|
260
|
+
self.send_response_only(answer.status)
|
|
261
|
+
for name, value in answer.headers:
|
|
262
|
+
if name.lower() not in UNFORWARDED_HEADERS:
|
|
263
|
+
self.send_header(name, value)
|
|
264
|
+
self.send_header("content-length", str(len(answer.body)))
|
|
265
|
+
self.send_header("connection", "close")
|
|
266
|
+
self.end_headers()
|
|
267
|
+
if self.command != "HEAD":
|
|
268
|
+
self.wfile.write(answer.body)
|
|
269
|
+
|
|
270
|
+
def _refuse_connection(self) -> None:
|
|
271
|
+
call = OutboundCall("CONNECT", "//" + self.path, self._read_headers(), None, False)
|
|
272
|
+
open_call = self._proxy.begin_caught_call(call)
|
|
273
|
+
refusal = OutboundResponse(FORBIDDEN, (("content-length", "0"),))
|
|
274
|
+
self._proxy.interception.end(open_call, CallOutcome(refusal, copy_body(b""), True, None))
|
|
275
|
+
self.send_response_only(FORBIDDEN)
|
|
276
|
+
self.send_header("content-length", "0")
|
|
277
|
+
self.send_header("connection", "close")
|
|
278
|
+
self.end_headers()
|
|
279
|
+
|
|
280
|
+
def _tunnel(self, host: str, port: int) -> None:
|
|
281
|
+
try:
|
|
282
|
+
upstream = socket.create_connection((host, port))
|
|
283
|
+
except OSError:
|
|
284
|
+
self.send_error(BAD_GATEWAY)
|
|
285
|
+
return
|
|
286
|
+
with upstream:
|
|
287
|
+
self.send_response_only(OK, "Connection Established")
|
|
288
|
+
self.end_headers()
|
|
289
|
+
_relay(self.connection, upstream)
|
|
290
|
+
|
|
291
|
+
def _read_body(self) -> bytes | None:
|
|
292
|
+
if "chunked" in self.headers.get("transfer-encoding", "").lower():
|
|
293
|
+
return _read_chunked_body(self.rfile)
|
|
294
|
+
length = self.headers.get("content-length")
|
|
295
|
+
if length is None:
|
|
296
|
+
return None
|
|
297
|
+
return self.rfile.read(_read_size(length, 10))
|
|
298
|
+
|
|
299
|
+
def _read_headers(self) -> Headers:
|
|
300
|
+
return tuple(self.headers.items())
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _read_size(digits: str | bytes, base: int) -> int:
|
|
304
|
+
size = int(digits, base)
|
|
305
|
+
if size < 0:
|
|
306
|
+
raise ValueError(f"a body cannot have a negative size: {size}")
|
|
307
|
+
return size
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _read_chunked_body(stream: io.BufferedIOBase) -> bytes:
|
|
311
|
+
chunks: list[bytes] = []
|
|
312
|
+
while size := _read_size(stream.readline().split(b";")[0], 16):
|
|
313
|
+
chunks.append(stream.read(size))
|
|
314
|
+
stream.readline()
|
|
315
|
+
while stream.readline().strip():
|
|
316
|
+
continue
|
|
317
|
+
return b"".join(chunks)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _relay(client: socket.socket, upstream: socket.socket) -> None:
|
|
321
|
+
peers = {client: upstream, upstream: client}
|
|
322
|
+
while True:
|
|
323
|
+
readable, _, _ = select.select(list(peers), [], [])
|
|
324
|
+
for source in readable:
|
|
325
|
+
data = source.recv(TUNNEL_READ_SIZE)
|
|
326
|
+
if not data:
|
|
327
|
+
return
|
|
328
|
+
peers[source].sendall(data)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import TypeVar
|
|
6
|
+
|
|
7
|
+
from irimi._bodies import BodyCopy, CopiedBody
|
|
8
|
+
from irimi._interception import Interception, OpenCall
|
|
9
|
+
from irimi._outbound_calls import CallOutcome, OutboundResponse
|
|
10
|
+
|
|
11
|
+
BuiltResponse = TypeVar("BuiltResponse")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ResponseRecording:
|
|
15
|
+
def __init__(
|
|
16
|
+
self, interception: Interception, open_call: OpenCall, response: OutboundResponse
|
|
17
|
+
) -> None:
|
|
18
|
+
self._interception = interception
|
|
19
|
+
self._open_call = open_call
|
|
20
|
+
self._response = response
|
|
21
|
+
self._body: BodyCopy | None = BodyCopy() if open_call.is_attached else None
|
|
22
|
+
self._has_copy_failed = False
|
|
23
|
+
self._ends_asked_for = itertools.count()
|
|
24
|
+
|
|
25
|
+
def add(self, chunk: bytes) -> None:
|
|
26
|
+
body_copy = self._body
|
|
27
|
+
if body_copy is None:
|
|
28
|
+
return
|
|
29
|
+
try:
|
|
30
|
+
body_copy.add(chunk)
|
|
31
|
+
except Exception:
|
|
32
|
+
self._body = None
|
|
33
|
+
self._has_copy_failed = True
|
|
34
|
+
self._interception.report_failure("copy an outbound response body")
|
|
35
|
+
|
|
36
|
+
def end(self, was_read_to_end: bool, error: BaseException | None) -> None:
|
|
37
|
+
is_first_end = next(self._ends_asked_for) == 0
|
|
38
|
+
if not is_first_end:
|
|
39
|
+
return
|
|
40
|
+
try:
|
|
41
|
+
outcome = CallOutcome(
|
|
42
|
+
response=self._response,
|
|
43
|
+
body=self._release_body(),
|
|
44
|
+
was_read_to_end=was_read_to_end and not self._has_copy_failed,
|
|
45
|
+
error=error,
|
|
46
|
+
)
|
|
47
|
+
except Exception:
|
|
48
|
+
self._interception.release_live_call(self._open_call)
|
|
49
|
+
self._interception.report_failure("take the copy of an outbound response body")
|
|
50
|
+
return
|
|
51
|
+
self._interception.end(self._open_call, outcome)
|
|
52
|
+
|
|
53
|
+
def _release_body(self) -> CopiedBody | None:
|
|
54
|
+
body_copy, self._body = self._body, None
|
|
55
|
+
return body_copy.take() if body_copy is not None else None
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def end_without_response(
|
|
59
|
+
interception: Interception, open_call: OpenCall | None, error: BaseException
|
|
60
|
+
) -> None:
|
|
61
|
+
outcome = CallOutcome(response=None, body=None, was_read_to_end=False, error=error)
|
|
62
|
+
interception.end(open_call, outcome)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def serve_built_response(
|
|
66
|
+
interception: Interception, open_call: OpenCall, build_response: Callable[[], BuiltResponse]
|
|
67
|
+
) -> BuiltResponse:
|
|
68
|
+
try:
|
|
69
|
+
response = build_response()
|
|
70
|
+
except BaseException as error:
|
|
71
|
+
end_without_response(interception, open_call, error)
|
|
72
|
+
raise
|
|
73
|
+
interception.end_served(open_call)
|
|
74
|
+
return response
|