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
@@ -165,7 +165,7 @@ jobs:
|
|||||||
| tar -xz -C /tmp/src --strip-components=1
|
| tar -xz -C /tmp/src --strip-components=1
|
||||||
# -B: no bytecode left behind to break the pristine-filesystem check below.
|
# -B: no bytecode left behind to break the pristine-filesystem check below.
|
||||||
env -u PAT_USER -u PAT_TOKEN -u JOB_TOKEN python3 -B -E -s \
|
env -u PAT_USER -u PAT_TOKEN -u JOB_TOKEN python3 -B -E -s \
|
||||||
/tmp/src/scripts/next_image_version.py /tmp/src "$IMAGE_NAME" "$registry" > /kaniko/image-version
|
/tmp/src/scripts/next_image_version.py /tmp/src "$IMAGE_NAME" "$SERVER_URL" > /kaniko/image-version
|
||||||
if [ -s /kaniko/image-version ]; then
|
if [ -s /kaniko/image-version ]; then
|
||||||
read -r IMAGE_VERSION _ < /kaniko/image-version
|
read -r IMAGE_VERSION _ < /kaniko/image-version
|
||||||
echo "Inputs of ${IMAGE_PATH} changed: publishing ${IMAGE_VERSION}."
|
echo "Inputs of ${IMAGE_PATH} changed: publishing ${IMAGE_VERSION}."
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
"""Choose the version an image build publishes, or none.
|
"""Choose the version an image build publishes, or none.
|
||||||
|
|
||||||
python3 scripts/next_image_version.py <source-dir> <image-name> <registry-host>
|
python3 scripts/next_image_version.py <source-dir> <image-name> <registry-url>
|
||||||
|
|
||||||
Prints "<version> <checksum>" when the image's inputs differ from the newest published
|
Prints "<version> <checksum>" when the image's inputs differ from the newest published
|
||||||
<base>.N (its input-checksum label), and nothing when they match.
|
<base>.N (its input-checksum label), and nothing when they match.
|
||||||
@@ -65,39 +65,72 @@ MANIFEST_TYPES = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Bot filters in front of a registry commonly refuse Python's default User-Agent.
|
||||||
|
USER_AGENT = "kamino-next-image-version"
|
||||||
|
|
||||||
|
|
||||||
|
class RegistryError(Exception):
|
||||||
|
def __init__(self, url, status, text, challenge=""):
|
||||||
|
super().__init__(f"GET {url}: HTTP {status}: {text}")
|
||||||
|
self.status, self.challenge = status, challenge
|
||||||
|
|
||||||
|
|
||||||
|
def _readable(raw):
|
||||||
|
"""The visible text of an error page on one line, so the job log shows a block page."""
|
||||||
|
text = re.sub(
|
||||||
|
r"<(script|style)\b.*?</\1>|<[^>]+>", " ", raw, flags=re.DOTALL | re.IGNORECASE
|
||||||
|
)
|
||||||
|
return " ".join(text.split())[:300]
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch(url, headers):
|
||||||
|
"""(JSON body, headers) of a GET; any HTTP error is a RegistryError naming status and text."""
|
||||||
|
request = urllib.request.Request(url, headers={**headers, "User-Agent": USER_AGENT})
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=30) as resp:
|
||||||
|
return json.load(resp), resp.headers
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
raw = exc.read(20000).decode("utf-8", errors="replace")
|
||||||
|
challenge = exc.headers.get("WWW-Authenticate", "")
|
||||||
|
raise RegistryError(url, exc.code, _readable(raw), challenge) from exc
|
||||||
|
|
||||||
|
|
||||||
class Registry:
|
class Registry:
|
||||||
"""Anonymous reads of one image in an OCI registry: the images are public."""
|
"""Anonymous reads of one image in an OCI registry: the images are public."""
|
||||||
|
|
||||||
def __init__(self, host, image):
|
def __init__(self, base_url, image):
|
||||||
self.host, self.image, self.token = host, image, None
|
self.base_url, self.image, self.token = base_url, image, None
|
||||||
|
|
||||||
def _get(self, path, accept="application/json"):
|
def _get(self, path, accept="application/json"):
|
||||||
url = f"https://{self.host}/v2/{self.image}/{path}"
|
url = f"{self.base_url}/v2/{self.image}/{path}"
|
||||||
headers = {"Accept": accept}
|
headers = {"Accept": accept}
|
||||||
if self.token:
|
if self.token:
|
||||||
headers["Authorization"] = f"Bearer {self.token}"
|
headers["Authorization"] = f"Bearer {self.token}"
|
||||||
try:
|
try:
|
||||||
with urllib.request.urlopen(
|
return _fetch(url, headers)
|
||||||
urllib.request.Request(url, headers=headers), timeout=30
|
except RegistryError as exc:
|
||||||
) as resp:
|
# One login at most: a 401 after it is final, whatever token it gave.
|
||||||
return json.load(resp), resp.headers
|
if (
|
||||||
except urllib.error.HTTPError as exc:
|
exc.status != 401
|
||||||
if exc.code != 401 or self.token:
|
or self.token is not None
|
||||||
|
or not self._login(exc.challenge)
|
||||||
|
):
|
||||||
raise
|
raise
|
||||||
challenge = dict(
|
return self._get(path, accept)
|
||||||
re.findall(r'(\w+)="([^"]*)"', exc.headers.get("WWW-Authenticate", ""))
|
|
||||||
)
|
def _login(self, challenge_header):
|
||||||
query = urllib.parse.urlencode(
|
"""Fetch an anonymous pull token from the 401 challenge's realm; False when it names none."""
|
||||||
{
|
challenge = dict(re.findall(r'(\w+)="([^"]*)"', challenge_header))
|
||||||
"service": challenge.get("service", ""),
|
if "realm" not in challenge:
|
||||||
"scope": f"repository:{self.image}:pull",
|
return False
|
||||||
}
|
query = urllib.parse.urlencode(
|
||||||
)
|
{
|
||||||
with urllib.request.urlopen(
|
"service": challenge.get("service", ""),
|
||||||
f"{challenge['realm']}?{query}", timeout=30
|
"scope": f"repository:{self.image}:pull",
|
||||||
) as resp:
|
}
|
||||||
self.token = json.load(resp)["token"]
|
)
|
||||||
return self._get(path, accept)
|
self.token = _fetch(f"{challenge['realm']}?{query}", {})[0]["token"]
|
||||||
|
return True
|
||||||
|
|
||||||
def tags(self):
|
def tags(self):
|
||||||
tags, path = [], "tags/list"
|
tags, path = [], "tags/list"
|
||||||
@@ -122,11 +155,15 @@ def main(argv):
|
|||||||
if len(argv) != 4:
|
if len(argv) != 4:
|
||||||
sys.stderr.write(__doc__)
|
sys.stderr.write(__doc__)
|
||||||
return 2
|
return 2
|
||||||
root, name, host = pathlib.Path(argv[1]), argv[2], argv[3]
|
root, name, url = pathlib.Path(argv[1]), argv[2], argv[3]
|
||||||
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text(encoding="utf-8"))[name]
|
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text(encoding="utf-8"))[name]
|
||||||
checksum = input_checksum(root, entry)
|
checksum = input_checksum(root, entry)
|
||||||
registry = Registry(host, f"mortis/{name}")
|
registry = Registry(url, f"mortis/{name}")
|
||||||
version = next_version(entry["base"], registry.tags(), checksum, registry.label)
|
try:
|
||||||
|
version = next_version(entry["base"], registry.tags(), checksum, registry.label)
|
||||||
|
except RegistryError as exc:
|
||||||
|
sys.stderr.write(f"::error::{exc}\n")
|
||||||
|
return 1
|
||||||
if version:
|
if version:
|
||||||
print(version, checksum)
|
print(version, checksum)
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -2,9 +2,14 @@
|
|||||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
"""Run with: python3 -m unittest discover -s tests/scripts"""
|
"""Run with: python3 -m unittest discover -s tests/scripts"""
|
||||||
|
|
||||||
|
import contextlib
|
||||||
|
import http.server
|
||||||
|
import io
|
||||||
|
import json
|
||||||
import pathlib
|
import pathlib
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import threading
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
|
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
|
||||||
@@ -92,5 +97,128 @@ class InputChecksum(unittest.TestCase):
|
|||||||
self.assertNotEqual(self.checksum(MOL), before)
|
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__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Reference in new issue
Block a user