Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_api/credentials/store.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 errno
15 import json
16 import subprocess
17 import typing as t
18
19 from . import constants, errors
20 from .utils import create_environment_dict, find_executable
21
22
23 class Store:
24 def __init__(self, program: str, environment: dict[str, str] | None = None) -> None:
25 """Create a store object that acts as an interface to
26 perform the basic operations for storing, retrieving
27 and erasing credentials using `program`.
28 """
29 self.program = constants.PROGRAM_PREFIX + program
30 self.exe = find_executable(self.program)
31 self.environment = environment
32 if self.exe is None:
33 raise errors.InitializationError(
34 f"{self.program} not installed or not available in PATH"
35 )
36
37 def get(self, server: str | bytes) -> dict[str, t.Any]:
38 """Retrieve credentials for `server`. If no credentials are found,
39 a `StoreError` will be raised.
40 """
41 if not isinstance(server, bytes):
42 server = server.encode("utf-8")
43 data = self._execute("get", server)
44 result = json.loads(data.decode("utf-8"))
45
46 # docker-credential-pass will return an object for inexistent servers
47 # whereas other helpers will exit with returncode != 0. For
48 # consistency, if no significant data is returned,
49 # raise CredentialsNotFound
50 if result["Username"] == "" and result["Secret"] == "":
51 raise errors.CredentialsNotFound(
52 f"No matching credentials in {self.program}"
53 )
54
55 return result
56
57 def store(self, server: str, username: str, secret: str) -> bytes:
58 """Store credentials for `server`. Raises a `StoreError` if an error
59 occurs.
60 """
61 data_input = json.dumps(
62 {"ServerURL": server, "Username": username, "Secret": secret}
63 ).encode("utf-8")
64 return self._execute("store", data_input)
65
66 def erase(self, server: str | bytes) -> None:
67 """Erase credentials for `server`. Raises a `StoreError` if an error
68 occurs.
69 """
70 if not isinstance(server, bytes):
71 server = server.encode("utf-8")
72 self._execute("erase", server)
73
74 def list(self) -> t.Any:
75 """List stored credentials. Requires v0.4.0+ of the helper."""
76 data = self._execute("list", None)
77 return json.loads(data.decode("utf-8"))
78
79 def _execute(self, subcmd: str, data_input: bytes | None) -> bytes:
80 if self.exe is None:
81 raise errors.StoreError(
82 f"{self.program} not installed or not available in PATH"
83 )
84 output = None
85 env = create_environment_dict(self.environment)
86 try:
87 output = subprocess.check_output(
88 [self.exe, subcmd],
89 input=data_input,
90 env=env,
91 )
92 except subprocess.CalledProcessError as e:
93 raise errors.process_store_error(e, self.program) from e
94 except OSError as e:
95 if e.errno == errno.ENOENT:
96 raise errors.StoreError(
97 f"{self.program} not installed or not available in PATH"
98 ) from e
99 raise errors.StoreError(
100 f'Unexpected OS error "{e.strerror}", errno={e.errno}'
101 ) from e
102 return output