-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
authn.bzl
376 lines (319 loc) · 13 KB
/
authn.bzl
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
"repository rule that locates the .docker/config.json or containers/auth.json file."
load("@aspect_bazel_lib//lib:base64.bzl", "base64")
load("@aspect_bazel_lib//lib:repo_utils.bzl", "repo_utils")
load(":util.bzl", "util")
# Unfortunately bazel downloader doesn't let us sniff the WWW-Authenticate header, therefore we need to
# keep a map of known registries that require us to acquire a temporary token for authentication.
_WWW_AUTH = {
"index.docker.io": {
"realm": "auth.docker.io/token",
"scope": "repository:{repository}:pull",
"service": "registry.docker.io",
},
"public.ecr.aws": {
"realm": "{registry}/token",
"scope": "repository:{repository}:pull",
"service": "{registry}",
},
"ghcr.io": {
"realm": "{registry}/token",
"scope": "repository:{repository}:pull",
"service": "{registry}/token",
},
"cgr.dev": {
"realm": "{registry}/token",
"scope": "repository:{repository}:pull",
"service": "{registry}",
},
".azurecr.io": {
"realm": "{registry}/oauth2/token",
"scope": "repository:{repository}:pull",
"service": "{registry}",
},
"registry.gitlab.com": {
"realm": "gitlab.com/jwt/auth",
"scope": "repository:{repository}:pull",
"service": "container_registry",
},
".app.snowflake.com": {
"realm": "{registry}/v2/token",
"scope": "repository:{repository}:pull",
"service": "{registry}",
},
"docker.elastic.co": {
"realm": "docker-auth.elastic.co/auth",
"scope": "repository:{repository}:pull",
"service": "token-service",
},
"quay.io": {
"realm": "{registry}/v2/auth",
"scope": "repository:{repository}:pull",
"service": "{registry}",
},
"nvcr.io": {
"realm": "{registry}/proxy_auth",
"scope": "repository:{repository}:pull",
"service": "{registry}",
},
}
def _strip_host(url):
# TODO: a principled way of doing this
return url.replace("http://", "").replace("https://", "").replace("/v1/", "")
# Path of the auth file is determined by the order described here;
# https://github.com/google/go-containerregistry/tree/main/pkg/authn#tldr-for-consumers-of-this-package
def _get_auth_file_path(rctx):
HOME = repo_utils.get_env_var(rctx, "HOME", "ERR_NO_HOME_SET")
# this is the standard path where registry credentials are stored
# https://docs.docker.com/engine/reference/commandline/cli/#configuration-files
DOCKER_CONFIG = "{}/.docker".format(HOME)
# set DOCKER_CONFIG to $DOCKER_CONFIG env if present
if "DOCKER_CONFIG" in rctx.os.environ:
DOCKER_CONFIG = rctx.os.environ["DOCKER_CONFIG"]
config_path = "{}/config.json".format(DOCKER_CONFIG)
if util.file_exists(rctx, config_path):
return config_path
# https://docs.podman.io/en/latest/markdown/podman-login.1.html#authfile-path
XDG_RUNTIME_DIR = "{}/.config".format(HOME)
# set XDG_RUNTIME_DIR to $XDG_RUNTIME_DIR env if present
if "XDG_RUNTIME_DIR" in rctx.os.environ:
XDG_RUNTIME_DIR = rctx.os.environ["XDG_RUNTIME_DIR"]
config_path = "{}/containers/auth.json".format(XDG_RUNTIME_DIR)
# podman support overriding the standard path for the auth file via this special environment variable.
# https://docs.podman.io/en/latest/markdown/podman-login.1.html#authfile-path
if "REGISTRY_AUTH_FILE" in rctx.os.environ:
config_path = rctx.os.environ["REGISTRY_AUTH_FILE"]
if util.file_exists(rctx, config_path):
return config_path
return None
def _fetch_auth_via_creds_helper(rctx, raw_host, helper_name, allow_fail = False):
if rctx.os.name.startswith("windows"):
executable = "{}.bat".format(helper_name)
rctx.file(
executable,
content = """\
@echo off
echo %1 | docker-credential-{} get """.format(helper_name),
)
else:
executable = "{}.sh".format(helper_name)
rctx.file(
executable,
content = """\
#!/usr/bin/env bash
exec "docker-credential-{}" get <<< "$1" """.format(helper_name),
)
result = rctx.execute([rctx.path(executable), raw_host])
if result.return_code:
if not allow_fail:
fail("credential helper failed: \nSTDOUT:\n{}\nSTDERR:\n{}".format(result.stdout, result.stderr))
else:
return {}
response = json.decode(result.stdout)
return {
"type": "basic",
"login": response["Username"],
"password": response["Secret"],
}
OAUTH_2_SCRIPT_POWERSHELL = """\
param (
[string]$url,
[string]$service,
[string]$scope,
[string]$refresh_token
)
try {
$response = Invoke-RestMethod -Uri $url -Method Post -Body @{
grant_type = "refresh_token"
service = $service
scope = $scope
refresh_token = $refresh_token
} -ErrorAction Stop
$jsonResponse = $response | ConvertTo-Json
echo $jsonResponse
} catch {
$ErrorMessage = $_.Exception.Message
Write-Error "oauth2 failed: PowerShell request failed with error: $ErrorMessage"
exit 1
}
"""
OAUTH_2_SCRIPT_CURL = """\
url=$1
service=$2
scope=$3
refresh_token=$4
response=$(curl --silent --show-error --fail --request POST --data "grant_type=refresh_token&service=$service&scope=$scope&refresh_token=$refresh_token" $url)
if [ $? -ne 0 ]; then
exit 1
fi
echo "$response"
"""
OAUTH_2_SCRIPT_WGET = """\
url=$1
service=$2
scope=$3
refresh_token=$4
response=$(wget --quiet --output-document=- --post-data "grant_type=refresh_token&service=$service&scope=$scope&refresh_token=$refresh_token" $url)
if [ $? -ne 0 ]; then
exit 1
fi
echo "$response"
"""
def _oauth2(rctx, realm, scope, service, secret):
if rctx.os.name.startswith("windows") and rctx.which("powershell"):
executable = "oauth2.ps1"
rctx.file(executable, content = OAUTH_2_SCRIPT_POWERSHELL)
result = rctx.execute(["powershell", "-File", rctx.path(executable), realm, service, scope, secret])
elif rctx.which("curl"):
executable = "oauth2.sh"
rctx.file(executable, content = OAUTH_2_SCRIPT_CURL)
result = rctx.execute(["bash", rctx.path(executable), realm, service, scope, secret])
elif rctx.which("wget"):
executable = "oauth2.sh"
rctx.file(executable, content = OAUTH_2_SCRIPT_WGET)
result = rctx.execute(["bash", rctx.path(executable), realm, service, scope, secret])
else:
fail("oauth2 failed, could not find either of: curl, wget, powershell")
if result.return_code:
fail("oauth2 failed:\nSTDOUT:\n{}\nSTDERR:\n{}".format(result.stdout, result.stderr))
return result.stdout
def _get_auth(rctx, state, registry):
# if we have a cached auth for this registry then just return it.
# this will prevent repetitive calls to external cred helper binaries.
if registry in state["auth"]:
return state["auth"][registry]
pattern = {}
config = state["config"]
# first look into per registry credHelpers if it exists
if "credHelpers" in config:
for host_raw in config["credHelpers"]:
host = _strip_host(host_raw)
if host == registry:
helper_val = config["credHelpers"][host_raw]
pattern = _fetch_auth_via_creds_helper(rctx, host_raw, helper_val)
# if no match for per registry credential helper for the host then look into auths dictionary
if "auths" in config and len(pattern.keys()) == 0:
for host_raw in config["auths"]:
host = _strip_host(host_raw)
if host == registry:
auth_val = config["auths"][host_raw]
if len(auth_val.keys()) == 0:
# zero keys indicates that credentials are stored in credsStore helper.
pattern = _fetch_auth_via_creds_helper(rctx, host_raw, config["credsStore"])
elif "auth" in auth_val:
# base64 encoded plaintext username and password
raw_auth = auth_val["auth"]
login, sep, password = base64.decode(raw_auth).partition(":")
if not sep:
fail("auth string must be in form username:password")
if not password and "identitytoken" in auth_val:
password = auth_val["identitytoken"]
pattern = {
"type": "basic",
"login": login,
"password": password,
}
elif "username" in auth_val and "password" in auth_val:
# plain text username and password
pattern = {
"type": "basic",
"login": auth_val["username"],
"password": auth_val["password"],
}
# look for generic credentials-store all lookups for host-specific auth fails
if "credsStore" in config and len(pattern.keys()) == 0:
pattern = _fetch_auth_via_creds_helper(rctx, registry, config["credsStore"], allow_fail = True)
# cache the result so that we don't do this again unnecessarily.
state["auth"][registry] = pattern
return pattern
IDENTITY_TOKEN_WARNING = """\
OAuth2 support for oci_pull is highly experimental and is not enabled by default.
We may change or abandon it without a notice. Use it at your own peril!
To enable this feature, add `common --repo_env=OCI_ENABLE_OAUTH2_SUPPORT=1` to the `.bazelrc` file.
"""
def _get_token(rctx, state, registry, repository):
pattern = _get_auth(rctx, state, registry)
for registry_pattern in _WWW_AUTH.keys():
if (registry == registry_pattern) or registry.endswith(registry_pattern):
www_authenticate = _WWW_AUTH[registry_pattern]
url = "https://{realm}?scope={scope}&service={service}".format(
realm = www_authenticate["realm"].format(registry = registry),
service = www_authenticate["service"].format(registry = registry),
scope = www_authenticate["scope"].format(repository = repository),
)
# if a token for this repository and registry is acquired, use that instead.
if url in state["token"]:
return state["token"][url]
auth = None
if pattern.get("login", None) == "<token>":
if not rctx.os.environ.get("OCI_ENABLE_OAUTH2_SUPPORT"):
fail(IDENTITY_TOKEN_WARNING)
response = _oauth2(
rctx = rctx,
realm = "https://" + www_authenticate["realm"].format(registry = registry),
scope = www_authenticate["scope"].format(repository = repository),
service = www_authenticate["service"].format(registry = registry),
secret = pattern["password"],
)
rctx.file(
"www-authenticate.json",
content = response,
executable = False,
)
else:
rctx.download(
url = [url],
output = "www-authenticate.json",
# optionally, sending the credentials to authenticate using the credentials.
# this is for fetching from private repositories that require WWW-Authenticate
auth = {url: pattern},
)
auth_raw = rctx.read("www-authenticate.json")
auth = json.decode(auth_raw)
token = ""
if "token" in auth:
token = auth["token"]
if "access_token" in auth:
token = auth["access_token"]
if token == "":
fail("could not find token in neither field 'token' nor 'access_token' in the response from the registry")
pattern = {
"type": "pattern",
"pattern": "Bearer <password>",
"password": token,
}
# put the token into cache so that we don't do the token exchange again.
state["token"][url] = pattern
return pattern
NO_CONFIG_FOUND_ERROR = """\
Could not find the `$HOME/.docker/config.json` and `$XDG_RUNTIME_DIR/containers/auth.json` file
Running one of `podman login`, `docker login`, `crane login` may help.
"""
def _explain(state):
if not state["config"]:
return NO_CONFIG_FOUND_ERROR
return None
def _new_auth(rctx, config_path = None):
if not config_path:
config_path = _get_auth_file_path(rctx)
config = {}
if config_path:
config = json.decode(rctx.read(config_path))
state = {
"config": config,
"auth": {},
"token": {},
}
return struct(
get_token = lambda reg, repo: _get_token(rctx, state, reg, repo),
explain = lambda: _explain(state),
)
authn = struct(
new = _new_auth,
ENVIRON = [
"DOCKER_CONFIG",
"REGISTRY_AUTH_FILE",
"XDG_RUNTIME_DIR",
"HOME",
"OCI_ENABLE_OAUTH2_SUPPORT",
],
)