fix(images): name the registry client and report a refused request
The first Images run after #165 failed: the runner's first registry request from next_image_version.py got HTTP 403, as a bare traceback, while the same request works from elsewhere and curl reaches the host in the same job. The suspected cause, a bot filter refusing Python's default User-Agent, is not confirmed. Every registry request, the token request included, now sends its own User-Agent. Every HTTP error becomes a RegistryError that names the status and the visible text of the response body, and main prints it as one ::error:: line and exits 1. The client logs in at most once, so an empty token cannot loop. The script takes the registry URL, so the tests drive it against a local fake registry. Refs #165 Assisted-by: Claude Code:claude-opus-5-5
This commit is contained in:
1 parent
5af66ed941
commit
30316c5a7d
3 files changed
+193
-28
No files matched your search
@@ -2,9 +2,14 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Run with: python3 -m unittest discover -s tests/scripts"""
|
||||
|
||||
import contextlib
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
|
||||
@@ -92,5 +97,128 @@ class InputChecksum(unittest.TestCase):
|
||||
self.assertNotEqual(self.checksum(MOL), before)
|
||||
|
||||
|
||||
class FakeRegistry(http.server.BaseHTTPRequestHandler):
|
||||
"""Asks for a token like the Gitea registry; `refuse` refuses every request, `refuse_token` the token."""
|
||||
|
||||
refuse = False
|
||||
refuse_token = False
|
||||
no_realm = False
|
||||
empty_token = False
|
||||
agents = None # a fresh list per test, set in setUp
|
||||
|
||||
def do_GET(self):
|
||||
self.agents.append(self.headers.get("User-Agent"))
|
||||
if self.refuse:
|
||||
page = "<html><head><style>" + "p{margin:0}" * 80 + "</style></head>"
|
||||
page += "<body><h1>Blocked by the firewall</h1></body></html>"
|
||||
self.reply(403, page.encode(), "text/html")
|
||||
elif self.path.startswith("/v2/token") and self.refuse_token:
|
||||
self.reply(401, b'{"errors":[{"message":"token refused"}]}')
|
||||
elif self.path.startswith("/v2/token"):
|
||||
self.reply(
|
||||
200, json.dumps({"token": "" if self.empty_token else "t"}).encode()
|
||||
)
|
||||
elif self.no_realm:
|
||||
self.reply(401, b"{}", extra={"WWW-Authenticate": "Basic"})
|
||||
elif self.headers.get("Authorization") != "Bearer t":
|
||||
realm = f"http://127.0.0.1:{self.server.server_port}/v2/token"
|
||||
self.reply(
|
||||
401,
|
||||
b"{}",
|
||||
extra={"WWW-Authenticate": f'Bearer realm="{realm}",service="reg"'},
|
||||
)
|
||||
else:
|
||||
self.reply(200, json.dumps({"tags": ["0.1.0"]}).encode())
|
||||
|
||||
def reply(self, code, body, kind="application/json", extra=None):
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", kind)
|
||||
for key, value in (extra or {}).items():
|
||||
self.send_header(key, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
class QuietServer(http.server.HTTPServer):
|
||||
def handle_error(self, request, client_address):
|
||||
"""A client hang-up is not a test failure, and must not write to the captured stderr."""
|
||||
|
||||
|
||||
class RegistryClient(unittest.TestCase):
|
||||
def setUp(self):
|
||||
FakeRegistry.refuse = FakeRegistry.refuse_token = FakeRegistry.no_realm = False
|
||||
FakeRegistry.empty_token = False
|
||||
FakeRegistry.agents = []
|
||||
server = QuietServer(("127.0.0.1", 0), FakeRegistry)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
self.url = f"http://127.0.0.1:{server.server_port}"
|
||||
self.registry = niv.Registry(self.url, "mortis/ci")
|
||||
|
||||
def test_every_request_names_the_client(self):
|
||||
self.assertEqual(self.registry.tags(), ["0.1.0"])
|
||||
self.assertTrue(FakeRegistry.agents)
|
||||
for agent in FakeRegistry.agents:
|
||||
self.assertTrue(agent.startswith("kamino-"), agent)
|
||||
|
||||
def test_a_refused_request_names_its_status_and_body(self):
|
||||
FakeRegistry.refuse = True
|
||||
with self.assertRaises(niv.RegistryError) as caught:
|
||||
self.registry.tags()
|
||||
self.assertIn("403", str(caught.exception))
|
||||
self.assertIn("Blocked by the firewall", str(caught.exception))
|
||||
|
||||
def test_a_refused_token_is_a_registry_error_with_its_body(self):
|
||||
FakeRegistry.refuse_token = True
|
||||
with self.assertRaises(niv.RegistryError) as caught:
|
||||
self.registry.tags()
|
||||
self.assertIn("401", str(caught.exception))
|
||||
self.assertIn("token refused", str(caught.exception))
|
||||
|
||||
def test_a_401_without_a_token_realm_is_a_registry_error(self):
|
||||
FakeRegistry.no_realm = True
|
||||
with self.assertRaises(niv.RegistryError) as caught:
|
||||
self.registry.tags()
|
||||
self.assertIn("401", str(caught.exception))
|
||||
|
||||
def test_one_login_only_even_when_the_token_is_empty(self):
|
||||
FakeRegistry.empty_token = True
|
||||
with self.assertRaises(niv.RegistryError):
|
||||
self.registry.tags()
|
||||
self.assertLessEqual(len(FakeRegistry.agents), 3)
|
||||
|
||||
def test_the_cli_reports_a_refusal_as_one_error_line_and_fails(self):
|
||||
FakeRegistry.refuse = True
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tmp.cleanup)
|
||||
root = pathlib.Path(tmp.name)
|
||||
(root / ".gitea/workflows").mkdir(parents=True)
|
||||
(root / ".gitea/workflows/image.yml").write_text(
|
||||
"jobs:\n image:\n strategy:\n matrix:\n include:\n"
|
||||
' - name: ci\n base: "0.1"\n subpath: images/ci\n'
|
||||
" dockerfile: Dockerfile\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(root / "images/ci").mkdir(parents=True)
|
||||
(root / "images/ci/Dockerfile").write_text(
|
||||
"FROM ubuntu:26.04\n", encoding="utf-8"
|
||||
)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = niv.main(["next_image_version.py", str(root), "ci", self.url])
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(out.getvalue(), "")
|
||||
# Only the annotation lines: stderr is process-wide, and other threads may write to it.
|
||||
errors = [
|
||||
line for line in err.getvalue().splitlines() if line.startswith("::error::")
|
||||
]
|
||||
self.assertEqual(len(errors), 1, err.getvalue())
|
||||
self.assertIn("Blocked by the firewall", errors[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user