-
Notifications
You must be signed in to change notification settings - Fork 265
/
__init__.py
209 lines (174 loc) · 7.67 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
"""
The proxy module provides the means to proxy images from other registry instances.
Registries following the distribution spec are supported.
"""
from __future__ import annotations
import re
import requests
from requests.exceptions import RequestException
from app import model_cache
from data.cache import cache_key
from data.database import ProxyCacheConfig
WWW_AUTHENTICATE_REGEX = re.compile(r'(\w+)[=] ?"?([^",]+)"?')
TOKEN_VALIDITY_LIFETIME_S = 60 * 60 # 1 hour, in seconds - Quay's default
TOKEN_RENEWAL_THRESHOLD = 10 # interval (in seconds) when to renew auth token
REGISTRY_URLS = {"docker.io": "registry-1.docker.io"}
class UpstreamRegistryError(Exception):
def __init__(self, detail):
msg = f"Error requesting upstream registry: {detail}"
super().__init__(msg)
def parse_www_auth(value: str) -> dict[str, str]:
"""
Parses WWW-Authenticate parameters and returns a dict of key=val.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
for details.
This parser is *not* fully compliant with RFC 7235, notably it does not support
multiple challenges.
"""
scheme = value.split(" ", 1)[0]
matches = WWW_AUTHENTICATE_REGEX.findall(value)
parsed = dict(matches)
if scheme:
parsed["scheme"] = scheme
return parsed
class Proxy:
def __init__(self, config: ProxyCacheConfig, repository: str, validation: bool = False):
self._config = config
self._validation = validation
hostname = REGISTRY_URLS.get(
config.upstream_registry_hostname,
config.upstream_registry_hostname,
)
url = f"https://{hostname}"
if config.insecure:
url = f"http://{hostname}"
self.base_url = url
self._session = requests.Session()
self._repo = repository
self._authorize(self._credentials(), force_renewal=self._validation)
# flag used for validating Proxy cache config before saving to db
def get_manifest(
self, image_ref: str, media_types: list[str] | None = None
) -> tuple[bytes, str | None]:
url = f"{self.base_url}/v2/{self._repo}/manifests/{image_ref}"
headers = {}
if media_types is not None:
headers["Accept"] = ", ".join(media_types)
resp = self.get(url, headers=headers)
raw_manifest = resp.content
content_type = resp.headers.get("content-type")
return raw_manifest, content_type
def manifest_exists(self, image_ref: str, media_types: list[str] | None = None) -> str | None:
"""
Returns the manifest digest (docker-content-digest) if given by the
upstream registry.
If the manifest does not exist or the upstream registry errors, raises
an UpstreamRegistryError exception.
"""
url = f"{self.base_url}/v2/{self._repo}/manifests/{image_ref}"
headers = {}
if media_types is not None:
headers["Accept"] = ", ".join(media_types)
resp = self.head(url, headers=headers, allow_redirects=True)
return resp.headers.get("docker-content-digest")
def get_blob(self, digest: str):
url = f"{self.base_url}/v2/{self._repo}/blobs/{digest}"
resp = self.get(
url,
allow_redirects=True,
stream=True,
)
return resp
def blob_exists(self, digest: str):
url = f"{self.base_url}/v2/{self._repo}/blobs/{digest}"
resp = self.head(url, allow_redirects=True)
return {
"response": resp.text,
"status": resp.status_code,
"headers": dict(resp.headers),
}
def get(self, *args, **kwargs) -> requests.Response:
"""
Wrapper for session.get for renewing auth tokens and retrying requests in case of 401.
"""
return self._request(self._session.get, *args, **kwargs)
def head(self, *args, **kwargs) -> requests.Response:
"""
Wrapper for session.head for renewing auth tokens and retrying requests in case of 401.
"""
return self._request(self._session.head, *args, **kwargs)
def _request(self, request_func, *args, **kwargs) -> requests.Response:
resp = self._safe_request(request_func, *args, **kwargs)
if resp.status_code == 401:
self._authorize(self._credentials(), force_renewal=True)
resp = self._safe_request(request_func, *args, **kwargs)
if not resp.ok:
raise UpstreamRegistryError(resp.status_code)
return resp
def _safe_request(self, request_func, *args, **kwargs):
try:
return request_func(*args, **kwargs)
except (RequestException, ConnectionError) as e:
raise UpstreamRegistryError(str(e))
def _credentials(self) -> tuple[str, str] | None:
auth = None
username = self._config.upstream_registry_username
password = self._config.upstream_registry_password
if username is not None and password is not None:
auth = (
(username, password)
if isinstance(username, str) and isinstance(password, str)
else (username.decrypt(), password.decrypt())
)
return auth
def _authorize(self, auth: tuple[str, str] | None = None, force_renewal: bool = False) -> None:
raw_token = model_cache.retrieve(self._cache_key(), lambda: None)
if raw_token is not None and not force_renewal:
token = raw_token["token"]
if isinstance(token, bytes):
token = token.decode("ascii")
self._session.headers["Authorization"] = f"Bearer {token}"
return
if force_renewal:
self._session.headers.pop("Authorization", None)
# the /v2/ endpoint returns 401 when the client is not authorized.
# if we get 200, there's no need to proceed.
resp = self._session.get(f"{self.base_url}/v2/")
if resp.status_code == 200:
return
www_auth = parse_www_auth(resp.headers.get("www-authenticate", ""))
scheme = www_auth.get("scheme")
service = www_auth.get("service")
realm = www_auth.get("realm")
if scheme == "Basic" and auth is not None:
# attach basic auth header to session
requests.auth.HTTPBasicAuth(auth[0], auth[1])(self._session)
return
scope = f"repository:{self._repo}:pull"
auth_url = f"{realm}?service={service}&scope={scope}"
basic_auth = None
if auth is not None:
basic_auth = requests.auth.HTTPBasicAuth(auth[0], auth[1])
resp = self._safe_request(self._session.get, auth_url, auth=basic_auth)
if not resp.ok:
raise UpstreamRegistryError(
f"Failed to get token from: '{realm}', with status code: {resp.status_code}"
)
resp_json = resp.json()
token = resp_json.get("token")
# our cached token will expire a few seconds (TOKEN_RENEWAL_THRESHOLD)
# before the actual token expiration.
# we do this so that we can renew the token before actually hitting
# any 401s, to save some http requests.
expires_in = resp_json.get("expires_in", TOKEN_VALIDITY_LIFETIME_S)
expires_in -= TOKEN_RENEWAL_THRESHOLD
model_cache.retrieve(self._cache_key(expires_in), lambda: {"token": token})
self._session.headers["Authorization"] = f"{scheme} {token}"
def _cache_key(self, expires_in=TOKEN_VALIDITY_LIFETIME_S):
key = cache_key.for_upstream_registry_token(
self._config.organization.username,
self._config.upstream_registry,
self._repo,
f"{expires_in}s",
)
return key