bitwarden-keyring 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ from .backend import BitwardenBackend
2
+
3
+ __all__ = ["BitwardenBackend"]
@@ -0,0 +1,264 @@
1
+ import base64
2
+ import json
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ from collections.abc import Iterable, Mapping
7
+ from typing import Any, NotRequired, Protocol, TypedDict, cast
8
+
9
+ from jaraco.classes import properties
10
+ from keyring import backend
11
+
12
+ PRIORITY = 10.0 # Doc is oddly vague
13
+ BW_CLI = "bw"
14
+
15
+
16
+ class Login(TypedDict):
17
+ username: str
18
+ password: str
19
+
20
+
21
+ class Credentials(TypedDict):
22
+ id: str
23
+ name: NotRequired[str]
24
+ login: Login
25
+
26
+
27
+ def user_is_authenticated() -> bool:
28
+ try:
29
+ bw_run(*bw_args("login", "--check"))
30
+ except subprocess.CalledProcessError:
31
+ return False
32
+ return True
33
+
34
+
35
+ class WhichCallable(Protocol):
36
+ def __call__(self, cmd: str) -> str | None: ...
37
+
38
+
39
+ def bitwarden_cli_installed(which_callable: WhichCallable = shutil.which) -> bool:
40
+ return bool(which_callable(BW_CLI))
41
+
42
+
43
+ def ask_for_session(command: str) -> str:
44
+ result = bw(command, "--raw")
45
+ return result
46
+
47
+
48
+ def ask_for_session_command(is_authenticated: bool) -> str:
49
+ return "unlock" if is_authenticated else "login"
50
+
51
+
52
+ def wrong_password(output: str) -> bool:
53
+ return bool(
54
+ "Username or password is incorrect" in output
55
+ or "Invalid master password" in output
56
+ )
57
+
58
+
59
+ def bw_args(*args: str, session: str | None = None):
60
+ cli_args = [BW_CLI]
61
+ if session:
62
+ cli_args += ["--session", session]
63
+
64
+ return [*cli_args, *args]
65
+
66
+
67
+ def bw_run(*args: str) -> subprocess.CompletedProcess[str]:
68
+ return subprocess.run(args, stdout=subprocess.PIPE, check=True, text=True)
69
+
70
+
71
+ def bw(*args: str, session: str | None = None) -> str:
72
+
73
+ cli_args = bw_args(*args, session=session)
74
+
75
+ while True:
76
+ try:
77
+ result = bw_run(*cli_args).stdout.strip()
78
+ except subprocess.CalledProcessError as exc:
79
+ output = cast(str, exc.stdout)
80
+ if wrong_password(output):
81
+ print(output)
82
+ continue
83
+ raise ValueError(output) from exc
84
+ else:
85
+ break
86
+
87
+ return result
88
+
89
+
90
+ def match_credentials(
91
+ credentials: list[Credentials], username: str
92
+ ) -> Iterable[Credentials]:
93
+ for cred in credentials:
94
+ login = cred.get("login") or {}
95
+ cred_username = login.get("username")
96
+ if cred_username == username and "password" in login:
97
+ yield cred
98
+
99
+
100
+ def select_single_match(matches: list[Credentials]) -> str | None:
101
+ if len(matches) == 0:
102
+ return
103
+
104
+ if len(matches) == 1:
105
+ (match,) = matches
106
+ try:
107
+ return match["login"]["password"]
108
+ except KeyError:
109
+ return None
110
+
111
+ raise ValueError("Multiple matches")
112
+
113
+
114
+ def display_credentials(mapping: dict[str, Credentials]) -> str:
115
+ result: list[str] = []
116
+ for val, match in mapping.items():
117
+ result.append(f"{val}) {display_credential(match)}")
118
+
119
+ return "\n".join(result)
120
+
121
+
122
+ def display_credential(match: Credentials) -> str:
123
+ return f"{match.get('name', 'no name')} - {match['login']['username']}"
124
+
125
+
126
+ class InputCallable(Protocol):
127
+ def __call__(self, prompt: str = "", /) -> str: ...
128
+
129
+
130
+ def select_from_multiple_matches(
131
+ matches: list[Credentials], input_callable: InputCallable
132
+ ) -> str | None:
133
+ print("Multiple credential found. Which one would you like to use ?")
134
+ mapping: dict[str, Credentials] = {str(i): v for i, v in enumerate(matches, 1)}
135
+ print(display_credentials(mapping))
136
+ value = input_callable("Your choice ? ")
137
+ return mapping[value]["login"]["password"]
138
+
139
+
140
+ def select_match(
141
+ matches: list[Credentials], input_callable: InputCallable
142
+ ) -> str | None:
143
+ try:
144
+ return select_single_match(matches)
145
+ except ValueError:
146
+ return select_from_multiple_matches(matches, input_callable=input_callable)
147
+
148
+
149
+ def encode(payload: dict[str, Any]) -> str:
150
+ return base64.b64encode(json.dumps(payload).encode("utf-8")).decode("utf-8")
151
+
152
+
153
+ def get_session(environ: Mapping[str, str]) -> str:
154
+ if "BW_SESSION" in environ:
155
+ try:
156
+ # Check that the token works.
157
+ bw("sync")
158
+ except ValueError:
159
+ pass
160
+ else:
161
+ return environ["BW_SESSION"]
162
+
163
+ command = ask_for_session_command(is_authenticated=user_is_authenticated())
164
+ return ask_for_session(command=command)
165
+
166
+
167
+ def get_password(
168
+ service: str,
169
+ username: str,
170
+ _input_callable: InputCallable = input,
171
+ _environ: Mapping[str, str] = os.environ,
172
+ ) -> str | None:
173
+ session = get_session(_environ)
174
+
175
+ # Making sure we're up to date
176
+ bw("sync", session=session)
177
+
178
+ results = bw("list", "items", "--search", service, session=session)
179
+
180
+ credentials = cast(list[Credentials], json.loads(results))
181
+
182
+ matches = list(match_credentials(credentials, username))
183
+
184
+ return select_match(matches, input_callable=_input_callable)
185
+
186
+
187
+ def set_password(
188
+ service: str,
189
+ username: str,
190
+ password: str,
191
+ _environ: Mapping[str, str] = os.environ,
192
+ ) -> None:
193
+ session = get_session(_environ)
194
+
195
+ template_str = bw("get", "template", "item", session=session)
196
+
197
+ template = json.loads(template_str)
198
+ template.update(
199
+ {
200
+ "name": service,
201
+ "notes": None,
202
+ "login": {
203
+ "uris": [{"match": None, "uri": service}],
204
+ "username": username,
205
+ "password": password,
206
+ },
207
+ }
208
+ )
209
+
210
+ payload = encode(template)
211
+
212
+ bw("create", "item", payload)
213
+ print("Created.")
214
+
215
+
216
+ def confirm_delete(
217
+ session: str, credential: Credentials, input_callable: InputCallable
218
+ ) -> None:
219
+
220
+ print("The following match will be DELETED:")
221
+ print(display_credential(credential))
222
+ if input_callable("Confirm ? (type 'yes')").lower() == "yes":
223
+ bw("delete", "item", credential["id"], session=session)
224
+ print("Deleted.")
225
+ return
226
+ print("Cancelled.")
227
+
228
+
229
+ def delete_password(
230
+ service: str,
231
+ username: str,
232
+ _input_callable: InputCallable = input,
233
+ _environ: Mapping[str, str] = os.environ,
234
+ ) -> None:
235
+ session = get_session(_environ)
236
+
237
+ bw("sync", session=session)
238
+
239
+ result = bw("get", "item", service, session=session)
240
+
241
+ credential = json.loads(result)
242
+
243
+ confirm_delete(session, credential, input_callable=_input_callable)
244
+
245
+
246
+ class BitwardenBackend(backend.KeyringBackend):
247
+ @properties.classproperty
248
+ @classmethod
249
+ def priority(cls) -> float:
250
+ if not bitwarden_cli_installed():
251
+ raise RuntimeError(
252
+ "Requires bitwarden cli: https://help.bitwarden.com/article/cli/"
253
+ )
254
+
255
+ return PRIORITY
256
+
257
+ def get_password(self, service: str, username: str) -> str | None:
258
+ return get_password(service, username)
259
+
260
+ def set_password(self, service: str, username: str, password: str) -> None:
261
+ return set_password(service, username, password)
262
+
263
+ def delete_password(self, service: str, username: str) -> None:
264
+ return delete_password(service, username)
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.5
2
+ Name: bitwarden-keyring
3
+ Version: 0.4.0
4
+ Summary: A Bitwarden backend for the keyring Python library
5
+ Project-URL: Homepage, https://github.com/ewjoachim/bitwarden-keyring
6
+ Project-URL: Repository, https://github.com/ewjoachim/bitwarden-keyring
7
+ Project-URL: Issues, https://github.com/ewjoachim/bitwarden-keyring/issues
8
+ Author-email: Joachim Jablon <ewjoachim@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE.md
11
+ Keywords: bitwarden,keyring,secrets
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3.15
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: keyring>=25.6.0
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Bitwarden Keyring
26
+
27
+ [![Build Status](https://travis-ci.org/ewjoachim/bitwarden-keyring.svg?branch=master)](https://travis-ci.org/ewjoachim/bitwarden-keyring)
28
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
29
+ [![PyPI version](https://badge.fury.io/py/bitwarden-keyring.svg)](https://badge.fury.io/py/bitwarden-keyring)
30
+ [![codecov](https://codecov.io/gh/ewjoachim/bitwarden-keyring/branch/master/graph/badge.svg)](https://codecov.io/gh/ewjoachim/bitwarden-keyring)
31
+
32
+
33
+ Implementation of the [Keyring](https://pypi.org/project/keyring/) backend code reading secrets from [Bitwarden](https://bitwarden.com) using [Bitwarden-cli](https://help.bitwarden.com/article/cli/)
34
+
35
+ ## Overview
36
+
37
+ The [Keyring](https://pypi.org/project/keyring/) python package provides a handy single point of entry for any secret holding system, allowing for seemless integration of those systems into applications needing secrets, like [twine]().
38
+
39
+ This projects implement Keyring to be able to read secrets from Bitwarden, an open source multiplatform cloud/self-hostable password manager.
40
+
41
+ This backend assumes that it will be used in the context of a CLI application, and that it can communicate with the user using `sdtin`, `stdout` and `stderr`. We could implement an additional backend for use in a library assuming that everything is already unlocked, or another one using `pinentry` to ask the user.
42
+
43
+
44
+ ## Requirements
45
+
46
+ This project uses the official [bitwarden CLI](https://help.bitwarden.com/article/cli/) under the hood, because there's no simple official Python bitwarden lib. Here are the installation instructions as of October 2018 and the link to the [up to date instructions](https://github.com/bitwarden/cli#downloadinstall)
47
+
48
+ You can install the Bitwarden CLI multiple different ways:
49
+
50
+ **NPM**
51
+
52
+ If you already have the Node.js runtime installed on your system, you can install the CLI using NPM. NPM makes it easy to keep your installation updated and should be the preferred installation method if you are already using Node.js.
53
+
54
+ ```bash
55
+ npm install -g @bitwarden/cli
56
+ ```
57
+
58
+ **Native Executable**
59
+
60
+ Natively packaged versions of the CLI are provided for each platform which have no requirements on installing the Node.js runtime. You can obtain these from the [downloads section](https://help.bitwarden.com/article/cli/#download--install) in the Bitwarden documentation.
61
+
62
+ **Other Package Managers**
63
+
64
+ - [Chocolatey](https://chocolatey.org/packages/bitwarden-cli)
65
+ ```powershell
66
+ choco install bitwarden-cli
67
+ ```
68
+ - [Homebrew](https://formulae.brew.sh/formula/bitwarden-cli)
69
+ ```bash
70
+ brew install bitwarden-cli
71
+ ```
72
+ - [Snap](https://snapcraft.io/bw)
73
+ ```bash
74
+ sudo snap install bw
75
+ ```
76
+
77
+ ## Installation and configuration
78
+
79
+ ```
80
+ pip install bitwarden-keyring
81
+ ```
82
+
83
+ The Python packaging ecosystem can be quite a mess.
84
+
85
+ [<img title="XKCD 1987: Python Environment. The Python environmental protection agency wants to seal it in a cement chamber, with pictorial messages to future civilizations warning them about the danger of using sudo to install random Python packages." src="https://imgs.xkcd.com/comics/python_environment_2x.png" width="400">](https://xkcd.com/1987/)
86
+
87
+ Because of this, it's likely that your setup and my setup are nothing alike. Keyring [supports](https://pypi.org/project/keyring/#config-file-content) a configuration file with an option allowing to explicitly define the path to a backend. You may need that for your installation, or maybe not.
88
+
89
+ ## Usage
90
+
91
+ Use as a normal keyring backend. It is installed with priority 10 so it's likely going to be selected
92
+ first.
93
+
94
+ If you want to use it with [twine](https://pypi.org/project/twine/), good news, you're already set. Just make sure that this package is installed in the same location as twine.
95
+
96
+ `bitwarden-keyring` will automatically ask for credentials when needed. If you don't want to unlock your vault every time, export the vault session to your environment (use `bw unlock` and follow the instructions, or launch `export BW_SESSION=$(bw unlock --raw)`).
97
+
98
+ ## Caveats
99
+
100
+ `bitwarden-keyring` was only tested with:
101
+ - macOS, using the `bitwarden-cli` from `brew`
102
+ - ubuntu, using the `bw` from `snap`
103
+
104
+ As mentionned, `bitwarden-keyring` only works in the context of a CLI application with access to standard inputs and output. If you need something that either reads silently or using another method of communication, the best is probably to make another backend and most of the functions can be reused.
105
+
106
+ ## Licensing
107
+
108
+ `bitwarden-keyring` is published under the terms of the [MIT License](LICENSE.md).
109
+ The name Bitwarden is most probably the property of 8bit Solutions LLC.
110
+
111
+
112
+ ## Contributions and Code of Conduct
113
+
114
+ Contributions are welcome, please refer to the [Contributing](CONTRIBUTING.md) guide.
115
+ Please keep in mind that all interactions with the project are required to follow the
116
+ [Code of Conduct](CODE_OF_CONDUCT.md).
@@ -0,0 +1,7 @@
1
+ bitwarden_keyring/__init__.py,sha256=eFj9aLOFZl-mG8NbejsuTfMCrmowtg2TRcpcyLqNNsk,70
2
+ bitwarden_keyring/backend.py,sha256=cIvNGG6zop7LbeOII6FuI6A4bTje4NwfftVqe61c6bQ,6898
3
+ bitwarden_keyring-0.4.0.dist-info/METADATA,sha256=70B8v75R8m9U5uHOgKEUbkVTgT281lMSwtXHESpbsBE,5947
4
+ bitwarden_keyring-0.4.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
5
+ bitwarden_keyring-0.4.0.dist-info/entry_points.txt,sha256=7nJ9gecM1pNBMnj5Y_RWNftDfbLgAoVZqsGgpwYhsMs,49
6
+ bitwarden_keyring-0.4.0.dist-info/licenses/LICENSE.md,sha256=Yjk6Pl6VfSQWmiwzvrP-vHMsffHFUogAqTgatsFlbks,1080
7
+ bitwarden_keyring-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [keyring.backends]
2
+ bitwarden = bitwarden_keyring
@@ -0,0 +1,23 @@
1
+ ```
2
+ MIT License
3
+
4
+ Copyright (c) 2018, Joachim Jablon
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ ```