phabricator-proxy 0.1.0__tar.gz
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.
- phabricator_proxy-0.1.0/.gitignore +62 -0
- phabricator_proxy-0.1.0/PKG-INFO +11 -0
- phabricator_proxy-0.1.0/VERSION +1 -0
- phabricator_proxy-0.1.0/phabricator_proxy/__init__.py +3 -0
- phabricator_proxy-0.1.0/phabricator_proxy/app.py +110 -0
- phabricator_proxy-0.1.0/pyproject.toml +31 -0
- phabricator_proxy-0.1.0/tests/test_app.py +194 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
*model
|
|
2
|
+
*model.zst
|
|
3
|
+
*model.zst.etag
|
|
4
|
+
*data_X
|
|
5
|
+
*data_y
|
|
6
|
+
*data_X.zst
|
|
7
|
+
*data_X.zst.etag
|
|
8
|
+
*data_y.zst
|
|
9
|
+
*data_y.zst.etag
|
|
10
|
+
feature_importance.png
|
|
11
|
+
importance.html
|
|
12
|
+
importances.json
|
|
13
|
+
metrics.json
|
|
14
|
+
probs.json
|
|
15
|
+
services/bugbug-api/models/*model*
|
|
16
|
+
|
|
17
|
+
data/
|
|
18
|
+
sheets/
|
|
19
|
+
|
|
20
|
+
.mypy_cache/
|
|
21
|
+
.pytest_cache/
|
|
22
|
+
*.pyc
|
|
23
|
+
.coverage
|
|
24
|
+
|
|
25
|
+
# Distribution / packaging
|
|
26
|
+
.Python
|
|
27
|
+
build/
|
|
28
|
+
develop-eggs/
|
|
29
|
+
dist/
|
|
30
|
+
downloads/
|
|
31
|
+
eggs/
|
|
32
|
+
.eggs/
|
|
33
|
+
lib/
|
|
34
|
+
lib64/
|
|
35
|
+
parts/
|
|
36
|
+
sdist/
|
|
37
|
+
var/
|
|
38
|
+
wheels/
|
|
39
|
+
pip-wheel-metadata/
|
|
40
|
+
share/python-wheels/
|
|
41
|
+
*.egg-info/
|
|
42
|
+
.installed.cfg
|
|
43
|
+
*.egg
|
|
44
|
+
MANIFEST
|
|
45
|
+
cache/
|
|
46
|
+
node_modules/
|
|
47
|
+
|
|
48
|
+
# Logs
|
|
49
|
+
*.log
|
|
50
|
+
# Desktop Service Store
|
|
51
|
+
*.DS_Store
|
|
52
|
+
|
|
53
|
+
# Local env files
|
|
54
|
+
.env
|
|
55
|
+
/services/bugbug-api/docker-compose.override.yml
|
|
56
|
+
|
|
57
|
+
# Local files
|
|
58
|
+
*.local.*
|
|
59
|
+
|
|
60
|
+
# Claude Code local state
|
|
61
|
+
.claude/worktrees/
|
|
62
|
+
.claude/.cc-writes/
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: phabricator-proxy
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Mountable read-only Conduit proxy that holds the Phabricator key
|
|
5
|
+
Requires-Python: >=3.14
|
|
6
|
+
Requires-Dist: fastapi>=0.109.0
|
|
7
|
+
Requires-Dist: httpx>=0.26.0
|
|
8
|
+
Requires-Dist: moz-phabricator-client
|
|
9
|
+
Provides-Extra: dev
|
|
10
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
|
|
11
|
+
Requires-Dist: pytest>=8.0.0; extra == 'dev'
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
0.1.0
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""A read-only Conduit proxy: enough of Phabricator to be talked to, no key handed out.
|
|
2
|
+
|
|
3
|
+
:func:`create_app` returns an app to mount wherever a caller can reach it (for
|
|
4
|
+
hackbot, on the broker sidecar the agent talks to over loopback). Point a Conduit
|
|
5
|
+
client at the mount point and it behaves like a Phabricator instance, except that
|
|
6
|
+
the proxy holds the API key and the caller does not. Two rules keep that safe:
|
|
7
|
+
|
|
8
|
+
* only allow-listed methods are forwarded, so the key cannot be used to write;
|
|
9
|
+
and
|
|
10
|
+
* whatever ``__conduit__`` token the caller sends is discarded and replaced with
|
|
11
|
+
the real key, so a caller chooses the method and its arguments, never the
|
|
12
|
+
credentials.
|
|
13
|
+
|
|
14
|
+
Requests and responses are otherwise relayed as-is — including Conduit's own
|
|
15
|
+
error envelope — so a client's existing error handling keeps working.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
import urllib.parse
|
|
21
|
+
|
|
22
|
+
import httpx
|
|
23
|
+
from fastapi import FastAPI, Request
|
|
24
|
+
from fastapi.responses import JSONResponse
|
|
25
|
+
from phabricator_client import PhabricatorClient
|
|
26
|
+
|
|
27
|
+
log = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
# Everything needed to reconstruct a revision's stack and its diffs, and nothing
|
|
30
|
+
# that writes. An allow list rather than a deny list, so a Conduit method added
|
|
31
|
+
# upstream is refused by default instead of silently exposed with the key.
|
|
32
|
+
READ_ONLY_METHODS = frozenset(
|
|
33
|
+
{
|
|
34
|
+
# A revision's metadata and the stack graph it sits in.
|
|
35
|
+
"differential.revision.search",
|
|
36
|
+
# A revision's diffs, and the base commit each was built on.
|
|
37
|
+
"differential.querydiffs",
|
|
38
|
+
# The patch text itself.
|
|
39
|
+
"differential.getrawdiff",
|
|
40
|
+
# Expanding an abbreviated base commit to a full, fetchable hash.
|
|
41
|
+
"diffusion.querycommits",
|
|
42
|
+
}
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _conduit_error(code: str, info: str, status: int) -> JSONResponse:
|
|
47
|
+
"""A Conduit-shaped error body, so a Conduit client can read the refusal."""
|
|
48
|
+
return JSONResponse(
|
|
49
|
+
{"result": None, "error_code": code, "error_info": info}, status_code=status
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _parse_params(body: bytes) -> dict:
|
|
54
|
+
"""Read Conduit's ``params`` field out of a url-encoded request body.
|
|
55
|
+
|
|
56
|
+
Parsed directly rather than via ``request.form()``, which needs a
|
|
57
|
+
``Content-Type`` to recognise a form and would otherwise read the body as
|
|
58
|
+
empty. Not every Conduit client sends one — moz-phab's does not — and this
|
|
59
|
+
is a façade for Conduit clients in general, not only for the one hackbot
|
|
60
|
+
happens to use.
|
|
61
|
+
|
|
62
|
+
Raises :class:`ValueError` if ``params`` is not a JSON object.
|
|
63
|
+
"""
|
|
64
|
+
fields = urllib.parse.parse_qs(body.decode())
|
|
65
|
+
params = json.loads(fields.get("params", ["{}"])[0])
|
|
66
|
+
if not isinstance(params, dict):
|
|
67
|
+
raise ValueError("params must be a JSON object")
|
|
68
|
+
return params
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def create_app(
|
|
72
|
+
client: PhabricatorClient,
|
|
73
|
+
*,
|
|
74
|
+
allowed_methods: frozenset[str] = READ_ONLY_METHODS,
|
|
75
|
+
) -> FastAPI:
|
|
76
|
+
"""Build the proxy app, forwarding through ``client`` (which holds the key).
|
|
77
|
+
|
|
78
|
+
Mount it at the path a Conduit client will treat as the API root, e.g.
|
|
79
|
+
``Mount("/phabricator/api", app=create_app(client))`` makes a call to
|
|
80
|
+
``differential.revision.search`` land on
|
|
81
|
+
``/phabricator/api/differential.revision.search``.
|
|
82
|
+
"""
|
|
83
|
+
# No docs/OpenAPI routes: this app fronts a credential, so it serves the
|
|
84
|
+
# Conduit methods it was asked to serve and nothing else.
|
|
85
|
+
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
|
86
|
+
|
|
87
|
+
@app.post("/{method}")
|
|
88
|
+
async def proxy(method: str, request: Request) -> JSONResponse:
|
|
89
|
+
if method not in allowed_methods:
|
|
90
|
+
log.warning("refusing to proxy Conduit method %s", method)
|
|
91
|
+
return _conduit_error(
|
|
92
|
+
"ERR-CONDUIT-METHOD-NOT-ALLOWED",
|
|
93
|
+
f"{method} is not on the proxy's read-only allow list",
|
|
94
|
+
403,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
try:
|
|
98
|
+
params = _parse_params(await request.body())
|
|
99
|
+
except ValueError as exc:
|
|
100
|
+
return _conduit_error("ERR-CONDUIT-CORE", f"Malformed params: {exc}", 400)
|
|
101
|
+
|
|
102
|
+
try:
|
|
103
|
+
return JSONResponse(await client.conduit_call(method, params))
|
|
104
|
+
except httpx.HTTPError as exc:
|
|
105
|
+
log.warning("proxied Conduit call %s failed: %s", method, exc)
|
|
106
|
+
return _conduit_error(
|
|
107
|
+
"ERR-CONDUIT-CORE", f"Upstream Phabricator call failed: {exc}", 502
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
return app
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "phabricator-proxy"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "Mountable read-only Conduit proxy that holds the Phabricator key"
|
|
5
|
+
requires-python = ">=3.14"
|
|
6
|
+
dependencies = [
|
|
7
|
+
"fastapi>=0.109.0",
|
|
8
|
+
"httpx>=0.26.0",
|
|
9
|
+
"moz-phabricator-client",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
[project.optional-dependencies]
|
|
13
|
+
dev = ["pytest>=8.0.0", "pytest-asyncio>=0.23.0"]
|
|
14
|
+
|
|
15
|
+
[tool.uv.sources]
|
|
16
|
+
moz-phabricator-client = { workspace = true }
|
|
17
|
+
|
|
18
|
+
[build-system]
|
|
19
|
+
requires = ["hatchling"]
|
|
20
|
+
build-backend = "hatchling.build"
|
|
21
|
+
|
|
22
|
+
[tool.hatch.version]
|
|
23
|
+
path = "VERSION"
|
|
24
|
+
pattern = "(?P<version>.+)"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["phabricator_proxy"]
|
|
28
|
+
|
|
29
|
+
[tool.pytest.ini_options]
|
|
30
|
+
asyncio_mode = "auto"
|
|
31
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Tests for the mountable read-only Conduit proxy."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import urllib.parse
|
|
5
|
+
from unittest.mock import AsyncMock
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
import phabricator_proxy
|
|
9
|
+
from fastapi.testclient import TestClient
|
|
10
|
+
from phabricator_client import PhabricatorClient, PhabricatorSettings
|
|
11
|
+
from phabricator_client import client as client_module
|
|
12
|
+
from phabricator_proxy import app as proxy_app
|
|
13
|
+
from phabricator_proxy import create_app
|
|
14
|
+
|
|
15
|
+
VALID_TOKEN = "api-" + "a" * 28
|
|
16
|
+
ALLOWED_METHOD = "differential.revision.search"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _client(phabricator_client, **kwargs) -> TestClient:
|
|
20
|
+
return TestClient(create_app(phabricator_client, **kwargs))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _conduit_body(params: dict) -> bytes:
|
|
24
|
+
"""A url-encoded request body with no Content-Type header.
|
|
25
|
+
|
|
26
|
+
Posted with httpx's `content=`, which sets no Content-Type. That is the
|
|
27
|
+
awkward shape the proxy has to cope with — moz-phab's Conduit client sends
|
|
28
|
+
it — and the one `request.form()` would read as empty.
|
|
29
|
+
"""
|
|
30
|
+
return urllib.parse.urlencode(
|
|
31
|
+
{"params": json.dumps(params), "output": "json"}
|
|
32
|
+
).encode()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_forwards_an_allow_listed_method():
|
|
36
|
+
fake = AsyncMock()
|
|
37
|
+
fake.conduit_call = AsyncMock(
|
|
38
|
+
return_value={"result": {"data": []}, "error_code": None, "error_info": None}
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
resp = _client(fake).post(
|
|
42
|
+
f"/{ALLOWED_METHOD}", content=_conduit_body({"constraints": {"ids": [42]}})
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
assert resp.status_code == 200
|
|
46
|
+
assert resp.json() == {
|
|
47
|
+
"result": {"data": []},
|
|
48
|
+
"error_code": None,
|
|
49
|
+
"error_info": None,
|
|
50
|
+
}
|
|
51
|
+
fake.conduit_call.assert_awaited_once_with(
|
|
52
|
+
ALLOWED_METHOD, {"constraints": {"ids": [42]}}
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_refuses_a_method_that_writes(caplog):
|
|
57
|
+
fake = AsyncMock()
|
|
58
|
+
|
|
59
|
+
with caplog.at_level("WARNING", logger=proxy_app.log.name):
|
|
60
|
+
resp = _client(fake).post(
|
|
61
|
+
"/differential.revision.edit", content=_conduit_body({})
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
assert resp.status_code == 403
|
|
65
|
+
assert resp.json()["error_code"] == "ERR-CONDUIT-METHOD-NOT-ALLOWED"
|
|
66
|
+
# Nothing reached Phabricator, so the key was never used.
|
|
67
|
+
fake.conduit_call.assert_not_awaited()
|
|
68
|
+
assert "differential.revision.edit" in caplog.text
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_allow_list_is_overridable():
|
|
72
|
+
# The default list covers hackbot's checkout; another caller may need
|
|
73
|
+
# different reads, so it is a parameter rather than a hard-coded set.
|
|
74
|
+
fake = AsyncMock()
|
|
75
|
+
fake.conduit_call = AsyncMock(return_value={"result": {}})
|
|
76
|
+
|
|
77
|
+
proxy = _client(fake, allowed_methods=frozenset({"user.whoami"}))
|
|
78
|
+
|
|
79
|
+
assert proxy.post("/user.whoami", content=_conduit_body({})).status_code == 200
|
|
80
|
+
assert (
|
|
81
|
+
proxy.post(f"/{ALLOWED_METHOD}", content=_conduit_body({})).status_code == 403
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_substitutes_the_proxys_own_conduit_token(monkeypatch):
|
|
86
|
+
# The whole point: whatever token the caller sends is discarded, so a caller
|
|
87
|
+
# never needs (or gets) a real one.
|
|
88
|
+
captured: dict = {}
|
|
89
|
+
|
|
90
|
+
class _FakeAsyncClient:
|
|
91
|
+
def __init__(self, timeout=None):
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
async def __aenter__(self):
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
async def __aexit__(self, *exc):
|
|
98
|
+
return False
|
|
99
|
+
|
|
100
|
+
async def post(self, url, data=None):
|
|
101
|
+
captured["url"] = url
|
|
102
|
+
captured["params"] = json.loads(data["params"])
|
|
103
|
+
return httpx.Response(
|
|
104
|
+
200,
|
|
105
|
+
json={"result": {}, "error_code": None},
|
|
106
|
+
request=httpx.Request("POST", url),
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
monkeypatch.setattr(client_module.httpx, "AsyncClient", _FakeAsyncClient)
|
|
110
|
+
real = PhabricatorClient(
|
|
111
|
+
PhabricatorSettings(api_key=VALID_TOKEN, url="https://phab.example.com")
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
resp = _client(real).post(
|
|
115
|
+
f"/{ALLOWED_METHOD}",
|
|
116
|
+
content=_conduit_body(
|
|
117
|
+
{"constraints": {}, "__conduit__": {"token": "api-caller-supplied"}}
|
|
118
|
+
),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
assert resp.status_code == 200
|
|
122
|
+
assert captured["url"] == f"https://phab.example.com/api/{ALLOWED_METHOD}"
|
|
123
|
+
assert captured["params"]["__conduit__"] == {"token": VALID_TOKEN}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def test_relays_a_conduit_error_verbatim():
|
|
127
|
+
# Conduit reports failures in the response body, and the caller's client
|
|
128
|
+
# knows how to read them; passing the envelope through unchanged keeps that
|
|
129
|
+
# working instead of flattening it into an HTTP error.
|
|
130
|
+
fake = AsyncMock()
|
|
131
|
+
fake.conduit_call = AsyncMock(
|
|
132
|
+
return_value={
|
|
133
|
+
"result": None,
|
|
134
|
+
"error_code": "ERR-CONDUIT-CORE",
|
|
135
|
+
"error_info": "No such revision",
|
|
136
|
+
}
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
resp = _client(fake).post(f"/{ALLOWED_METHOD}", content=_conduit_body({}))
|
|
140
|
+
|
|
141
|
+
assert resp.status_code == 200
|
|
142
|
+
assert resp.json()["error_info"] == "No such revision"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_rejects_malformed_params():
|
|
146
|
+
fake = AsyncMock()
|
|
147
|
+
|
|
148
|
+
resp = _client(fake).post(f"/{ALLOWED_METHOD}", content=b"params=not-json")
|
|
149
|
+
|
|
150
|
+
assert resp.status_code == 400
|
|
151
|
+
fake.conduit_call.assert_not_awaited()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_rejects_params_that_are_not_an_object():
|
|
155
|
+
fake = AsyncMock()
|
|
156
|
+
|
|
157
|
+
resp = _client(fake).post(f"/{ALLOWED_METHOD}", content=b"params=[1,2]")
|
|
158
|
+
|
|
159
|
+
assert resp.status_code == 400
|
|
160
|
+
fake.conduit_call.assert_not_awaited()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def test_reports_an_upstream_failure():
|
|
164
|
+
fake = AsyncMock()
|
|
165
|
+
fake.conduit_call = AsyncMock(side_effect=httpx.ConnectError("refused"))
|
|
166
|
+
|
|
167
|
+
resp = _client(fake).post(f"/{ALLOWED_METHOD}", content=_conduit_body({}))
|
|
168
|
+
|
|
169
|
+
assert resp.status_code == 502
|
|
170
|
+
assert "refused" in resp.json()["error_info"]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_serves_nothing_but_conduit_methods():
|
|
174
|
+
# It fronts a credential, so no docs or schema routes come along for the
|
|
175
|
+
# ride. 405, not 404: `/{method}` matches the path and refuses the GET,
|
|
176
|
+
# which is exactly what "there is no docs handler here" looks like.
|
|
177
|
+
fake = AsyncMock()
|
|
178
|
+
app = create_app(fake)
|
|
179
|
+
proxy = TestClient(app)
|
|
180
|
+
|
|
181
|
+
assert app.openapi_url is None
|
|
182
|
+
assert proxy.get("/docs").status_code == 405
|
|
183
|
+
assert proxy.get("/openapi.json").status_code == 405
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def test_default_allow_list_holds_only_reads():
|
|
187
|
+
# Pinned deliberately: this is what a caller can reach with the proxy's
|
|
188
|
+
# Conduit key, so widening it should be a conscious edit.
|
|
189
|
+
assert {
|
|
190
|
+
"differential.revision.search",
|
|
191
|
+
"differential.querydiffs",
|
|
192
|
+
"differential.getrawdiff",
|
|
193
|
+
"diffusion.querycommits",
|
|
194
|
+
} == phabricator_proxy.READ_ONLY_METHODS
|