Repository navigation
Serve the signed hold list read-only for the kb-gate verifier #217
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| """The public, read-only endpoint for the signed hold list. | ||
|
|
||
| The kb-gate verifier (a GitHub-hosted runner with no secrets) reads the | ||
| service's signed hold list over HTTPS and fails any knowledge segment it | ||
| cannot fetch, verify, or that is stale. This server exposes exactly one file, | ||
| ``<state_dir>/public/holds.json``, at ``GET /holds.json``; everything else is | ||
| 404. It never lists directories, follows paths, accepts writes, or serves | ||
| anything but that signed file, so running it exposes nothing the kb-gate does | ||
| not already publish. Put TLS in front of it (the bot host's reverse proxy) and | ||
| set that URL as ``holds_url`` in ``.github/kb-gate/config.json``. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import threading | ||
| from http import HTTPStatus | ||
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| from pathlib import Path | ||
|
|
||
| ROUTE = "/holds.json" | ||
| MAX_BYTES = 1 << 20 | ||
|
|
||
|
|
||
| def make_handler(holds_path: Path): | ||
| class HoldsHandler(BaseHTTPRequestHandler): | ||
| server_version = "kb-holds" | ||
| sys_version = "" | ||
|
|
||
| def _serve(self, with_body: bool) -> None: | ||
| if self.path.split("?", 1)[0] != ROUTE: | ||
| self.send_error(HTTPStatus.NOT_FOUND) | ||
| return | ||
| try: | ||
| data = holds_path.read_bytes()[:MAX_BYTES] | ||
| except OSError: | ||
| # no hold list yet: the gate treats unreachable as held | ||
| self.send_error(HTTPStatus.SERVICE_UNAVAILABLE) | ||
| return | ||
| self.send_response(HTTPStatus.OK) | ||
| self.send_header("Content-Type", "application/json") | ||
| self.send_header("Content-Length", str(len(data))) | ||
| self.send_header("Cache-Control", "no-store") | ||
| self.end_headers() | ||
| if with_body: | ||
| self.wfile.write(data) | ||
|
|
||
| def do_GET(self) -> None: # noqa: N802 - http.server API | ||
| self._serve(True) | ||
|
|
||
| def do_HEAD(self) -> None: # noqa: N802 | ||
| self._serve(False) | ||
|
|
||
| def log_message(self, format: str, *args) -> None: # noqa: A002 - quiet by default | ||
| return | ||
|
|
||
| return HoldsHandler | ||
|
|
||
|
|
||
| def serve_holds(state_dir: str | Path, *, host: str = "127.0.0.1", port: int = 8765, | ||
| stop: threading.Event | None = None) -> ThreadingHTTPServer: | ||
| """Serve until ``stop`` is set (blocking); returns the server when stopped.""" | ||
| server = ThreadingHTTPServer((host, port), make_handler(Path(state_dir) / "public" / "holds.json")) | ||
| server.daemon_threads = True | ||
| if stop is None: | ||
| try: | ||
| server.serve_forever() | ||
| finally: | ||
| server.server_close() | ||
| return server | ||
| thread = threading.Thread(target=server.serve_forever, daemon=True) | ||
| thread.start() | ||
| stop.wait() | ||
| server.shutdown() | ||
| server.server_close() | ||
| return server | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| """The hold-list endpoint serves exactly one signed file, read-only.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import threading | ||
| import urllib.error | ||
| import urllib.request | ||
|
|
||
| import pytest | ||
| from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey | ||
|
|
||
| from infermatrix_copilot.kb_service.holds_server import make_handler | ||
| from infermatrix_copilot.knowledge_service import gate_verifier as gv | ||
| from infermatrix_copilot.knowledge_service.signing import sign | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def server(tmp_path): | ||
| from http.server import ThreadingHTTPServer | ||
|
|
||
| holds = tmp_path / "public" / "holds.json" | ||
| srv = ThreadingHTTPServer(("127.0.0.1", 0), make_handler(holds)) | ||
| thread = threading.Thread(target=srv.serve_forever, daemon=True) | ||
| thread.start() | ||
| yield srv, holds, f"http://127.0.0.1:{srv.server_address[1]}" | ||
| srv.shutdown() | ||
| srv.server_close() | ||
|
|
||
|
|
||
| def _status(url, method="GET"): | ||
| try: | ||
| with urllib.request.urlopen(urllib.request.Request(url, method=method), timeout=5) as response: | ||
| return response.status, response.read(), response.headers | ||
| except urllib.error.HTTPError as exc: | ||
| return exc.code, b"", exc.headers | ||
|
|
||
|
|
||
| def test_the_signed_hold_list_is_served_and_verifies_through_the_gate(server): | ||
| import time | ||
|
|
||
| srv, holds, base = server | ||
| key = Ed25519PrivateKey.generate() | ||
| holds.parent.mkdir(parents=True) | ||
| payload = {"issued_at": time.time(), "sequence": 3, "global": False, "repos": ["demo"], "prs": [7]} | ||
| holds.write_text(json.dumps(sign("kb-holds", payload, key))) | ||
| status, body, headers = _status(base + "/holds.json") | ||
| assert status == 200 and headers["Cache-Control"] == "no-store" | ||
| # exactly what the kb-gate verifier does with it | ||
| envelope = gv.fetch_holds(base + "/holds.json") | ||
| assert gv.verify_holds(envelope, key.public_key(), now=time.time())["prs"] == [7] | ||
|
|
||
|
|
||
| def test_nothing_else_is_served(server, tmp_path): | ||
| srv, holds, base = server | ||
| holds.parent.mkdir(parents=True) | ||
| holds.write_text("{}") | ||
| (tmp_path / "kb.db").write_text("secret ledger") | ||
| for path in ("/", "/kb.db", "/../kb.db", "/public/", "/public/holds.json", "/holds.json/../kb.db"): | ||
| assert _status(base + path)[0] == 404, path | ||
| assert _status(base + "/holds.json", method="POST")[0] in (404, 405, 501) | ||
|
|
||
|
|
||
| def test_a_missing_hold_list_is_unavailable_not_empty(server): | ||
| assert _status(server[2] + "/holds.json")[0] == 503 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
holds.jsonexceeds 1 MiB, this reads the entire file into memory and then silently returns only its first MiB with HTTP 200. The truncated JSON cannot passfetch_holds, so every knowledge gate fails closed; moreover, concurrent requests to an unexpectedly large or corrupted file can allocate the full file repeatedly despite the apparent size cap. Read at mostMAX_BYTES + 1bytes and return an error when the extra byte is present.Useful? React with 👍 / 👎.