irimi 0.1.0__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 +3 -0
- irimi/__main__.py +9 -0
- irimi/bodies.py +266 -0
- irimi/ca.py +111 -0
- irimi/cli.py +1573 -0
- irimi/compare.py +262 -0
- irimi/control.py +359 -0
- irimi/delegation.py +143 -0
- irimi/echo/__init__.py +198 -0
- irimi/echo/generic.py +154 -0
- irimi/echo/slack.py +240 -0
- irimi/engine/__init__.py +54 -0
- irimi/engine/mitm.py +1272 -0
- irimi/exchange.py +357 -0
- irimi/fixture.py +86 -0
- irimi/fixtures/slack.json +16 -0
- irimi/fixtures/stripe.json +346 -0
- irimi/idempotency.py +177 -0
- irimi/maps/anthropic.yaml +29 -0
- irimi/maps/openai.yaml +47 -0
- irimi/maps/slack.yaml +105 -0
- irimi/maps/stripe.yaml +113 -0
- irimi/maps/telemetry.yaml +239 -0
- irimi/netaddr.py +89 -0
- irimi/overlay.py +198 -0
- irimi/paths.py +66 -0
- irimi/pipeline.py +268 -0
- irimi/policy.py +636 -0
- irimi/reader.py +130 -0
- irimi/recording.py +582 -0
- irimi/redact.py +639 -0
- irimi/replay.py +339 -0
- irimi/report.py +904 -0
- irimi/reverse_door.py +71 -0
- irimi/runner.py +203 -0
- irimi/sdk/__init__.py +53 -0
- irimi/sdk/api.py +251 -0
- irimi/sdk/capture.py +423 -0
- irimi/sdk/client.py +175 -0
- irimi/sdk/context.py +77 -0
- irimi/sdk/errors.py +74 -0
- irimi/sdk/instrumentation.py +226 -0
- irimi/sdk/replay_child.py +171 -0
- irimi/sdk/replays.py +168 -0
- irimi/sdk/runs.py +266 -0
- irimi/sdk/tools.py +402 -0
- irimi/secret_shapes.py +54 -0
- irimi/servicemap/__init__.py +82 -0
- irimi/servicemap/loader.py +495 -0
- irimi/servicemap/model.py +256 -0
- irimi/servicemap/rules.py +252 -0
- irimi/services/__init__.py +85 -0
- irimi/services/model.py +175 -0
- irimi/services/slack.py +624 -0
- irimi/services/stripe.py +454 -0
- irimi/store.py +1167 -0
- irimi/trace.py +759 -0
- irimi/writelog.py +65 -0
- irimi-0.1.0.dist-info/METADATA +1062 -0
- irimi-0.1.0.dist-info/RECORD +63 -0
- irimi-0.1.0.dist-info/WHEEL +4 -0
- irimi-0.1.0.dist-info/entry_points.txt +2 -0
- irimi-0.1.0.dist-info/licenses/LICENSE +202 -0
irimi/__init__.py
ADDED
irimi/__main__.py
ADDED
irimi/bodies.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""What a request or response body says, parsed without ever raising.
|
|
2
|
+
|
|
3
|
+
`reflect` reads a request's own fields - a JSON object, or a form body with Stripe's bracketed
|
|
4
|
+
encoding - and `json_object` reads a response's. They are the one parser for each, shared by the
|
|
5
|
+
faker (`echo`), the write log, the idempotency store, the overlay, the policy and the summary, so
|
|
6
|
+
all of them see the same view of one body. Nothing here raises: every caller is on the answer
|
|
7
|
+
path of a mitmproxy hook, where a raise forwards the flow and a forwarded write escapes shadow
|
|
8
|
+
mode. Layer 1: it imports only `exchange`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import math
|
|
13
|
+
import re
|
|
14
|
+
from collections.abc import Iterable
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import parse_qsl
|
|
17
|
+
|
|
18
|
+
from irimi.exchange import Request, media_type
|
|
19
|
+
|
|
20
|
+
JSON_CT = "application/json"
|
|
21
|
+
FORM_CT = "application/x-www-form-urlencoded"
|
|
22
|
+
|
|
23
|
+
# One bracket segment of a form field name: the `[order_id]` of `metadata[order_id]`.
|
|
24
|
+
_BRACKET = re.compile(r"\[([^\[\]]*)\]")
|
|
25
|
+
# What `_split_key` returns for the one empty bracket pair it understands, `expand[]`. A real
|
|
26
|
+
# segment can never be this: `_BRACKET` captures what is between the brackets, so a key spelling
|
|
27
|
+
# `[]` out literally arrives as the two characters and not as this marker.
|
|
28
|
+
APPEND = "[]"
|
|
29
|
+
# How deep a bracket path may nest before the key is kept flat instead. Stripe's deepest real key
|
|
30
|
+
# is `line_items[0][price_data][product_data][name]`, four levels; a hostile body can otherwise
|
|
31
|
+
# nest thousands, and unwinding one that deep is a RecursionError inside a mitmproxy hook.
|
|
32
|
+
_MAX_FORM_DEPTH = 8
|
|
33
|
+
|
|
34
|
+
# A form value that is a canonical decimal integer of at most 15 digits is echoed as a number:
|
|
35
|
+
# stripe-python posts `amount=4900` and the agent that reads `refund.amount` wants 4900 back.
|
|
36
|
+
# "007" and a 20-digit account number are not canonical, so they stay strings - coercing them
|
|
37
|
+
# would hand back something other than what the caller sent, and 15 digits is the floor where an
|
|
38
|
+
# integer still survives a JSON parser that stores numbers as doubles.
|
|
39
|
+
_INTEGER = re.compile(r"0|[1-9][0-9]{0,14}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def content_type(request: Request) -> str:
|
|
43
|
+
"""The request's content type without parameters, lower-cased. "" when there is none."""
|
|
44
|
+
return media_type(request.header("content-type") or "")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _form_value(value: str) -> Any:
|
|
48
|
+
return int(value) if _INTEGER.fullmatch(value) else value
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _is_json(ct: str) -> bool:
|
|
52
|
+
"""Every content type that carries a JSON document.
|
|
53
|
+
|
|
54
|
+
RFC 6839's `+json` structured suffix covers `application/vnd.api+json` and
|
|
55
|
+
`application/json-patch+json`; `text/json` is a legacy spelling clients still send. Before
|
|
56
|
+
this, only the exact `application/json` was parsed and the rest reflected nothing, which is
|
|
57
|
+
indistinguishable from a malformed body (#29).
|
|
58
|
+
"""
|
|
59
|
+
return ct == JSON_CT or ct == "text/json" or ct.endswith("+json")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _has_non_finite(value: Any) -> bool:
|
|
63
|
+
"""True when `value` holds a float `json.dumps` would write as NaN, Infinity or -Infinity.
|
|
64
|
+
|
|
65
|
+
json.loads accepts all three and json.dumps writes them straight back out, so the echo would
|
|
66
|
+
be a body a strict JSON parser refuses. This keeps them out of the single `json.dumps` in
|
|
67
|
+
`fake_response`; the `try` in `answer` is what makes that call safe outright. It replaces a
|
|
68
|
+
throwaway serialization of the whole body, which cost a second full pass over a large one and
|
|
69
|
+
was discarded either way (#29).
|
|
70
|
+
"""
|
|
71
|
+
if isinstance(value, float):
|
|
72
|
+
return not math.isfinite(value)
|
|
73
|
+
if isinstance(value, dict):
|
|
74
|
+
return any(_has_non_finite(v) for v in value.values())
|
|
75
|
+
if isinstance(value, list):
|
|
76
|
+
return any(_has_non_finite(v) for v in value)
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _split_key(key: str) -> tuple[str, list[str]]:
|
|
81
|
+
"""`metadata[order_id]` -> `("metadata", ["order_id"])`; `a[0][b]` -> `("a", ["0", "b"])`.
|
|
82
|
+
|
|
83
|
+
`expand[]` -> `("expand", [APPEND])`: an empty bracket pair on its own is the one bracketed
|
|
84
|
+
shape with an unambiguous meaning, and it is Stripe's own documented `curl` spelling for a
|
|
85
|
+
repeated array field. It stayed flat before, so `expand[]=a&expand[]=b` echoed the literal
|
|
86
|
+
JSON key `"expand[]"` (#33).
|
|
87
|
+
|
|
88
|
+
A key with no brackets, or bracketed in a shape we will not guess at - `a[b`, `a[b]c`,
|
|
89
|
+
`a[[b]]`, `a[][b]`, `[b]`, or more than `_MAX_FORM_DEPTH` levels - comes back with no segments
|
|
90
|
+
and stays flat. Echoing such a key unchanged is wrong in a small, visible way; guessing at its
|
|
91
|
+
structure is wrong in an unpredictable one.
|
|
92
|
+
"""
|
|
93
|
+
head, bracket, rest = key.partition("[")
|
|
94
|
+
if not bracket or not head:
|
|
95
|
+
return key, []
|
|
96
|
+
tail = bracket + rest
|
|
97
|
+
segments = _BRACKET.findall(tail)
|
|
98
|
+
if not segments or len(segments) > _MAX_FORM_DEPTH:
|
|
99
|
+
return key, []
|
|
100
|
+
if "".join(f"[{s}]" for s in segments) != tail:
|
|
101
|
+
return key, []
|
|
102
|
+
if segments == [""]:
|
|
103
|
+
return head, [APPEND]
|
|
104
|
+
if "" in segments: # `a[][b]`, `a[b][]`: an append in the middle of a path means nothing here
|
|
105
|
+
return key, []
|
|
106
|
+
return head, segments
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _is_string_valued(names: Iterable[str]) -> bool:
|
|
110
|
+
"""True when a value reached through these field names is one the caller chose the text of.
|
|
111
|
+
|
|
112
|
+
`STRING_KEYED_FIELDS` names the fields whose *keys* are the caller's, and their values are the
|
|
113
|
+
caller's for the same reason: a Stripe metadata value is always a string on the live API, so
|
|
114
|
+
coercing `metadata[order_id]=6735` to an int hands back something other than what was sent
|
|
115
|
+
(#27). Anywhere else a nested value is coerced exactly like a top-level one.
|
|
116
|
+
"""
|
|
117
|
+
return any(name in STRING_KEYED_FIELDS for name in names)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _assign(node: dict[str, Any], head: str, segments: list[str], value: str) -> None:
|
|
121
|
+
"""Walk the bracket path, creating a dict per level, and set the leaf.
|
|
122
|
+
|
|
123
|
+
The leaf is coerced by `_form_value` unless some name on the way to it is a
|
|
124
|
+
`STRING_KEYED_FIELDS` one. `line_items[0][quantity]=2` echoed the string `"2"` while the same
|
|
125
|
+
number at the top level echoed `2`, so `quantity * 2` was `"22"` with no raise (#33).
|
|
126
|
+
|
|
127
|
+
An existing dict at the leaf is left alone: `a[0][b]=1&a[0]=2` and `a[0]=2&a[0][b]=1` both keep
|
|
128
|
+
the structure, which is the rule `parse_form` already applies to a bare key one level up.
|
|
129
|
+
"""
|
|
130
|
+
for segment in segments[:-1]:
|
|
131
|
+
child = node.get(segment)
|
|
132
|
+
if not isinstance(child, dict):
|
|
133
|
+
child = {}
|
|
134
|
+
node[segment] = child
|
|
135
|
+
node = child
|
|
136
|
+
leaf = segments[-1]
|
|
137
|
+
if isinstance(node.get(leaf), dict):
|
|
138
|
+
return
|
|
139
|
+
node[leaf] = value if _is_string_valued((head, *segments)) else _form_value(value)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# Fields whose keys are arbitrary strings chosen by the caller, so `0`, `1`, ... are key names
|
|
143
|
+
# and not array indices. `metadata[0]=zero` and `expand[0]=charge` are byte-wise the same shape on
|
|
144
|
+
# the wire; the field name is the only thing that tells them apart, so it is the field name that
|
|
145
|
+
# decides. Stripe, Slack and Segment all spell this field `metadata`.
|
|
146
|
+
STRING_KEYED_FIELDS: frozenset[str] = frozenset({"metadata"})
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _to_lists(node: Any, field: str = "") -> Any:
|
|
150
|
+
"""Depth first, a dict whose keys are exactly `0`..`n-1` becomes a list.
|
|
151
|
+
|
|
152
|
+
Stripe form-encodes an array as `expand[0]=a&expand[1]=b` and the live API answers with a
|
|
153
|
+
JSON array. A gap, a repeat or an out-of-range index leaves it a dict: inventing the missing
|
|
154
|
+
elements would echo fields the caller never sent. The comparison is against canonical decimal
|
|
155
|
+
strings, so "007" and non-ASCII digits cannot reach it - `str.isdigit()` would let both in.
|
|
156
|
+
|
|
157
|
+
A `STRING_KEYED_FIELDS` name is never promoted, at any depth: `metadata[0]=zero` is the key
|
|
158
|
+
`"0"`, which the live API answers as `{"metadata": {"0": "zero"}}`. Promoting it hands the
|
|
159
|
+
agent a list, and `refund.metadata["0"]` then raises TypeError instead of returning the value
|
|
160
|
+
the caller just sent - #27's failure class moved one step along.
|
|
161
|
+
"""
|
|
162
|
+
if not isinstance(node, dict):
|
|
163
|
+
return node
|
|
164
|
+
converted = {key: _to_lists(value, key) for key, value in node.items()}
|
|
165
|
+
if field in STRING_KEYED_FIELDS:
|
|
166
|
+
return converted
|
|
167
|
+
if converted and set(converted) == {str(i) for i in range(len(converted))}:
|
|
168
|
+
return [converted[str(i)] for i in range(len(converted))]
|
|
169
|
+
return converted
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def parse_form(text: str) -> dict[str, Any]:
|
|
173
|
+
"""A form body as the object the live API would answer with (#27, #33).
|
|
174
|
+
|
|
175
|
+
Four rules, one per bug in the flat `dict(parse_qsl(...))` this replaces. A bracket-nested key
|
|
176
|
+
becomes a nested container, so `metadata[order_id]=6735` echoes `metadata` and an SDK can read
|
|
177
|
+
it. `expand[]=a&expand[]=b` becomes the list `expand`. A repeated bare key collects into a
|
|
178
|
+
list instead of keeping only the last value. And a value is coerced by `_form_value` wherever
|
|
179
|
+
it sits, except under a `STRING_KEYED_FIELDS` name.
|
|
180
|
+
|
|
181
|
+
Structure always beats a scalar of the same name, whichever order the two arrive in, and a
|
|
182
|
+
bracket path beats an append. Those are the shapes no real caller sends, so the rule is chosen
|
|
183
|
+
to be *stable* rather than clever: `a[0][b]=1&a[0]=2` and `a[0]=2&a[0][b]=1` echo the same
|
|
184
|
+
thing, which is what stops the echo from depending on dict ordering (#33).
|
|
185
|
+
"""
|
|
186
|
+
root: dict[str, Any] = {}
|
|
187
|
+
bare: dict[str, list[Any]] = {}
|
|
188
|
+
appended: dict[str, list[Any]] = {}
|
|
189
|
+
for key, value in parse_qsl(text, keep_blank_values=True):
|
|
190
|
+
head, segments = _split_key(key)
|
|
191
|
+
if not segments:
|
|
192
|
+
if isinstance(root.get(head), dict) or head in appended:
|
|
193
|
+
continue
|
|
194
|
+
bare.setdefault(head, []).append(_form_value(value))
|
|
195
|
+
root.setdefault(head, None) # hold the position; the value is filled in below
|
|
196
|
+
continue
|
|
197
|
+
if segments == [APPEND]:
|
|
198
|
+
if isinstance(root.get(head), dict):
|
|
199
|
+
continue
|
|
200
|
+
bare.pop(head, None)
|
|
201
|
+
item = value if _is_string_valued((head,)) else _form_value(value)
|
|
202
|
+
appended.setdefault(head, []).append(item)
|
|
203
|
+
root.setdefault(head, None)
|
|
204
|
+
continue
|
|
205
|
+
node = root.get(head)
|
|
206
|
+
if not isinstance(node, dict):
|
|
207
|
+
node = {}
|
|
208
|
+
root[head] = node
|
|
209
|
+
bare.pop(head, None)
|
|
210
|
+
appended.pop(head, None)
|
|
211
|
+
_assign(node, head, segments, value)
|
|
212
|
+
for head, items in appended.items():
|
|
213
|
+
root[head] = items
|
|
214
|
+
for head, values in bare.items():
|
|
215
|
+
root[head] = values[0] if len(values) == 1 else values
|
|
216
|
+
return {key: _to_lists(value, key) for key, value in root.items()}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def reflect(request: Request) -> dict[str, Any]:
|
|
220
|
+
"""The request's own fields, as a JSON-serializable dict. Never raises.
|
|
221
|
+
|
|
222
|
+
A JSON content type counts only when the body decodes to an object;
|
|
223
|
+
`application/x-www-form-urlencoded` goes through `parse_form`. Any other content type, and
|
|
224
|
+
any parse failure, reflects nothing.
|
|
225
|
+
"""
|
|
226
|
+
ct = content_type(request)
|
|
227
|
+
try:
|
|
228
|
+
if _is_json(ct):
|
|
229
|
+
parsed = json.loads(request.body)
|
|
230
|
+
if not isinstance(parsed, dict) or _has_non_finite(parsed):
|
|
231
|
+
return {}
|
|
232
|
+
return parsed
|
|
233
|
+
if ct == FORM_CT:
|
|
234
|
+
return parse_form(request.body.decode("utf-8", "replace"))
|
|
235
|
+
except Exception: # a malformed body reflects nothing; it must never reach the caller
|
|
236
|
+
return {}
|
|
237
|
+
return {}
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
# A live body this size is not an object any service's effects model, and parsing it on the answer
|
|
241
|
+
# path would cost more than the read or the check it is trying to improve.
|
|
242
|
+
MAX_BODY_BYTES = 2_000_000
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def json_object(body: bytes) -> dict[str, Any] | None:
|
|
246
|
+
"""`body` as a JSON object, or None when it is not one irimi should decode."""
|
|
247
|
+
if not body or len(body) > MAX_BODY_BYTES:
|
|
248
|
+
return None
|
|
249
|
+
try:
|
|
250
|
+
parsed = json.loads(body)
|
|
251
|
+
except Exception:
|
|
252
|
+
return None
|
|
253
|
+
return parsed if isinstance(parsed, dict) else None
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
# Fields of a fixture object the service owns, which the request may therefore never write over.
|
|
257
|
+
# `id` is here as well as in every route's `ids:`, because a body posting `object=charge` to a
|
|
258
|
+
# refund route would otherwise hand stripe-python the wrong class to build, and `created` and
|
|
259
|
+
# `livemode` are facts about this answer rather than values the caller gets to choose.
|
|
260
|
+
# The read side keeps the same rule: `services.stripe._customer` may not move one.
|
|
261
|
+
SERVICE_OWNED: frozenset[str] = frozenset({"id", "object", "created", "livemode"})
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def is_int(value: Any) -> bool:
|
|
265
|
+
"""A JSON integer: an `int` that is not a `bool`, which Python counts as one."""
|
|
266
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
irimi/ca.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import datetime as dt
|
|
2
|
+
import os
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from cryptography import x509
|
|
7
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
8
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
9
|
+
from cryptography.x509.oid import NameOID
|
|
10
|
+
|
|
11
|
+
from irimi import paths
|
|
12
|
+
|
|
13
|
+
CA_COMMON_NAME = "irimi local CA"
|
|
14
|
+
CA_VALID_DAYS = 3650
|
|
15
|
+
KEY_MODE = 0o600
|
|
16
|
+
CERT_MODE = 0o644
|
|
17
|
+
DIR_MODE = 0o700
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class CAPaths:
|
|
22
|
+
key: Path
|
|
23
|
+
cert: Path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def ca_paths() -> CAPaths:
|
|
27
|
+
d = paths.ca_dir()
|
|
28
|
+
return CAPaths(key=d / paths.CA_KEY_NAME, cert=d / paths.CA_CERT_NAME)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ca_exists(p: CAPaths) -> bool:
|
|
32
|
+
"""True only when both the key and the cert are present."""
|
|
33
|
+
return p.key.is_file() and p.cert.is_file()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def ca_partial(p: CAPaths) -> bool:
|
|
37
|
+
"""True when exactly one of key/cert is present (a broken or interrupted init)."""
|
|
38
|
+
return p.key.is_file() != p.cert.is_file()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def generate_ca(p: CAPaths) -> None:
|
|
42
|
+
"""Generate a self-signed CA and write key (0600) and cert (0644). Overwrites if present."""
|
|
43
|
+
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
44
|
+
name = x509.Name(
|
|
45
|
+
[
|
|
46
|
+
x509.NameAttribute(NameOID.COMMON_NAME, CA_COMMON_NAME),
|
|
47
|
+
x509.NameAttribute(NameOID.ORGANIZATION_NAME, "irimi"),
|
|
48
|
+
]
|
|
49
|
+
)
|
|
50
|
+
now = dt.datetime.now(dt.UTC)
|
|
51
|
+
cert = (
|
|
52
|
+
x509.CertificateBuilder()
|
|
53
|
+
.subject_name(name)
|
|
54
|
+
.issuer_name(name)
|
|
55
|
+
.public_key(key.public_key())
|
|
56
|
+
.serial_number(x509.random_serial_number())
|
|
57
|
+
.not_valid_before(now - dt.timedelta(days=1))
|
|
58
|
+
.not_valid_after(now + dt.timedelta(days=CA_VALID_DAYS))
|
|
59
|
+
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
|
|
60
|
+
.add_extension(
|
|
61
|
+
x509.KeyUsage(
|
|
62
|
+
digital_signature=False,
|
|
63
|
+
content_commitment=False,
|
|
64
|
+
key_encipherment=False,
|
|
65
|
+
data_encipherment=False,
|
|
66
|
+
key_agreement=False,
|
|
67
|
+
key_cert_sign=True,
|
|
68
|
+
crl_sign=True,
|
|
69
|
+
encipher_only=False,
|
|
70
|
+
decipher_only=False,
|
|
71
|
+
),
|
|
72
|
+
critical=True,
|
|
73
|
+
)
|
|
74
|
+
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
|
|
75
|
+
.sign(key, hashes.SHA256())
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
key_pem = key.private_bytes(
|
|
79
|
+
encoding=serialization.Encoding.PEM,
|
|
80
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
81
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
82
|
+
)
|
|
83
|
+
cert_pem = cert.public_bytes(serialization.Encoding.PEM)
|
|
84
|
+
|
|
85
|
+
p.key.parent.mkdir(parents=True, exist_ok=True)
|
|
86
|
+
os.chmod(p.key.parent, DIR_MODE)
|
|
87
|
+
_write_with_mode(p.key, key_pem, KEY_MODE)
|
|
88
|
+
_write_with_mode(p.cert, cert_pem, CERT_MODE)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _write_with_mode(path: Path, data: bytes, mode: int) -> None:
|
|
92
|
+
"""Create-or-truncate `path` with `mode`, never leaving it world-readable in between.
|
|
93
|
+
|
|
94
|
+
Refuses to follow a symlink at `path`, and fixes the mode on the open descriptor
|
|
95
|
+
before any bytes are written (O_CREAT's mode is subject to umask and ignored when
|
|
96
|
+
the file already exists).
|
|
97
|
+
"""
|
|
98
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, mode)
|
|
99
|
+
with os.fdopen(fd, "wb") as f:
|
|
100
|
+
os.fchmod(fd, mode)
|
|
101
|
+
f.write(data)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def write_mitm_bundle(p: CAPaths, confdir: Path) -> Path:
|
|
105
|
+
"""Write <confdir>/mitmproxy-ca.pem = CA key + CA cert (mode 0600), the file mitmproxy's
|
|
106
|
+
TlsConfig loads to mint per-host leaf certs. Always rewritten so `init --force` is picked up."""
|
|
107
|
+
bundle = confdir / paths.MITM_CA_BUNDLE_NAME
|
|
108
|
+
confdir.mkdir(parents=True, exist_ok=True)
|
|
109
|
+
os.chmod(confdir, DIR_MODE)
|
|
110
|
+
_write_with_mode(bundle, p.key.read_bytes() + p.cert.read_bytes(), KEY_MODE)
|
|
111
|
+
return bundle
|