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,7 +2,7 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""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
|
||||
<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:
|
||||
"""Anonymous reads of one image in an OCI registry: the images are public."""
|
||||
|
||||
def __init__(self, host, image):
|
||||
self.host, self.image, self.token = host, image, None
|
||||
def __init__(self, base_url, image):
|
||||
self.base_url, self.image, self.token = base_url, image, None
|
||||
|
||||
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}
|
||||
if self.token:
|
||||
headers["Authorization"] = f"Bearer {self.token}"
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
urllib.request.Request(url, headers=headers), timeout=30
|
||||
) as resp:
|
||||
return json.load(resp), resp.headers
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 401 or self.token:
|
||||
return _fetch(url, headers)
|
||||
except RegistryError as exc:
|
||||
# One login at most: a 401 after it is final, whatever token it gave.
|
||||
if (
|
||||
exc.status != 401
|
||||
or self.token is not None
|
||||
or not self._login(exc.challenge)
|
||||
):
|
||||
raise
|
||||
challenge = dict(
|
||||
re.findall(r'(\w+)="([^"]*)"', exc.headers.get("WWW-Authenticate", ""))
|
||||
)
|
||||
query = urllib.parse.urlencode(
|
||||
{
|
||||
"service": challenge.get("service", ""),
|
||||
"scope": f"repository:{self.image}:pull",
|
||||
}
|
||||
)
|
||||
with urllib.request.urlopen(
|
||||
f"{challenge['realm']}?{query}", timeout=30
|
||||
) as resp:
|
||||
self.token = json.load(resp)["token"]
|
||||
return self._get(path, accept)
|
||||
return self._get(path, accept)
|
||||
|
||||
def _login(self, challenge_header):
|
||||
"""Fetch an anonymous pull token from the 401 challenge's realm; False when it names none."""
|
||||
challenge = dict(re.findall(r'(\w+)="([^"]*)"', challenge_header))
|
||||
if "realm" not in challenge:
|
||||
return False
|
||||
query = urllib.parse.urlencode(
|
||||
{
|
||||
"service": challenge.get("service", ""),
|
||||
"scope": f"repository:{self.image}:pull",
|
||||
}
|
||||
)
|
||||
self.token = _fetch(f"{challenge['realm']}?{query}", {})[0]["token"]
|
||||
return True
|
||||
|
||||
def tags(self):
|
||||
tags, path = [], "tags/list"
|
||||
@@ -122,11 +155,15 @@ def main(argv):
|
||||
if len(argv) != 4:
|
||||
sys.stderr.write(__doc__)
|
||||
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]
|
||||
checksum = input_checksum(root, entry)
|
||||
registry = Registry(host, f"mortis/{name}")
|
||||
version = next_version(entry["base"], registry.tags(), checksum, registry.label)
|
||||
registry = Registry(url, f"mortis/{name}")
|
||||
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:
|
||||
print(version, checksum)
|
||||
return 0
|
||||
|
||||
Reference in new issue
Block a user