|
| 1 | +# SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +"""The tags a container repository publishes, read from the registry itself. |
| 3 | +
|
| 4 | +The registry is the authority on which Admin versions an appliance can install. |
| 5 | +A git tag is not an image -- this project tagged twenty releases before it built |
| 6 | +an Admin image for the first one -- and a hand-written index is a third list |
| 7 | +that can disagree with both. So the list an operator picks from is asked of the |
| 8 | +place the image is pulled from anyway. |
| 9 | +
|
| 10 | +Nothing here is trusted: a tag is a candidate until ``validate_release_tag`` |
| 11 | +accepts it, and the install path still verifies the pulled image's OCI labels. |
| 12 | +""" |
| 13 | + |
| 14 | +import json |
| 15 | +import re |
| 16 | +import time |
| 17 | +import urllib.error |
| 18 | +import urllib.parse |
| 19 | +import urllib.request |
| 20 | + |
| 21 | +DEFAULT_TIMEOUT = 10 |
| 22 | +MAX_TAGS_BYTES = 512 * 1024 |
| 23 | +MAX_PAGES = 10 |
| 24 | +PAGE_SIZE = 100 |
| 25 | +DEFAULT_REGISTRY = "registry-1.docker.io" |
| 26 | + |
| 27 | +_CHALLENGE_PARAMETER = re.compile(r'(\w+)="([^"]*)"') |
| 28 | +_NEXT_LINK = re.compile(r'<([^>]+)>\s*;\s*rel="?next"?') |
| 29 | + |
| 30 | + |
| 31 | +class RegistryError(Exception): |
| 32 | + def __init__(self, code, message): |
| 33 | + super().__init__(message) |
| 34 | + self.code = code |
| 35 | + self.message = message |
| 36 | + |
| 37 | + |
| 38 | +class _Budget: |
| 39 | + """One wall-clock budget for the whole lookup. |
| 40 | +
|
| 41 | + A per-request timeout bounds nothing here: a challenge, its token exchange |
| 42 | + and ten pages are eleven requests, and the operator's request would sit |
| 43 | + behind all of them long past the agent's own operation timeout. |
| 44 | + """ |
| 45 | + |
| 46 | + def __init__(self, seconds, clock): |
| 47 | + self._clock = clock |
| 48 | + self._deadline = clock() + max(float(seconds), 0.0) |
| 49 | + |
| 50 | + def remaining(self): |
| 51 | + left = self._deadline - self._clock() |
| 52 | + if left <= 0: |
| 53 | + raise RegistryError( |
| 54 | + "release_registry_unreachable", "the registry did not answer in time" |
| 55 | + ) |
| 56 | + return left |
| 57 | + |
| 58 | + |
| 59 | +def split_repository(repository): |
| 60 | + """The registry host and the repository path a reference names.""" |
| 61 | + |
| 62 | + text = str(repository or "").strip().strip("/") |
| 63 | + if not text: |
| 64 | + raise RegistryError("release_registry_invalid", "no image repository is configured") |
| 65 | + head, _, rest = text.partition("/") |
| 66 | + if rest and ("." in head or ":" in head or head == "localhost"): |
| 67 | + return head, rest |
| 68 | + return DEFAULT_REGISTRY, text if rest else f"library/{text}" |
| 69 | + |
| 70 | + |
| 71 | +def _open(opener, url, headers, budget): |
| 72 | + if urllib.parse.urlsplit(url).scheme != "https": |
| 73 | + raise RegistryError( |
| 74 | + "release_registry_unreachable", "only an https registry endpoint is read" |
| 75 | + ) |
| 76 | + request = urllib.request.Request(url, headers=headers) |
| 77 | + try: |
| 78 | + return opener(request, timeout=budget.remaining()) |
| 79 | + except urllib.error.HTTPError: |
| 80 | + raise |
| 81 | + except (urllib.error.URLError, OSError, ValueError) as exc: |
| 82 | + raise RegistryError( |
| 83 | + "release_registry_unreachable", |
| 84 | + f"the registry is unreachable: {exc.__class__.__name__}", |
| 85 | + ) from exc |
| 86 | + |
| 87 | + |
| 88 | +def _read(response): |
| 89 | + payload = response.read(MAX_TAGS_BYTES + 1) |
| 90 | + if len(payload) > MAX_TAGS_BYTES: |
| 91 | + raise RegistryError( |
| 92 | + "release_registry_invalid", |
| 93 | + f"the registry sends more than the {MAX_TAGS_BYTES} bytes this appliance reads", |
| 94 | + ) |
| 95 | + try: |
| 96 | + return json.loads(payload.decode("utf-8", errors="replace")) |
| 97 | + except ValueError as exc: |
| 98 | + raise RegistryError("release_registry_invalid", "the registry answer is not JSON") from exc |
| 99 | + |
| 100 | + |
| 101 | +def _token(opener, challenge, budget): |
| 102 | + """An anonymous pull token, from the realm the registry's challenge names. |
| 103 | +
|
| 104 | + The realm is a URL the registry chose, so it is held to https like every |
| 105 | + other endpoint here. No credentials are sent to it; there are none to send. |
| 106 | + """ |
| 107 | + |
| 108 | + parameters = dict(_CHALLENGE_PARAMETER.findall(challenge or "")) |
| 109 | + realm = parameters.pop("realm", "") |
| 110 | + if not realm: |
| 111 | + raise RegistryError( |
| 112 | + "release_registry_unreachable", "the registry challenge names no token realm" |
| 113 | + ) |
| 114 | + query = urllib.parse.urlencode( |
| 115 | + {key: value for key, value in parameters.items() if key in ("service", "scope")} |
| 116 | + ) |
| 117 | + payload, _ = _page(opener, f"{realm}?{query}" if query else realm, {}, budget) |
| 118 | + token = "" |
| 119 | + if isinstance(payload, dict): |
| 120 | + token = payload.get("token") or payload.get("access_token") or "" |
| 121 | + if not token: |
| 122 | + raise RegistryError("release_registry_invalid", "the token endpoint returned no token") |
| 123 | + return str(token) |
| 124 | + |
| 125 | + |
| 126 | +def _page(opener, url, headers, budget): |
| 127 | + try: |
| 128 | + with _open(opener, url, headers, budget) as response: |
| 129 | + return _read(response), response.headers.get("Link", "") |
| 130 | + except urllib.error.HTTPError as exc: |
| 131 | + raise RegistryError( |
| 132 | + "release_registry_unreachable", f"the registry answered HTTP {exc.code}" |
| 133 | + ) from exc |
| 134 | + |
| 135 | + |
| 136 | +def list_tags(repository, *, opener=None, timeout=DEFAULT_TIMEOUT, clock=time.monotonic): |
| 137 | + """Every tag the repository publishes, in the order the registry lists them.""" |
| 138 | + |
| 139 | + opener = opener or urllib.request.urlopen |
| 140 | + budget = _Budget(timeout, clock) |
| 141 | + host, path = split_repository(repository) |
| 142 | + base = f"https://{host}" |
| 143 | + url = f"{base}/v2/{path}/tags/list?n={PAGE_SIZE}" |
| 144 | + headers = {"Accept": "application/json"} |
| 145 | + |
| 146 | + try: |
| 147 | + with _open(opener, url, headers, budget) as response: |
| 148 | + payload, link = _read(response), response.headers.get("Link", "") |
| 149 | + except urllib.error.HTTPError as exc: |
| 150 | + if exc.code != 401: |
| 151 | + raise RegistryError( |
| 152 | + "release_registry_unreachable", f"the registry answered HTTP {exc.code}" |
| 153 | + ) from exc |
| 154 | + token = _token(opener, exc.headers.get("WWW-Authenticate", ""), budget) |
| 155 | + headers["Authorization"] = f"Bearer {token}" |
| 156 | + payload, link = _page(opener, url, headers, budget) |
| 157 | + |
| 158 | + tags = [] |
| 159 | + pages = 1 |
| 160 | + while True: |
| 161 | + listed = payload.get("tags") if isinstance(payload, dict) else None |
| 162 | + tags.extend(item for item in (listed or []) if isinstance(item, str)) |
| 163 | + match = _NEXT_LINK.search(link or "") |
| 164 | + if not match or pages >= MAX_PAGES: |
| 165 | + break |
| 166 | + payload, link = _page(opener, urllib.parse.urljoin(base, match.group(1)), headers, budget) |
| 167 | + pages += 1 |
| 168 | + return tags |
0 commit comments