Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/auth.py

raw
1 # This code is part of the Ansible collection community.docker, but is an independent component.
2 # This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/)
3 #
4 # Copyright (c) 2016-2022 Docker, Inc.
5 #
6 # It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection)
7 # SPDX-License-Identifier: Apache-2.0
8
9 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
10 # Do not use this from other collections or standalone plugins/modules!
11
12 from __future__ import annotations
13
14 import base64
15 import json
16 import logging
17 import typing as t
18
19 from . import errors
20 from .credentials.errors import CredentialsNotFound, StoreError
21 from .credentials.store import Store
22 from .utils import config
23
24 if t.TYPE_CHECKING:
25 from ansible_collections.community.docker.plugins.module_utils._api.api.client import (
26 APIClient,
27 )
28
29
30 INDEX_NAME = "docker.io"
31 INDEX_URL = f"https://index.{INDEX_NAME}/v1/"
32 TOKEN_USERNAME = "<token>"
33
34 log = logging.getLogger(__name__)
35
36
37 def resolve_repository_name(repo_name: str) -> tuple[str, str]:
38 if "://" in repo_name:
39 raise errors.InvalidRepository(
40 f"Repository name cannot contain a scheme ({repo_name})"
41 )
42
43 index_name, remote_name = split_repo_name(repo_name)
44 if index_name[0] == "-" or index_name[-1] == "-":
45 raise errors.InvalidRepository(
46 f"Invalid index name ({index_name}). Cannot begin or end with a hyphen."
47 )
48 return resolve_index_name(index_name), remote_name
49
50
51 def resolve_index_name(index_name: str) -> str:
52 index_name = convert_to_hostname(index_name)
53 if index_name == "index." + INDEX_NAME:
54 index_name = INDEX_NAME
55 return index_name
56
57
58 def get_config_header(client: APIClient, registry: str) -> bytes | None:
59 log.debug("Looking for auth config")
60 if not client._auth_configs or client._auth_configs.is_empty:
61 log.debug("No auth config in memory - loading from filesystem")
62 client._auth_configs = load_config(credstore_env=client.credstore_env)
63 authcfg = resolve_authconfig(
64 client._auth_configs, registry, credstore_env=client.credstore_env
65 )
66 # Do not fail here if no authentication exists for this
67 # specific registry as we can have a readonly pull. Just
68 # put the header if we can.
69 if authcfg:
70 log.debug("Found auth config")
71 # auth_config needs to be a dict in the format used by
72 # auth.py username , password, serveraddress, email
73 return encode_header(authcfg)
74 log.debug("No auth config found")
75 return None
76
77
78 def split_repo_name(repo_name: str) -> tuple[str, str]:
79 parts = repo_name.split("/", 1)
80 if len(parts) == 1 or (
81 "." not in parts[0] and ":" not in parts[0] and parts[0] != "localhost"
82 ):
83 # This is a docker index repo (ex: username/foobar or ubuntu)
84 return INDEX_NAME, repo_name
85 return tuple(parts) # type: ignore
86
87
88 def get_credential_store(
89 authconfig: dict[str, t.Any] | AuthConfig, registry: str
90 ) -> str | None:
91 if not isinstance(authconfig, AuthConfig):
92 authconfig = AuthConfig(authconfig)
93 return authconfig.get_credential_store(registry)
94
95
96 class AuthConfig(dict):
97 def __init__(
98 self, dct: dict[str, t.Any], credstore_env: dict[str, str] | None = None
99 ):
100 if "auths" not in dct:
101 dct["auths"] = {}
102 self.update(dct)
103 self._credstore_env = credstore_env
104 self._stores: dict[str, Store] = {}
105
106 @classmethod
107 def parse_auth(
108 cls, entries: dict[str, dict[str, t.Any]], raise_on_error: bool = False
109 ) -> dict[str, dict[str, t.Any]]:
110 """
111 Parses authentication entries
112
113 Args:
114 entries: Dict of authentication entries.
115 raise_on_error: If set to true, an invalid format will raise
116 InvalidConfigFile
117
118 Returns:
119 Authentication registry.
120 """
121
122 conf: dict[str, dict[str, t.Any]] = {}
123 for registry, entry in entries.items():
124 if not isinstance(entry, dict):
125 log.debug("Config entry for key %s is not auth config", registry) # type: ignore
126 # We sometimes fall back to parsing the whole config as if it
127 # was the auth config by itself, for legacy purposes. In that
128 # case, we fail silently and return an empty conf if any of the
129 # keys is not formatted properly.
130 if raise_on_error:
131 raise errors.InvalidConfigFile(
132 f"Invalid configuration for registry {registry}"
133 )
134 return {}
135 if "identitytoken" in entry:
136 log.debug("Found an IdentityToken entry for registry %s", registry)
137 conf[registry] = {"IdentityToken": entry["identitytoken"]}
138 continue # Other values are irrelevant if we have a token
139
140 if "auth" not in entry:
141 # Starting with engine v1.11 (API 1.23), an empty dictionary is
142 # a valid value in the auths config.
143 # https://github.com/docker/compose/issues/3265
144 log.debug(
145 "Auth data for %s is absent. Client might be using a credentials store instead.",
146 registry,
147 )
148 conf[registry] = {}
149 continue
150
151 username, password = decode_auth(entry["auth"])
152 log.debug(
153 "Found entry (registry=%s, username=%s)", repr(registry), repr(username)
154 )
155
156 conf[registry] = {
157 "username": username,
158 "password": password,
159 "email": entry.get("email"),
160 "serveraddress": registry,
161 }
162 return conf
163
164 @classmethod
165 def load_config(
166 cls,
167 config_path: str | None,
168 config_dict: dict[str, t.Any] | None,
169 credstore_env: dict[str, str] | None = None,
170 ) -> t.Self:
171 """
172 Loads authentication data from a Docker configuration file in the given
173 root directory or if config_path is passed use given path.
174 Lookup priority:
175 explicit config_path parameter > DOCKER_CONFIG environment
176 variable > ~/.docker/config.json > ~/.dockercfg
177 """
178
179 if not config_dict:
180 config_file = config.find_config_file(config_path)
181
182 if not config_file:
183 return cls({}, credstore_env)
184 try:
185 with open(config_file, "rt", encoding="utf-8") as f:
186 config_dict = json.load(f)
187 except (IOError, KeyError, ValueError) as e:
188 # Likely missing new Docker config file or it is in an
189 # unknown format, continue to attempt to read old location
190 # and format.
191 log.debug(e)
192 return cls(_load_legacy_config(config_file), credstore_env)
193
194 res = {}
195 if config_dict.get("auths"):
196 log.debug("Found 'auths' section")
197 res.update(
198 {"auths": cls.parse_auth(config_dict.pop("auths"), raise_on_error=True)}
199 )
200 if config_dict.get("credsStore"):
201 log.debug("Found 'credsStore' section")
202 res.update({"credsStore": config_dict.pop("credsStore")})
203 if config_dict.get("credHelpers"):
204 log.debug("Found 'credHelpers' section")
205 res.update({"credHelpers": config_dict.pop("credHelpers")})
206 if res:
207 return cls(res, credstore_env)
208
209 log.debug(
210 "Could not find auth-related section ; attempting to interpret "
211 "as auth-only file"
212 )
213 return cls({"auths": cls.parse_auth(config_dict)}, credstore_env)
214
215 @property
216 def auths(self) -> dict[str, dict[str, t.Any]]:
217 return self.get("auths", {})
218
219 @property
220 def creds_store(self) -> str | None:
221 return self.get("credsStore", None)
222
223 @property
224 def cred_helpers(self) -> dict[str, t.Any]:
225 return self.get("credHelpers", {})
226
227 @property
228 def is_empty(self) -> bool:
229 return not self.auths and not self.creds_store and not self.cred_helpers
230
231 def resolve_authconfig(
232 self, registry: str | None = None
233 ) -> dict[str, t.Any] | None:
234 """
235 Returns the authentication data from the given auth configuration for a
236 specific registry. As with the Docker client, legacy entries in the
237 config with full URLs are stripped down to hostnames before checking
238 for a match. Returns None if no match was found.
239 """
240
241 if self.creds_store or self.cred_helpers:
242 store_name = self.get_credential_store(registry)
243 if store_name is not None:
244 log.debug('Using credentials store "%s"', store_name)
245 cfg = self._resolve_authconfig_credstore(registry, store_name)
246 if cfg is not None:
247 return cfg
248 log.debug("No entry in credstore - fetching from auth dict")
249
250 # Default to the public index server
251 registry = resolve_index_name(registry) if registry else INDEX_NAME
252 log.debug("Looking for auth entry for %s", repr(registry))
253
254 if registry in self.auths:
255 log.debug("Found %s", repr(registry))
256 return self.auths[registry]
257
258 for key, conf in self.auths.items():
259 if resolve_index_name(key) == registry:
260 log.debug("Found %s", repr(key))
261 return conf
262
263 log.debug("No entry found")
264 return None
265
266 def _resolve_authconfig_credstore(
267 self, registry: str | None, credstore_name: str
268 ) -> dict[str, t.Any] | None:
269 if not registry or registry == INDEX_NAME:
270 # The ecosystem is a little schizophrenic with index.docker.io VS
271 # docker.io - in that case, it seems the full URL is necessary.
272 registry = INDEX_URL
273 log.debug("Looking for auth entry for %s", repr(registry))
274 store = self._get_store_instance(credstore_name)
275 try:
276 data = store.get(registry)
277 res = {
278 "ServerAddress": registry,
279 }
280 if data["Username"] == TOKEN_USERNAME:
281 res["IdentityToken"] = data["Secret"]
282 else:
283 res.update(
284 {
285 "Username": data["Username"],
286 "Password": data["Secret"],
287 }
288 )
289 return res
290 except CredentialsNotFound:
291 log.debug("No entry found")
292 return None
293 except StoreError as e:
294 raise errors.DockerException(f"Credentials store error: {e}") from e
295
296 def _get_store_instance(self, name: str) -> Store:
297 if name not in self._stores:
298 self._stores[name] = Store(name, environment=self._credstore_env)
299 return self._stores[name]
300
301 def get_credential_store(self, registry: str | None) -> str | None:
302 if not registry or registry == INDEX_NAME:
303 registry = INDEX_URL
304
305 return self.cred_helpers.get(registry) or self.creds_store
306
307 def get_all_credentials(self) -> dict[str, dict[str, t.Any] | None]:
308 auth_data: dict[str, dict[str, t.Any] | None] = self.auths.copy() # type: ignore
309 if self.creds_store:
310 # Retrieve all credentials from the default store
311 store = self._get_store_instance(self.creds_store)
312 for k in store.list():
313 auth_data[k] = self._resolve_authconfig_credstore(k, self.creds_store)
314 auth_data[convert_to_hostname(k)] = auth_data[k]
315
316 # credHelpers entries take priority over all others
317 for reg, store_name in self.cred_helpers.items():
318 auth_data[reg] = self._resolve_authconfig_credstore(reg, store_name)
319 auth_data[convert_to_hostname(reg)] = auth_data[reg]
320
321 return auth_data
322
323 def add_auth(self, reg: str, data: dict[str, t.Any]) -> None:
324 self["auths"][reg] = data
325
326
327 def resolve_authconfig(
328 authconfig: AuthConfig | dict[str, t.Any],
329 registry: str | None = None,
330 credstore_env: dict[str, str] | None = None,
331 ) -> dict[str, t.Any] | None:
332 if not isinstance(authconfig, AuthConfig):
333 authconfig = AuthConfig(authconfig, credstore_env)
334 return authconfig.resolve_authconfig(registry)
335
336
337 def convert_to_hostname(url: str) -> str:
338 return url.replace("http://", "").replace("https://", "").split("/", 1)[0]
339
340
341 def decode_auth(auth: str | bytes) -> tuple[str, str]:
342 if isinstance(auth, str):
343 auth = auth.encode("ascii")
344 s = base64.b64decode(auth)
345 login, pwd = s.split(b":", 1)
346 return login.decode("utf8"), pwd.decode("utf8")
347
348
349 def encode_header(auth: dict[str, t.Any]) -> bytes:
350 auth_json = json.dumps(auth).encode("ascii")
351 return base64.urlsafe_b64encode(auth_json)
352
353
354 def parse_auth(
355 entries: dict[str, dict[str, t.Any]], raise_on_error: bool = False
356 ) -> dict[str, dict[str, t.Any]]:
357 """
358 Parses authentication entries
359
360 Args:
361 entries: Dict of authentication entries.
362 raise_on_error: If set to true, an invalid format will raise
363 InvalidConfigFile
364
365 Returns:
366 Authentication registry.
367 """
368
369 return AuthConfig.parse_auth(entries, raise_on_error)
370
371
372 def load_config(
373 config_path: str | None = None,
374 config_dict: dict[str, t.Any] | None = None,
375 credstore_env: dict[str, str] | None = None,
376 ) -> AuthConfig:
377 return AuthConfig.load_config(config_path, config_dict, credstore_env)
378
379
380 def _load_legacy_config(config_file: str) -> dict[str, dict[str, t.Any]]:
381 log.debug("Attempting to parse legacy auth file format")
382 try:
383 data = []
384 with open(config_file, "rt", encoding="utf-8") as f:
385 for line in f.readlines():
386 data.append(line.strip().split(" = ")[1])
387 if len(data) < 2:
388 # Not enough data
389 raise errors.InvalidConfigFile("Invalid or empty configuration file!")
390
391 username, password = decode_auth(data[0])
392 return {
393 "auths": {
394 INDEX_NAME: {
395 "username": username,
396 "password": password,
397 "email": data[1],
398 "serveraddress": INDEX_URL,
399 }
400 }
401 }
402 except Exception as e: # pylint: disable=broad-exception-caught
403 log.debug(e)
404
405 log.debug("All parsing attempts failed - returning empty config")
406 return {}