datapi-selfheal 0.3.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.
- datapi_selfheal-0.3.0.dist-info/METADATA +313 -0
- datapi_selfheal-0.3.0.dist-info/RECORD +35 -0
- datapi_selfheal-0.3.0.dist-info/WHEEL +5 -0
- datapi_selfheal-0.3.0.dist-info/entry_points.txt +3 -0
- datapi_selfheal-0.3.0.dist-info/licenses/LICENSE +21 -0
- datapi_selfheal-0.3.0.dist-info/top_level.txt +3 -0
- selfheal_api/__init__.py +106 -0
- selfheal_api/_sandbox_exec.py +124 -0
- selfheal_api/autoheal.py +658 -0
- selfheal_api/billing.py +738 -0
- selfheal_api/cli.py +958 -0
- selfheal_api/dashboard.py +1094 -0
- selfheal_api/eval_fixtures.py +39 -0
- selfheal_api/github_app.py +1050 -0
- selfheal_api/github_jwt.py +145 -0
- selfheal_api/ledger.py +305 -0
- selfheal_api/metrics.py +259 -0
- selfheal_api/middleware.py +297 -0
- selfheal_api/modelgen.py +333 -0
- selfheal_api/notifier.py +426 -0
- selfheal_api/remediation.py +277 -0
- selfheal_api/replay.py +126 -0
- selfheal_api/sandbox.py +157 -0
- selfheal_api/server.py +1480 -0
- selfheal_api/server_hosted.py +1656 -0
- selfheal_api/specwatch.py +203 -0
- selfheal_api/worker.py +212 -0
- sentinel/__init__.py +33 -0
- sentinel/detector.py +626 -0
- sentinel/guard.py +345 -0
- sentinel/llm_fallback.py +256 -0
- synthesizer/__init__.py +31 -0
- synthesizer/openapi_emitter.py +181 -0
- synthesizer/patcher.py +944 -0
- synthesizer/zod_emitter.py +336 -0
|
@@ -0,0 +1,1050 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import re
|
|
8
|
+
import sqlite3
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
import urllib.error
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import urllib.request
|
|
14
|
+
from collections.abc import Iterable
|
|
15
|
+
from datetime import datetime
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, Protocol, runtime_checkable
|
|
18
|
+
|
|
19
|
+
from pydantic import BaseModel, ConfigDict
|
|
20
|
+
|
|
21
|
+
from selfheal_api.github_jwt import JwtError, mint_app_jwt
|
|
22
|
+
|
|
23
|
+
_GITHUB_API_VERSION = "2022-11-28"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def verify_webhook_signature(secret: str, body: bytes, signature_header: str) -> bool:
|
|
27
|
+
"""Verify HMAC-SHA256 webhook signature (`sha256=<hex>`)."""
|
|
28
|
+
if not secret or not signature_header:
|
|
29
|
+
return False
|
|
30
|
+
header = signature_header.strip()
|
|
31
|
+
if not header.lower().startswith("sha256="):
|
|
32
|
+
return False
|
|
33
|
+
provided_sig = f"sha256={header[7:].lower()}"
|
|
34
|
+
digest = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
|
|
35
|
+
expected_sig = f"sha256={digest}"
|
|
36
|
+
return hmac.compare_digest(expected_sig, provided_sig)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class InstallationRecord(BaseModel):
|
|
40
|
+
"""Immutable record of a GitHub App installation for an organization."""
|
|
41
|
+
|
|
42
|
+
model_config = ConfigDict(frozen=True)
|
|
43
|
+
|
|
44
|
+
installation_id: int
|
|
45
|
+
org_id: str
|
|
46
|
+
account_login: str
|
|
47
|
+
repositories: tuple[str, ...] = ()
|
|
48
|
+
suspended: bool = False
|
|
49
|
+
auto_heal_enabled: bool = False
|
|
50
|
+
auto_heal_allowed_kinds: tuple[str, ...] = ()
|
|
51
|
+
installed_by: str | None = None
|
|
52
|
+
alert_email: str | None = None
|
|
53
|
+
pagerduty_routing_key: str | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class InstallationRegistry:
|
|
57
|
+
"""Thread-safe SQLite-backed registry mapping org_id and installation_id to installations."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, db_path: str | Path = ":memory:") -> None:
|
|
60
|
+
resolved_path = str(db_path)
|
|
61
|
+
if resolved_path != ":memory:" and not resolved_path.startswith("file:"):
|
|
62
|
+
Path(resolved_path).parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
|
|
64
|
+
self._lock = threading.Lock()
|
|
65
|
+
self._closed = False
|
|
66
|
+
self._conn = sqlite3.connect(resolved_path, check_same_thread=False)
|
|
67
|
+
self._initialize_schema()
|
|
68
|
+
|
|
69
|
+
def _initialize_schema(self) -> None:
|
|
70
|
+
with self._lock:
|
|
71
|
+
self._conn.execute("PRAGMA busy_timeout=5000;")
|
|
72
|
+
self._conn.execute("PRAGMA journal_mode=WAL")
|
|
73
|
+
self._conn.execute(
|
|
74
|
+
"""
|
|
75
|
+
CREATE TABLE IF NOT EXISTS installations (
|
|
76
|
+
installation_id INTEGER PRIMARY KEY,
|
|
77
|
+
org_id TEXT NOT NULL UNIQUE,
|
|
78
|
+
account_login TEXT NOT NULL,
|
|
79
|
+
repositories_json TEXT NOT NULL,
|
|
80
|
+
suspended INTEGER NOT NULL,
|
|
81
|
+
installed_at REAL NOT NULL,
|
|
82
|
+
auto_heal_enabled INTEGER NOT NULL DEFAULT 0,
|
|
83
|
+
installed_by TEXT,
|
|
84
|
+
alert_email TEXT,
|
|
85
|
+
pagerduty_routing_key TEXT
|
|
86
|
+
)
|
|
87
|
+
"""
|
|
88
|
+
)
|
|
89
|
+
self._migrate_installations_schema()
|
|
90
|
+
self._conn.commit()
|
|
91
|
+
|
|
92
|
+
def _migrate_installations_schema(self) -> None:
|
|
93
|
+
"""Idempotent column adds for pre-migration installations tables."""
|
|
94
|
+
existing = {
|
|
95
|
+
str(row[1])
|
|
96
|
+
for row in self._conn.execute("PRAGMA table_info(installations)")
|
|
97
|
+
}
|
|
98
|
+
for column, ddl in (
|
|
99
|
+
(
|
|
100
|
+
"auto_heal_enabled",
|
|
101
|
+
"ALTER TABLE installations ADD COLUMN auto_heal_enabled"
|
|
102
|
+
" INTEGER NOT NULL DEFAULT 0",
|
|
103
|
+
),
|
|
104
|
+
("installed_by", "ALTER TABLE installations ADD COLUMN installed_by TEXT"),
|
|
105
|
+
("alert_email", "ALTER TABLE installations ADD COLUMN alert_email TEXT"),
|
|
106
|
+
(
|
|
107
|
+
"pagerduty_routing_key",
|
|
108
|
+
"ALTER TABLE installations ADD COLUMN pagerduty_routing_key TEXT",
|
|
109
|
+
),
|
|
110
|
+
(
|
|
111
|
+
"auto_heal_allowed_kinds",
|
|
112
|
+
"ALTER TABLE installations ADD COLUMN auto_heal_allowed_kinds TEXT",
|
|
113
|
+
),
|
|
114
|
+
):
|
|
115
|
+
if column not in existing:
|
|
116
|
+
self._conn.execute(ddl)
|
|
117
|
+
|
|
118
|
+
_SELECT_COLS = (
|
|
119
|
+
"installation_id, org_id, account_login, repositories_json, suspended,"
|
|
120
|
+
" auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,"
|
|
121
|
+
" pagerduty_routing_key"
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
@staticmethod
|
|
125
|
+
def _parse_kinds_column(value: Any) -> tuple[str, ...]:
|
|
126
|
+
if value is None:
|
|
127
|
+
return ()
|
|
128
|
+
try:
|
|
129
|
+
parsed = json.loads(str(value))
|
|
130
|
+
except (json.JSONDecodeError, TypeError):
|
|
131
|
+
return ()
|
|
132
|
+
if not isinstance(parsed, list):
|
|
133
|
+
return ()
|
|
134
|
+
return tuple(str(item) for item in parsed)
|
|
135
|
+
|
|
136
|
+
@staticmethod
|
|
137
|
+
def _row_to_record(row: tuple[Any, ...]) -> InstallationRecord:
|
|
138
|
+
raw_repos = json.loads(str(row[3]))
|
|
139
|
+
repos = tuple(str(item) for item in raw_repos) if isinstance(raw_repos, list) else ()
|
|
140
|
+
return InstallationRecord(
|
|
141
|
+
installation_id=int(row[0]),
|
|
142
|
+
org_id=str(row[1]),
|
|
143
|
+
account_login=str(row[2]),
|
|
144
|
+
repositories=repos,
|
|
145
|
+
suspended=bool(int(row[4])),
|
|
146
|
+
auto_heal_enabled=bool(int(row[5])) if len(row) > 5 else False,
|
|
147
|
+
auto_heal_allowed_kinds=InstallationRegistry._parse_kinds_column(
|
|
148
|
+
row[6] if len(row) > 6 else None
|
|
149
|
+
),
|
|
150
|
+
installed_by=str(row[7]) if len(row) > 7 and row[7] is not None else None,
|
|
151
|
+
alert_email=str(row[8]) if len(row) > 8 and row[8] is not None else None,
|
|
152
|
+
pagerduty_routing_key=(
|
|
153
|
+
str(row[9]) if len(row) > 9 and row[9] is not None else None
|
|
154
|
+
),
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def upsert(self, record: InstallationRecord) -> InstallationRecord:
|
|
158
|
+
"""Insert or replace an installation record."""
|
|
159
|
+
now = time.time()
|
|
160
|
+
repos_json = json.dumps(list(record.repositories))
|
|
161
|
+
suspended_int = 1 if record.suspended else 0
|
|
162
|
+
with self._lock:
|
|
163
|
+
self._conn.execute(
|
|
164
|
+
"DELETE FROM installations WHERE org_id = ? AND installation_id != ?",
|
|
165
|
+
(record.org_id, record.installation_id),
|
|
166
|
+
)
|
|
167
|
+
self._conn.execute(
|
|
168
|
+
"""
|
|
169
|
+
INSERT INTO installations (
|
|
170
|
+
installation_id,
|
|
171
|
+
org_id,
|
|
172
|
+
account_login,
|
|
173
|
+
repositories_json,
|
|
174
|
+
suspended,
|
|
175
|
+
installed_at
|
|
176
|
+
) VALUES (?, ?, ?, ?, ?, ?)
|
|
177
|
+
ON CONFLICT(installation_id) DO UPDATE SET
|
|
178
|
+
org_id = excluded.org_id,
|
|
179
|
+
account_login = excluded.account_login,
|
|
180
|
+
repositories_json = excluded.repositories_json,
|
|
181
|
+
suspended = excluded.suspended,
|
|
182
|
+
installed_at = excluded.installed_at
|
|
183
|
+
""",
|
|
184
|
+
(
|
|
185
|
+
record.installation_id,
|
|
186
|
+
record.org_id,
|
|
187
|
+
record.account_login,
|
|
188
|
+
repos_json,
|
|
189
|
+
suspended_int,
|
|
190
|
+
now,
|
|
191
|
+
),
|
|
192
|
+
)
|
|
193
|
+
self._conn.commit()
|
|
194
|
+
return record
|
|
195
|
+
|
|
196
|
+
def list_org_ids(self) -> list[str]:
|
|
197
|
+
with self._lock:
|
|
198
|
+
rows = self._conn.execute(
|
|
199
|
+
"SELECT org_id FROM installations ORDER BY org_id ASC"
|
|
200
|
+
).fetchall()
|
|
201
|
+
return [str(row[0]) for row in rows]
|
|
202
|
+
|
|
203
|
+
def remove(self, installation_id: int) -> InstallationRecord | None:
|
|
204
|
+
"""Remove an installation by installation_id, returning it if present."""
|
|
205
|
+
with self._lock:
|
|
206
|
+
row = self._conn.execute(
|
|
207
|
+
"""
|
|
208
|
+
SELECT installation_id, org_id, account_login, repositories_json, suspended,
|
|
209
|
+
auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,
|
|
210
|
+
pagerduty_routing_key
|
|
211
|
+
FROM installations
|
|
212
|
+
WHERE installation_id = ?
|
|
213
|
+
""",
|
|
214
|
+
(installation_id,),
|
|
215
|
+
).fetchone()
|
|
216
|
+
if row is None:
|
|
217
|
+
return None
|
|
218
|
+
self._conn.execute(
|
|
219
|
+
"DELETE FROM installations WHERE installation_id = ?",
|
|
220
|
+
(installation_id,),
|
|
221
|
+
)
|
|
222
|
+
self._conn.commit()
|
|
223
|
+
return self._row_to_record(row)
|
|
224
|
+
|
|
225
|
+
def add_repositories(
|
|
226
|
+
self, installation_id: int, repos: Iterable[str]
|
|
227
|
+
) -> InstallationRecord | None:
|
|
228
|
+
"""Add repositories to an existing installation, preserving order."""
|
|
229
|
+
with self._lock:
|
|
230
|
+
row = self._conn.execute(
|
|
231
|
+
"""
|
|
232
|
+
SELECT installation_id, org_id, account_login, repositories_json, suspended,
|
|
233
|
+
auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,
|
|
234
|
+
pagerduty_routing_key
|
|
235
|
+
FROM installations
|
|
236
|
+
WHERE installation_id = ?
|
|
237
|
+
""",
|
|
238
|
+
(installation_id,),
|
|
239
|
+
).fetchone()
|
|
240
|
+
if row is None:
|
|
241
|
+
return None
|
|
242
|
+
record = self._row_to_record(row)
|
|
243
|
+
merged = tuple(dict.fromkeys([*record.repositories, *repos]))
|
|
244
|
+
updated = record.model_copy(update={"repositories": merged})
|
|
245
|
+
self._conn.execute(
|
|
246
|
+
"UPDATE installations SET repositories_json = ? WHERE installation_id = ?",
|
|
247
|
+
(json.dumps(list(merged)), installation_id),
|
|
248
|
+
)
|
|
249
|
+
self._conn.commit()
|
|
250
|
+
return updated
|
|
251
|
+
|
|
252
|
+
def remove_repositories(
|
|
253
|
+
self, installation_id: int, repos: Iterable[str]
|
|
254
|
+
) -> InstallationRecord | None:
|
|
255
|
+
"""Remove repositories from an existing installation."""
|
|
256
|
+
to_remove = set(repos)
|
|
257
|
+
with self._lock:
|
|
258
|
+
row = self._conn.execute(
|
|
259
|
+
"""
|
|
260
|
+
SELECT installation_id, org_id, account_login, repositories_json, suspended,
|
|
261
|
+
auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,
|
|
262
|
+
pagerduty_routing_key
|
|
263
|
+
FROM installations
|
|
264
|
+
WHERE installation_id = ?
|
|
265
|
+
""",
|
|
266
|
+
(installation_id,),
|
|
267
|
+
).fetchone()
|
|
268
|
+
if row is None:
|
|
269
|
+
return None
|
|
270
|
+
record = self._row_to_record(row)
|
|
271
|
+
remaining = tuple(r for r in record.repositories if r not in to_remove)
|
|
272
|
+
updated = record.model_copy(update={"repositories": remaining})
|
|
273
|
+
self._conn.execute(
|
|
274
|
+
"UPDATE installations SET repositories_json = ? WHERE installation_id = ?",
|
|
275
|
+
(json.dumps(list(remaining)), installation_id),
|
|
276
|
+
)
|
|
277
|
+
self._conn.commit()
|
|
278
|
+
return updated
|
|
279
|
+
|
|
280
|
+
def set_suspended(
|
|
281
|
+
self, installation_id: int, suspended: bool
|
|
282
|
+
) -> InstallationRecord | None:
|
|
283
|
+
"""Update the suspended flag for an existing installation."""
|
|
284
|
+
with self._lock:
|
|
285
|
+
row = self._conn.execute(
|
|
286
|
+
"""
|
|
287
|
+
SELECT installation_id, org_id, account_login, repositories_json, suspended,
|
|
288
|
+
auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,
|
|
289
|
+
pagerduty_routing_key
|
|
290
|
+
FROM installations
|
|
291
|
+
WHERE installation_id = ?
|
|
292
|
+
""",
|
|
293
|
+
(installation_id,),
|
|
294
|
+
).fetchone()
|
|
295
|
+
if row is None:
|
|
296
|
+
return None
|
|
297
|
+
record = self._row_to_record(row)
|
|
298
|
+
updated = record.model_copy(update={"suspended": suspended})
|
|
299
|
+
self._conn.execute(
|
|
300
|
+
"UPDATE installations SET suspended = ? WHERE installation_id = ?",
|
|
301
|
+
(1 if suspended else 0, installation_id),
|
|
302
|
+
)
|
|
303
|
+
self._conn.commit()
|
|
304
|
+
return updated
|
|
305
|
+
|
|
306
|
+
def update_org_settings(
|
|
307
|
+
self,
|
|
308
|
+
org_id: str,
|
|
309
|
+
*,
|
|
310
|
+
alert_email: str | None = None,
|
|
311
|
+
pagerduty_routing_key: str | None = None,
|
|
312
|
+
auto_heal_enabled: bool | None = None,
|
|
313
|
+
auto_heal_allowed_kinds: list[str] | tuple[str, ...] | None = None,
|
|
314
|
+
installed_by: str | None = None,
|
|
315
|
+
) -> InstallationRecord | None:
|
|
316
|
+
"""Update per-org alerting/automation settings; None leaves unchanged."""
|
|
317
|
+
sets: list[str] = []
|
|
318
|
+
params: list[Any] = []
|
|
319
|
+
if alert_email is not None:
|
|
320
|
+
sets.append("alert_email = ?")
|
|
321
|
+
params.append(alert_email)
|
|
322
|
+
if pagerduty_routing_key is not None:
|
|
323
|
+
sets.append("pagerduty_routing_key = ?")
|
|
324
|
+
params.append(pagerduty_routing_key)
|
|
325
|
+
if auto_heal_enabled is not None:
|
|
326
|
+
sets.append("auto_heal_enabled = ?")
|
|
327
|
+
params.append(1 if auto_heal_enabled else 0)
|
|
328
|
+
if auto_heal_allowed_kinds is not None:
|
|
329
|
+
sets.append("auto_heal_allowed_kinds = ?")
|
|
330
|
+
params.append(json.dumps(sorted(set(auto_heal_allowed_kinds))))
|
|
331
|
+
if installed_by is not None:
|
|
332
|
+
sets.append("installed_by = ?")
|
|
333
|
+
params.append(installed_by)
|
|
334
|
+
if not sets:
|
|
335
|
+
return self.get_by_org(org_id)
|
|
336
|
+
with self._lock:
|
|
337
|
+
cur = self._conn.execute(
|
|
338
|
+
f"UPDATE installations SET {', '.join(sets)} WHERE org_id = ?",
|
|
339
|
+
(*params, org_id),
|
|
340
|
+
)
|
|
341
|
+
self._conn.commit()
|
|
342
|
+
if cur.rowcount == 0:
|
|
343
|
+
return None
|
|
344
|
+
return self.get_by_org(org_id)
|
|
345
|
+
|
|
346
|
+
def get_by_org(self, org_id: str) -> InstallationRecord | None:
|
|
347
|
+
"""Look up an installation record by org_id."""
|
|
348
|
+
with self._lock:
|
|
349
|
+
row = self._conn.execute(
|
|
350
|
+
"""
|
|
351
|
+
SELECT installation_id, org_id, account_login, repositories_json, suspended,
|
|
352
|
+
auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,
|
|
353
|
+
pagerduty_routing_key
|
|
354
|
+
FROM installations
|
|
355
|
+
WHERE org_id = ?
|
|
356
|
+
""",
|
|
357
|
+
(org_id,),
|
|
358
|
+
).fetchone()
|
|
359
|
+
return self._row_to_record(row) if row is not None else None
|
|
360
|
+
|
|
361
|
+
def get_by_installation(self, installation_id: int) -> InstallationRecord | None:
|
|
362
|
+
"""Look up an installation record by installation_id."""
|
|
363
|
+
with self._lock:
|
|
364
|
+
row = self._conn.execute(
|
|
365
|
+
"""
|
|
366
|
+
SELECT installation_id, org_id, account_login, repositories_json, suspended,
|
|
367
|
+
auto_heal_enabled, auto_heal_allowed_kinds, installed_by, alert_email,
|
|
368
|
+
pagerduty_routing_key
|
|
369
|
+
FROM installations
|
|
370
|
+
WHERE installation_id = ?
|
|
371
|
+
""",
|
|
372
|
+
(installation_id,),
|
|
373
|
+
).fetchone()
|
|
374
|
+
return self._row_to_record(row) if row is not None else None
|
|
375
|
+
|
|
376
|
+
def ping(self) -> bool:
|
|
377
|
+
"""Check database connectivity, returning False if closed or on SQLite errors."""
|
|
378
|
+
with self._lock:
|
|
379
|
+
if self._closed:
|
|
380
|
+
return False
|
|
381
|
+
try:
|
|
382
|
+
self._conn.execute("SELECT 1").fetchone()
|
|
383
|
+
except sqlite3.Error:
|
|
384
|
+
return False
|
|
385
|
+
return True
|
|
386
|
+
|
|
387
|
+
def close(self) -> None:
|
|
388
|
+
"""Close the underlying SQLite connection."""
|
|
389
|
+
with self._lock:
|
|
390
|
+
if not self._closed:
|
|
391
|
+
self._conn.close()
|
|
392
|
+
self._closed = True
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _extract_repo_names(raw_repos: Any) -> tuple[str, ...]:
|
|
396
|
+
if not isinstance(raw_repos, list):
|
|
397
|
+
return ()
|
|
398
|
+
names: list[str] = []
|
|
399
|
+
for item in raw_repos:
|
|
400
|
+
if isinstance(item, dict):
|
|
401
|
+
name = item.get("full_name") or item.get("name")
|
|
402
|
+
if isinstance(name, str) and name:
|
|
403
|
+
names.append(name)
|
|
404
|
+
elif isinstance(item, str) and item:
|
|
405
|
+
names.append(item)
|
|
406
|
+
return tuple(dict.fromkeys(names))
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _is_valid_int(value: Any) -> bool:
|
|
410
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def handle_github_webhook(
|
|
414
|
+
secret: str,
|
|
415
|
+
body: bytes,
|
|
416
|
+
signature_header: str,
|
|
417
|
+
event_type: str,
|
|
418
|
+
registry: InstallationRegistry,
|
|
419
|
+
) -> tuple[int, dict[str, Any]]:
|
|
420
|
+
"""Verify and process a GitHub App webhook event."""
|
|
421
|
+
if not verify_webhook_signature(secret, body, signature_header):
|
|
422
|
+
return 401, {"error": "Invalid webhook signature"}
|
|
423
|
+
|
|
424
|
+
try:
|
|
425
|
+
decoded = body.decode("utf-8")
|
|
426
|
+
payload = json.loads(decoded)
|
|
427
|
+
except (UnicodeDecodeError, json.JSONDecodeError):
|
|
428
|
+
return 400, {"error": "Invalid JSON payload"}
|
|
429
|
+
|
|
430
|
+
if not isinstance(payload, dict):
|
|
431
|
+
return 400, {"error": "JSON payload must be an object"}
|
|
432
|
+
|
|
433
|
+
if event_type == "ping":
|
|
434
|
+
return 200, {
|
|
435
|
+
"status": "ok",
|
|
436
|
+
"event": "ping",
|
|
437
|
+
"zen": str(payload.get("zen", "")),
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
if event_type == "installation":
|
|
441
|
+
return _handle_installation_event(payload, registry)
|
|
442
|
+
|
|
443
|
+
if event_type == "installation_repositories":
|
|
444
|
+
return _handle_installation_repositories_event(payload, registry)
|
|
445
|
+
|
|
446
|
+
return 200, {"status": "ignored", "event": event_type}
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _handle_installation_event(
|
|
450
|
+
payload: dict[str, Any],
|
|
451
|
+
registry: InstallationRegistry,
|
|
452
|
+
) -> tuple[int, dict[str, Any]]:
|
|
453
|
+
action = payload.get("action")
|
|
454
|
+
installation = payload.get("installation")
|
|
455
|
+
if not isinstance(installation, dict):
|
|
456
|
+
return 400, {"error": "Missing installation object"}
|
|
457
|
+
|
|
458
|
+
installation_id = installation.get("id")
|
|
459
|
+
if not _is_valid_int(installation_id):
|
|
460
|
+
return 400, {"error": "Missing or invalid installation.id"}
|
|
461
|
+
assert isinstance(installation_id, int)
|
|
462
|
+
|
|
463
|
+
if action == "created":
|
|
464
|
+
account = installation.get("account")
|
|
465
|
+
account_login = ""
|
|
466
|
+
if isinstance(account, dict) and isinstance(account.get("login"), str):
|
|
467
|
+
account_login = account["login"]
|
|
468
|
+
org_id = account_login or f"installation-{installation_id}"
|
|
469
|
+
repos = _extract_repo_names(payload.get("repositories"))
|
|
470
|
+
suspended = installation.get("suspended_at") is not None
|
|
471
|
+
record = InstallationRecord(
|
|
472
|
+
installation_id=installation_id,
|
|
473
|
+
org_id=org_id,
|
|
474
|
+
account_login=account_login,
|
|
475
|
+
repositories=repos,
|
|
476
|
+
suspended=suspended,
|
|
477
|
+
)
|
|
478
|
+
registry.upsert(record)
|
|
479
|
+
return 200, {
|
|
480
|
+
"status": "ok",
|
|
481
|
+
"event": "installation",
|
|
482
|
+
"action": "created",
|
|
483
|
+
"installation_id": installation_id,
|
|
484
|
+
"org_id": org_id,
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
if action == "deleted":
|
|
488
|
+
removed = registry.remove(installation_id)
|
|
489
|
+
return 200, {
|
|
490
|
+
"status": "ok",
|
|
491
|
+
"event": "installation",
|
|
492
|
+
"action": "deleted",
|
|
493
|
+
"installation_id": installation_id,
|
|
494
|
+
"removed": removed is not None,
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
if action == "suspend":
|
|
498
|
+
updated = registry.set_suspended(installation_id, True)
|
|
499
|
+
return 200, {
|
|
500
|
+
"status": "ok",
|
|
501
|
+
"event": "installation",
|
|
502
|
+
"action": "suspend",
|
|
503
|
+
"installation_id": installation_id,
|
|
504
|
+
"updated": updated is not None,
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
if action == "unsuspend":
|
|
508
|
+
updated = registry.set_suspended(installation_id, False)
|
|
509
|
+
return 200, {
|
|
510
|
+
"status": "ok",
|
|
511
|
+
"event": "installation",
|
|
512
|
+
"action": "unsuspend",
|
|
513
|
+
"installation_id": installation_id,
|
|
514
|
+
"updated": updated is not None,
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
return 200, {"status": "ignored", "event": "installation", "action": action}
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _handle_installation_repositories_event(
|
|
521
|
+
payload: dict[str, Any],
|
|
522
|
+
registry: InstallationRegistry,
|
|
523
|
+
) -> tuple[int, dict[str, Any]]:
|
|
524
|
+
action = payload.get("action")
|
|
525
|
+
installation = payload.get("installation")
|
|
526
|
+
if not isinstance(installation, dict):
|
|
527
|
+
return 400, {"error": "Missing installation object"}
|
|
528
|
+
|
|
529
|
+
installation_id = installation.get("id")
|
|
530
|
+
if not _is_valid_int(installation_id):
|
|
531
|
+
return 400, {"error": "Missing or invalid installation.id"}
|
|
532
|
+
assert isinstance(installation_id, int)
|
|
533
|
+
|
|
534
|
+
if action == "added":
|
|
535
|
+
repos = _extract_repo_names(payload.get("repositories_added"))
|
|
536
|
+
updated = registry.add_repositories(installation_id, repos)
|
|
537
|
+
return 200, {
|
|
538
|
+
"status": "ok",
|
|
539
|
+
"event": "installation_repositories",
|
|
540
|
+
"action": "added",
|
|
541
|
+
"installation_id": installation_id,
|
|
542
|
+
"repositories": list(updated.repositories) if updated is not None else [],
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if action == "removed":
|
|
546
|
+
repos = _extract_repo_names(payload.get("repositories_removed"))
|
|
547
|
+
updated = registry.remove_repositories(installation_id, repos)
|
|
548
|
+
return 200, {
|
|
549
|
+
"status": "ok",
|
|
550
|
+
"event": "installation_repositories",
|
|
551
|
+
"action": "removed",
|
|
552
|
+
"installation_id": installation_id,
|
|
553
|
+
"repositories": list(updated.repositories) if updated is not None else [],
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return 200, {
|
|
557
|
+
"status": "ignored",
|
|
558
|
+
"event": "installation_repositories",
|
|
559
|
+
"action": action,
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
@runtime_checkable
|
|
564
|
+
class GitHubAppClient(Protocol):
|
|
565
|
+
"""Protocol for opening pull requests as a GitHub App installation."""
|
|
566
|
+
|
|
567
|
+
def open_pull_request(
|
|
568
|
+
self,
|
|
569
|
+
owner: str,
|
|
570
|
+
repo: str,
|
|
571
|
+
title: str,
|
|
572
|
+
head: str,
|
|
573
|
+
base: str,
|
|
574
|
+
body: str = "",
|
|
575
|
+
draft: bool = False,
|
|
576
|
+
) -> dict[str, Any]:
|
|
577
|
+
"""Open a pull request and return the GitHub PR payload."""
|
|
578
|
+
...
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
class MockGitHubAppClient:
|
|
582
|
+
"""In-memory GitHub App client recording opened PRs for deterministic tests."""
|
|
583
|
+
|
|
584
|
+
def __init__(self) -> None:
|
|
585
|
+
self._lock = threading.Lock()
|
|
586
|
+
self.opened_prs: list[dict[str, Any]] = []
|
|
587
|
+
|
|
588
|
+
def open_pull_request(
|
|
589
|
+
self,
|
|
590
|
+
owner: str,
|
|
591
|
+
repo: str,
|
|
592
|
+
title: str,
|
|
593
|
+
head: str,
|
|
594
|
+
base: str,
|
|
595
|
+
body: str = "",
|
|
596
|
+
draft: bool = False,
|
|
597
|
+
) -> dict[str, Any]:
|
|
598
|
+
with self._lock:
|
|
599
|
+
number = len(self.opened_prs) + 1
|
|
600
|
+
pr: dict[str, Any] = {
|
|
601
|
+
"number": number,
|
|
602
|
+
"html_url": f"https://github.com/{owner}/{repo}/pull/{number}",
|
|
603
|
+
"owner": owner,
|
|
604
|
+
"repo": repo,
|
|
605
|
+
"title": title,
|
|
606
|
+
"head": head,
|
|
607
|
+
"base": base,
|
|
608
|
+
"body": body,
|
|
609
|
+
"draft": draft,
|
|
610
|
+
"state": "open",
|
|
611
|
+
}
|
|
612
|
+
self.opened_prs.append(pr)
|
|
613
|
+
return dict(pr)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
_SLUG_RE = re.compile(r"^[A-Za-z0-9._-]+$")
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def _validate_slug(value: str, field_name: str) -> None:
|
|
620
|
+
if not _SLUG_RE.match(value) or ".." in value:
|
|
621
|
+
raise ValueError(f"Invalid {field_name}: {value!r}")
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
class UrllibGitHubAppClient:
|
|
625
|
+
"""Stdlib urllib.request client using an installation access token."""
|
|
626
|
+
|
|
627
|
+
def __init__(
|
|
628
|
+
self,
|
|
629
|
+
token: str,
|
|
630
|
+
api_base_url: str = "https://api.github.com",
|
|
631
|
+
timeout_seconds: float = 10.0,
|
|
632
|
+
allow_insecure_http: bool = False,
|
|
633
|
+
) -> None:
|
|
634
|
+
if not token:
|
|
635
|
+
raise ValueError("token must be non-empty")
|
|
636
|
+
parsed = urllib.parse.urlparse(api_base_url)
|
|
637
|
+
if not allow_insecure_http:
|
|
638
|
+
if parsed.scheme != "https" or not parsed.netloc:
|
|
639
|
+
raise ValueError(
|
|
640
|
+
"api_base_url must use https:// (or set allow_insecure_http=True)"
|
|
641
|
+
)
|
|
642
|
+
elif parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
643
|
+
raise ValueError("api_base_url must use http:// or https://")
|
|
644
|
+
self._token = token
|
|
645
|
+
self._api_base_url = api_base_url.rstrip("/")
|
|
646
|
+
self._timeout_seconds = timeout_seconds
|
|
647
|
+
|
|
648
|
+
def open_pull_request(
|
|
649
|
+
self,
|
|
650
|
+
owner: str,
|
|
651
|
+
repo: str,
|
|
652
|
+
title: str,
|
|
653
|
+
head: str,
|
|
654
|
+
base: str,
|
|
655
|
+
body: str = "",
|
|
656
|
+
draft: bool = False,
|
|
657
|
+
) -> dict[str, Any]:
|
|
658
|
+
_validate_slug(owner, "owner")
|
|
659
|
+
_validate_slug(repo, "repo")
|
|
660
|
+
url = f"{self._api_base_url}/repos/{owner}/{repo}/pulls"
|
|
661
|
+
payload = json.dumps(
|
|
662
|
+
{
|
|
663
|
+
"title": title,
|
|
664
|
+
"head": head,
|
|
665
|
+
"base": base,
|
|
666
|
+
"body": body,
|
|
667
|
+
"draft": draft,
|
|
668
|
+
}
|
|
669
|
+
).encode("utf-8")
|
|
670
|
+
request = urllib.request.Request(
|
|
671
|
+
url,
|
|
672
|
+
data=payload,
|
|
673
|
+
method="POST",
|
|
674
|
+
headers={
|
|
675
|
+
"Authorization": f"Bearer {self._token}",
|
|
676
|
+
"Accept": "application/vnd.github+json",
|
|
677
|
+
"Content-Type": "application/json",
|
|
678
|
+
"X-GitHub-Api-Version": _GITHUB_API_VERSION,
|
|
679
|
+
"User-Agent": "selfheal-api",
|
|
680
|
+
},
|
|
681
|
+
)
|
|
682
|
+
with urllib.request.urlopen(request, timeout=self._timeout_seconds) as response:
|
|
683
|
+
raw = response.read().decode("utf-8")
|
|
684
|
+
parsed = json.loads(raw)
|
|
685
|
+
if not isinstance(parsed, dict):
|
|
686
|
+
raise ValueError("GitHub API response was not a JSON object")
|
|
687
|
+
return parsed
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
class GitHubAPIError(Exception):
|
|
691
|
+
"""GitHub API failure. ``status_code`` is None for transport-level errors."""
|
|
692
|
+
|
|
693
|
+
def __init__(self, message: str, status_code: int | None = None) -> None:
|
|
694
|
+
super().__init__(message)
|
|
695
|
+
self.status_code = status_code
|
|
696
|
+
self.message = message
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
class InstallationToken(BaseModel):
|
|
700
|
+
"""Short-lived installation access token minted by GitHub."""
|
|
701
|
+
|
|
702
|
+
model_config = ConfigDict(frozen=True)
|
|
703
|
+
|
|
704
|
+
token: str
|
|
705
|
+
expires_at: float
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
_TOKEN_EXPIRY_MARGIN_SECONDS = 120.0
|
|
709
|
+
_JWT_CACHE_SECONDS = 540.0
|
|
710
|
+
|
|
711
|
+
|
|
712
|
+
class GitHubAppAuth:
|
|
713
|
+
"""GitHub App authentication: RS256 JWTs, installation tokens, git-data API.
|
|
714
|
+
|
|
715
|
+
Zero-runtime-dependency client built on urllib. Mints app JWTs via
|
|
716
|
+
``github_jwt.mint_app_jwt`` and exchanges them for installation access
|
|
717
|
+
tokens, which are cached until shortly before expiry.
|
|
718
|
+
"""
|
|
719
|
+
|
|
720
|
+
def __init__(
|
|
721
|
+
self,
|
|
722
|
+
app_id: str | int,
|
|
723
|
+
private_key_pem: str,
|
|
724
|
+
api_base_url: str = "https://api.github.com",
|
|
725
|
+
timeout_seconds: float = 10.0,
|
|
726
|
+
allow_insecure_http: bool = False,
|
|
727
|
+
) -> None:
|
|
728
|
+
if not private_key_pem.strip():
|
|
729
|
+
raise ValueError("private_key_pem must be non-empty")
|
|
730
|
+
parsed = urllib.parse.urlparse(api_base_url)
|
|
731
|
+
if not allow_insecure_http:
|
|
732
|
+
if parsed.scheme != "https" or not parsed.netloc:
|
|
733
|
+
raise ValueError(
|
|
734
|
+
"api_base_url must use https:// (or set allow_insecure_http=True)"
|
|
735
|
+
)
|
|
736
|
+
elif parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
737
|
+
raise ValueError("api_base_url must use http:// or https://")
|
|
738
|
+
self._app_id = str(app_id)
|
|
739
|
+
self._private_key_pem = private_key_pem
|
|
740
|
+
self._api_base_url = api_base_url.rstrip("/")
|
|
741
|
+
self._timeout_seconds = timeout_seconds
|
|
742
|
+
self._lock = threading.Lock()
|
|
743
|
+
self._jwt_cache: tuple[str, float] | None = None
|
|
744
|
+
self._token_cache: dict[int, InstallationToken] = {}
|
|
745
|
+
|
|
746
|
+
def app_jwt(self) -> str:
|
|
747
|
+
"""Return a cached app JWT, reminting when older than ~9 minutes."""
|
|
748
|
+
now = time.time()
|
|
749
|
+
with self._lock:
|
|
750
|
+
if self._jwt_cache is not None and self._jwt_cache[1] > now:
|
|
751
|
+
return self._jwt_cache[0]
|
|
752
|
+
try:
|
|
753
|
+
jwt = mint_app_jwt(self._app_id, self._private_key_pem)
|
|
754
|
+
except JwtError as exc:
|
|
755
|
+
raise GitHubAPIError(f"JWT mint failed: {exc}") from exc
|
|
756
|
+
self._jwt_cache = (jwt, now + _JWT_CACHE_SECONDS)
|
|
757
|
+
return jwt
|
|
758
|
+
|
|
759
|
+
def _request(
|
|
760
|
+
self,
|
|
761
|
+
method: str,
|
|
762
|
+
path: str,
|
|
763
|
+
*,
|
|
764
|
+
bearer: str,
|
|
765
|
+
body: dict[str, Any] | None = None,
|
|
766
|
+
params: dict[str, str] | None = None,
|
|
767
|
+
) -> Any:
|
|
768
|
+
url = f"{self._api_base_url}{path}"
|
|
769
|
+
if params:
|
|
770
|
+
url = f"{url}?{urllib.parse.urlencode(params)}"
|
|
771
|
+
data = json.dumps(body).encode("utf-8") if body is not None else None
|
|
772
|
+
request = urllib.request.Request(
|
|
773
|
+
url,
|
|
774
|
+
data=data,
|
|
775
|
+
method=method,
|
|
776
|
+
headers={
|
|
777
|
+
"Authorization": f"Bearer {bearer}",
|
|
778
|
+
"Accept": "application/vnd.github+json",
|
|
779
|
+
"Content-Type": "application/json",
|
|
780
|
+
"X-GitHub-Api-Version": _GITHUB_API_VERSION,
|
|
781
|
+
"User-Agent": "selfheal-api",
|
|
782
|
+
},
|
|
783
|
+
)
|
|
784
|
+
try:
|
|
785
|
+
with urllib.request.urlopen(request, timeout=self._timeout_seconds) as response:
|
|
786
|
+
raw = response.read().decode("utf-8")
|
|
787
|
+
except urllib.error.HTTPError as exc:
|
|
788
|
+
detail = exc.read().decode("utf-8", errors="replace")[:500]
|
|
789
|
+
raise GitHubAPIError(
|
|
790
|
+
f"GitHub API {method} {path} failed: HTTP {exc.code}: {detail}",
|
|
791
|
+
status_code=exc.code,
|
|
792
|
+
) from exc
|
|
793
|
+
except (urllib.error.URLError, TimeoutError, OSError) as exc:
|
|
794
|
+
raise GitHubAPIError(
|
|
795
|
+
f"GitHub API {method} {path} transport error: {exc}"
|
|
796
|
+
) from exc
|
|
797
|
+
if not raw:
|
|
798
|
+
return None
|
|
799
|
+
try:
|
|
800
|
+
return json.loads(raw)
|
|
801
|
+
except json.JSONDecodeError as exc:
|
|
802
|
+
raise GitHubAPIError(f"GitHub API {method} {path} returned invalid JSON") from exc
|
|
803
|
+
|
|
804
|
+
def installation_token(
|
|
805
|
+
self, installation_id: int, permissions: dict[str, str] | None = None
|
|
806
|
+
) -> InstallationToken:
|
|
807
|
+
"""Exchange the app JWT for an installation access token (cached)."""
|
|
808
|
+
now = time.time()
|
|
809
|
+
with self._lock:
|
|
810
|
+
cached = self._token_cache.get(installation_id)
|
|
811
|
+
if cached is not None and cached.expires_at - _TOKEN_EXPIRY_MARGIN_SECONDS > now:
|
|
812
|
+
return cached
|
|
813
|
+
body: dict[str, Any] = {}
|
|
814
|
+
if permissions:
|
|
815
|
+
body["permissions"] = permissions
|
|
816
|
+
payload = self._request(
|
|
817
|
+
"POST",
|
|
818
|
+
f"/app/installations/{installation_id}/access_tokens",
|
|
819
|
+
bearer=self.app_jwt(),
|
|
820
|
+
body=body,
|
|
821
|
+
)
|
|
822
|
+
if not isinstance(payload, dict):
|
|
823
|
+
raise GitHubAPIError("installation token response was not a JSON object")
|
|
824
|
+
token = payload.get("token")
|
|
825
|
+
expires_raw = payload.get("expires_at")
|
|
826
|
+
if not isinstance(token, str) or not token or not isinstance(expires_raw, str):
|
|
827
|
+
raise GitHubAPIError("installation token response missing token/expires_at")
|
|
828
|
+
try:
|
|
829
|
+
expires_at = datetime.fromisoformat(
|
|
830
|
+
expires_raw.replace("Z", "+00:00")
|
|
831
|
+
).timestamp()
|
|
832
|
+
except ValueError as exc:
|
|
833
|
+
raise GitHubAPIError(f"invalid expires_at: {expires_raw!r}") from exc
|
|
834
|
+
record = InstallationToken(token=token, expires_at=expires_at)
|
|
835
|
+
with self._lock:
|
|
836
|
+
self._token_cache[installation_id] = record
|
|
837
|
+
return record
|
|
838
|
+
|
|
839
|
+
def client_for_installation(self, installation_id: int) -> UrllibGitHubAppClient:
|
|
840
|
+
"""Return a PR-capable client bound to a fresh installation token."""
|
|
841
|
+
token = self.installation_token(installation_id)
|
|
842
|
+
return UrllibGitHubAppClient(
|
|
843
|
+
token=token.token,
|
|
844
|
+
api_base_url=self._api_base_url,
|
|
845
|
+
timeout_seconds=self._timeout_seconds,
|
|
846
|
+
allow_insecure_http=self._api_base_url.startswith("http://"),
|
|
847
|
+
)
|
|
848
|
+
|
|
849
|
+
def _repo_request(
|
|
850
|
+
self,
|
|
851
|
+
installation_id: int,
|
|
852
|
+
method: str,
|
|
853
|
+
path: str,
|
|
854
|
+
*,
|
|
855
|
+
body: dict[str, Any] | None = None,
|
|
856
|
+
params: dict[str, str] | None = None,
|
|
857
|
+
) -> Any:
|
|
858
|
+
token = self.installation_token(installation_id)
|
|
859
|
+
return self._request(
|
|
860
|
+
method, path, bearer=token.token, body=body, params=params
|
|
861
|
+
)
|
|
862
|
+
|
|
863
|
+
# --- git-data / contents helpers ---
|
|
864
|
+
|
|
865
|
+
def get_branch_sha(
|
|
866
|
+
self, installation_id: int, owner: str, repo: str, branch: str
|
|
867
|
+
) -> str:
|
|
868
|
+
"""Resolve ``refs/heads/<branch>`` to its commit SHA."""
|
|
869
|
+
_validate_slug(owner, "owner")
|
|
870
|
+
_validate_slug(repo, "repo")
|
|
871
|
+
if not branch or ".." in branch:
|
|
872
|
+
raise ValueError(f"Invalid branch: {branch!r}")
|
|
873
|
+
payload = self._repo_request(
|
|
874
|
+
installation_id,
|
|
875
|
+
"GET",
|
|
876
|
+
f"/repos/{owner}/{repo}/git/ref/heads/{urllib.parse.quote(branch, safe='/')}",
|
|
877
|
+
)
|
|
878
|
+
if not isinstance(payload, dict):
|
|
879
|
+
raise GitHubAPIError("git ref response was not a JSON object")
|
|
880
|
+
obj = payload.get("object")
|
|
881
|
+
sha = obj.get("sha") if isinstance(obj, dict) else None
|
|
882
|
+
if not isinstance(sha, str) or not sha:
|
|
883
|
+
raise GitHubAPIError("git ref response missing object.sha")
|
|
884
|
+
return sha
|
|
885
|
+
|
|
886
|
+
def get_commit(
|
|
887
|
+
self, installation_id: int, owner: str, repo: str, commit_sha: str
|
|
888
|
+
) -> dict[str, Any]:
|
|
889
|
+
"""Fetch a commit object (tree SHA, parents) via the git-data API."""
|
|
890
|
+
_validate_slug(owner, "owner")
|
|
891
|
+
_validate_slug(repo, "repo")
|
|
892
|
+
if not commit_sha or ".." in commit_sha:
|
|
893
|
+
raise ValueError(f"Invalid commit sha: {commit_sha!r}")
|
|
894
|
+
payload = self._repo_request(
|
|
895
|
+
installation_id,
|
|
896
|
+
"GET",
|
|
897
|
+
f"/repos/{owner}/{repo}/git/commits/{urllib.parse.quote(commit_sha, safe='')}",
|
|
898
|
+
)
|
|
899
|
+
if not isinstance(payload, dict):
|
|
900
|
+
raise GitHubAPIError("git commit response was not a JSON object")
|
|
901
|
+
return payload
|
|
902
|
+
|
|
903
|
+
def get_file(
|
|
904
|
+
self,
|
|
905
|
+
installation_id: int,
|
|
906
|
+
owner: str,
|
|
907
|
+
repo: str,
|
|
908
|
+
path: str,
|
|
909
|
+
ref: str,
|
|
910
|
+
) -> tuple[bytes, str] | None:
|
|
911
|
+
"""Read a file's contents and blob SHA via the contents API.
|
|
912
|
+
|
|
913
|
+
Returns ``None`` when the path does not exist at ``ref``.
|
|
914
|
+
"""
|
|
915
|
+
_validate_slug(owner, "owner")
|
|
916
|
+
_validate_slug(repo, "repo")
|
|
917
|
+
if ".." in path.split("/"):
|
|
918
|
+
raise ValueError(f"Invalid path: {path!r}")
|
|
919
|
+
try:
|
|
920
|
+
payload = self._repo_request(
|
|
921
|
+
installation_id,
|
|
922
|
+
"GET",
|
|
923
|
+
f"/repos/{owner}/{repo}/contents/{urllib.parse.quote(path, safe='/')}",
|
|
924
|
+
params={"ref": ref},
|
|
925
|
+
)
|
|
926
|
+
except GitHubAPIError as exc:
|
|
927
|
+
if exc.status_code == 404:
|
|
928
|
+
return None
|
|
929
|
+
raise
|
|
930
|
+
if not isinstance(payload, dict):
|
|
931
|
+
raise GitHubAPIError("contents response was not a JSON object")
|
|
932
|
+
content_b64 = payload.get("content")
|
|
933
|
+
sha = payload.get("sha")
|
|
934
|
+
if (
|
|
935
|
+
payload.get("encoding") != "base64"
|
|
936
|
+
or not isinstance(content_b64, str)
|
|
937
|
+
or not isinstance(sha, str)
|
|
938
|
+
):
|
|
939
|
+
raise GitHubAPIError("contents response missing base64 content/sha")
|
|
940
|
+
content = base64.b64decode("".join(content_b64.split()))
|
|
941
|
+
return content, sha
|
|
942
|
+
|
|
943
|
+
def create_blob(
|
|
944
|
+
self, installation_id: int, owner: str, repo: str, content: bytes
|
|
945
|
+
) -> str:
|
|
946
|
+
"""Create a blob and return its SHA."""
|
|
947
|
+
_validate_slug(owner, "owner")
|
|
948
|
+
_validate_slug(repo, "repo")
|
|
949
|
+
payload = self._repo_request(
|
|
950
|
+
installation_id,
|
|
951
|
+
"POST",
|
|
952
|
+
f"/repos/{owner}/{repo}/git/blobs",
|
|
953
|
+
body={
|
|
954
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
955
|
+
"encoding": "base64",
|
|
956
|
+
},
|
|
957
|
+
)
|
|
958
|
+
sha = payload.get("sha") if isinstance(payload, dict) else None
|
|
959
|
+
if not isinstance(sha, str) or not sha:
|
|
960
|
+
raise GitHubAPIError("create blob response missing sha")
|
|
961
|
+
return sha
|
|
962
|
+
|
|
963
|
+
def create_tree(
|
|
964
|
+
self,
|
|
965
|
+
installation_id: int,
|
|
966
|
+
owner: str,
|
|
967
|
+
repo: str,
|
|
968
|
+
base_tree_sha: str,
|
|
969
|
+
entries: list[dict[str, Any]],
|
|
970
|
+
) -> str:
|
|
971
|
+
"""Create a tree on top of ``base_tree_sha``; returns tree SHA."""
|
|
972
|
+
_validate_slug(owner, "owner")
|
|
973
|
+
_validate_slug(repo, "repo")
|
|
974
|
+
payload = self._repo_request(
|
|
975
|
+
installation_id,
|
|
976
|
+
"POST",
|
|
977
|
+
f"/repos/{owner}/{repo}/git/trees",
|
|
978
|
+
body={"base_tree": base_tree_sha, "tree": entries},
|
|
979
|
+
)
|
|
980
|
+
sha = payload.get("sha") if isinstance(payload, dict) else None
|
|
981
|
+
if not isinstance(sha, str) or not sha:
|
|
982
|
+
raise GitHubAPIError("create tree response missing sha")
|
|
983
|
+
return sha
|
|
984
|
+
|
|
985
|
+
def create_commit(
|
|
986
|
+
self,
|
|
987
|
+
installation_id: int,
|
|
988
|
+
owner: str,
|
|
989
|
+
repo: str,
|
|
990
|
+
message: str,
|
|
991
|
+
tree_sha: str,
|
|
992
|
+
parent_shas: list[str],
|
|
993
|
+
) -> str:
|
|
994
|
+
"""Create a commit; returns commit SHA."""
|
|
995
|
+
_validate_slug(owner, "owner")
|
|
996
|
+
_validate_slug(repo, "repo")
|
|
997
|
+
payload = self._repo_request(
|
|
998
|
+
installation_id,
|
|
999
|
+
"POST",
|
|
1000
|
+
f"/repos/{owner}/{repo}/git/commits",
|
|
1001
|
+
body={
|
|
1002
|
+
"message": message,
|
|
1003
|
+
"tree": tree_sha,
|
|
1004
|
+
"parents": parent_shas,
|
|
1005
|
+
},
|
|
1006
|
+
)
|
|
1007
|
+
sha = payload.get("sha") if isinstance(payload, dict) else None
|
|
1008
|
+
if not isinstance(sha, str) or not sha:
|
|
1009
|
+
raise GitHubAPIError("create commit response missing sha")
|
|
1010
|
+
return sha
|
|
1011
|
+
|
|
1012
|
+
def create_ref(
|
|
1013
|
+
self, installation_id: int, owner: str, repo: str, ref: str, sha: str
|
|
1014
|
+
) -> None:
|
|
1015
|
+
"""Create ``refs/heads/<ref>`` pointing at ``sha``."""
|
|
1016
|
+
_validate_slug(owner, "owner")
|
|
1017
|
+
_validate_slug(repo, "repo")
|
|
1018
|
+
if not ref.startswith("refs/"):
|
|
1019
|
+
ref = f"refs/heads/{ref}"
|
|
1020
|
+
if ".." in ref:
|
|
1021
|
+
raise ValueError(f"Invalid ref: {ref!r}")
|
|
1022
|
+
self._repo_request(
|
|
1023
|
+
installation_id,
|
|
1024
|
+
"POST",
|
|
1025
|
+
f"/repos/{owner}/{repo}/git/refs",
|
|
1026
|
+
body={"ref": ref, "sha": sha},
|
|
1027
|
+
)
|
|
1028
|
+
|
|
1029
|
+
def update_ref(
|
|
1030
|
+
self,
|
|
1031
|
+
installation_id: int,
|
|
1032
|
+
owner: str,
|
|
1033
|
+
repo: str,
|
|
1034
|
+
ref: str,
|
|
1035
|
+
sha: str,
|
|
1036
|
+
force: bool = False,
|
|
1037
|
+
) -> None:
|
|
1038
|
+
"""Update an existing ref (e.g. ``heads/<branch>``) to ``sha``."""
|
|
1039
|
+
_validate_slug(owner, "owner")
|
|
1040
|
+
_validate_slug(repo, "repo")
|
|
1041
|
+
if not ref.startswith("refs/"):
|
|
1042
|
+
ref = f"refs/heads/{ref}"
|
|
1043
|
+
if ".." in ref:
|
|
1044
|
+
raise ValueError(f"Invalid ref: {ref!r}")
|
|
1045
|
+
self._repo_request(
|
|
1046
|
+
installation_id,
|
|
1047
|
+
"PATCH",
|
|
1048
|
+
f"/repos/{owner}/{repo}/git/{urllib.parse.quote(ref, safe='/')}",
|
|
1049
|
+
body={"sha": sha, "force": force},
|
|
1050
|
+
)
|