passwordstore-reader 0.1.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oliver Stolpe
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: passwordstore-reader
3
+ Version: 0.1.0
4
+ Summary: Simple python library to access an existing pass password store in your scripts.
5
+ Author: Oliver Stolpe
6
+ Author-email: Oliver Stolpe <oliver.stolpe@charite.de>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: POSIX
11
+ Classifier: Topic :: Security :: Cryptography
12
+ Classifier: Typing :: Typed
13
+ Requires-Dist: python-gnupg>=0.5.6
14
+ Requires-Python: >=3.12
15
+ Project-URL: Homepage, https://github.com/bihealth/passwordstore-reader
16
+ Project-URL: Issues, https://github.com/bihealth/passwordstore-reader/issues
17
+ Description-Content-Type: text/markdown
18
+
19
+ # passwordstore-reader
20
+
21
+ Small Python library to access passwords from the [pass](https://www.passwordstore.org/) password
22
+ manager. This library relies on `gnupg`, so the `pass` command is not required to be able to use an
23
+ existing store on systems without this command available. The password store must be however
24
+ maintained on a different system with `pass` available.
25
+
26
+ It also accounts for the case that pinentry is not available on the system which would prevent
27
+ `gnupg` from using a password prompt.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ # With uv
33
+ uv add passwordstore-reader
34
+
35
+ # With pip
36
+ pip install passwordstore-reader
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ ```python
42
+ from passwordstore_reader import PasswordStore
43
+
44
+ # Create the store, assuming the PASSWORD_STORE_DIR env variable is set.
45
+ pwstore = PasswordStore()
46
+
47
+ # Create the store with a custom password store path.
48
+ pwstore = PasswordStore(password_store_dir="./password-store")
49
+
50
+ # Retrieve a password
51
+ password = pwstore.show("example/api_key")
52
+ ```
53
+
54
+ `show()` prompts for your GPG key passphrase on every call.
55
+
56
+ ### In pydantic models
57
+
58
+ If you have a pydantic model that contains credentials, you can define a mixin that you inject into
59
+ your model. This would resolve all values in your model that start with `password_store:` to the
60
+ path in the password store that follows the keyword and store the password in the value, e.g
61
+ `password = "password_store:my/secret/pass"` resolves to whatever password is stored under `pass
62
+ my/secret/pass`.
63
+
64
+ ```python
65
+ class PasswordStoreMixin:
66
+ """Mixin for configurations that include password store paths."""
67
+
68
+ @pydantic.model_validator(mode="before")
69
+ @classmethod
70
+ def resolve_password_store(cls, values):
71
+ if not isinstance(values, dict):
72
+ return values
73
+
74
+ def resolve(obj):
75
+ if isinstance(obj, str) and obj.startswith("password_store:"):
76
+ password_store_path = obj[len("password_store:") :]
77
+ return PasswordStore().show(password_store_path)
78
+ return obj
79
+
80
+ return {k: resolve(v) for k, v in values.items()}
81
+ ```
82
+
83
+ ## Requirements
84
+
85
+ - Python 3.12+
86
+
87
+ ## License
88
+
89
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,71 @@
1
+ # passwordstore-reader
2
+
3
+ Small Python library to access passwords from the [pass](https://www.passwordstore.org/) password
4
+ manager. This library relies on `gnupg`, so the `pass` command is not required to be able to use an
5
+ existing store on systems without this command available. The password store must be however
6
+ maintained on a different system with `pass` available.
7
+
8
+ It also accounts for the case that pinentry is not available on the system which would prevent
9
+ `gnupg` from using a password prompt.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ # With uv
15
+ uv add passwordstore-reader
16
+
17
+ # With pip
18
+ pip install passwordstore-reader
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```python
24
+ from passwordstore_reader import PasswordStore
25
+
26
+ # Create the store, assuming the PASSWORD_STORE_DIR env variable is set.
27
+ pwstore = PasswordStore()
28
+
29
+ # Create the store with a custom password store path.
30
+ pwstore = PasswordStore(password_store_dir="./password-store")
31
+
32
+ # Retrieve a password
33
+ password = pwstore.show("example/api_key")
34
+ ```
35
+
36
+ `show()` prompts for your GPG key passphrase on every call.
37
+
38
+ ### In pydantic models
39
+
40
+ If you have a pydantic model that contains credentials, you can define a mixin that you inject into
41
+ your model. This would resolve all values in your model that start with `password_store:` to the
42
+ path in the password store that follows the keyword and store the password in the value, e.g
43
+ `password = "password_store:my/secret/pass"` resolves to whatever password is stored under `pass
44
+ my/secret/pass`.
45
+
46
+ ```python
47
+ class PasswordStoreMixin:
48
+ """Mixin for configurations that include password store paths."""
49
+
50
+ @pydantic.model_validator(mode="before")
51
+ @classmethod
52
+ def resolve_password_store(cls, values):
53
+ if not isinstance(values, dict):
54
+ return values
55
+
56
+ def resolve(obj):
57
+ if isinstance(obj, str) and obj.startswith("password_store:"):
58
+ password_store_path = obj[len("password_store:") :]
59
+ return PasswordStore().show(password_store_path)
60
+ return obj
61
+
62
+ return {k: resolve(v) for k, v in values.items()}
63
+ ```
64
+
65
+ ## Requirements
66
+
67
+ - Python 3.12+
68
+
69
+ ## License
70
+
71
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,57 @@
1
+ [project]
2
+ name = "passwordstore-reader"
3
+ version = "0.1.0"
4
+ description = "Simple python library to access an existing pass password store in your scripts."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Operating System :: POSIX",
12
+ "Topic :: Security :: Cryptography",
13
+ "Typing :: Typed",
14
+ ]
15
+ dependencies = ["python-gnupg>=0.5.6"]
16
+
17
+ [[project.authors]]
18
+ name = "Oliver Stolpe"
19
+ email = "oliver.stolpe@charite.de"
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/bihealth/passwordstore-reader"
23
+ Issues = "https://github.com/bihealth/passwordstore-reader/issues"
24
+
25
+ [dependency-groups]
26
+ dev = [
27
+ "pyrefly>=1.0.0",
28
+ "pytest",
29
+ "pytest-cov>=7.1.0",
30
+ "ruff",
31
+ ]
32
+
33
+ [tool.uv]
34
+ package = true
35
+
36
+ [tool.uv.sources]
37
+
38
+ [tool.ruff]
39
+ line-length = 100
40
+ target-version = "py312"
41
+
42
+ [tool.ruff.lint]
43
+ select = [
44
+ "E",
45
+ "F",
46
+ "I",
47
+ ]
48
+
49
+ [tool.pyrefly]
50
+ project-includes = [
51
+ "**/*.py*",
52
+ "**/*.ipynb",
53
+ ]
54
+
55
+ [build-system]
56
+ requires = ["uv_build>=0.9.5,<0.10.0"]
57
+ build-backend = "uv_build"
@@ -0,0 +1,58 @@
1
+ [project]
2
+ name = "passwordstore-reader"
3
+ version = "0.1.0"
4
+ description = "Simple python library to access an existing pass password store in your scripts."
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Oliver Stolpe", email = "oliver.stolpe@charite.de" }
8
+ ]
9
+ license = "MIT"
10
+ license-files = ["LICENSE"]
11
+ requires-python = ">=3.12"
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "Operating System :: POSIX",
15
+ "Topic :: Security :: Cryptography",
16
+ "Typing :: Typed",
17
+ ]
18
+ dependencies = [
19
+ "python-gnupg>=0.5.6",
20
+ ]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/bihealth/passwordstore-reader"
24
+ Issues = "https://github.com/bihealth/passwordstore-reader/issues"
25
+
26
+ [dependency-groups]
27
+ dev = [
28
+ "pyrefly>=1.0.0",
29
+ "pytest",
30
+ "pytest-cov>=7.1.0",
31
+ "ruff",
32
+ ]
33
+
34
+ [tool.uv]
35
+ package = true
36
+
37
+ [tool.uv.sources]
38
+
39
+ [tool.ruff]
40
+ line-length = 100
41
+ target-version = "py312"
42
+
43
+ [tool.ruff.lint]
44
+ select = [
45
+ "E", # pycodestyle errors
46
+ "F", # pyflakes
47
+ "I", # isort
48
+ ]
49
+
50
+ [tool.pyrefly]
51
+ project-includes = [
52
+ "**/*.py*",
53
+ "**/*.ipynb",
54
+ ]
55
+
56
+ [build-system]
57
+ requires = ["uv_build>=0.9.5,<0.10.0"]
58
+ build-backend = "uv_build"
@@ -0,0 +1,3 @@
1
+ from .core import PasswordStore
2
+
3
+ __all__ = ["PasswordStore"]
@@ -0,0 +1,81 @@
1
+ import getpass
2
+ import os
3
+
4
+ import gnupg
5
+
6
+ from .validator import validate_path
7
+
8
+
9
+ class PasswordStore:
10
+ """Read access to an existing pass password store.
11
+
12
+ Entries are decrypted directly with GnuPG, so the ``pass`` command is not needed.
13
+
14
+ Attributes:
15
+ password_store_dir (str): Directory of the password store in use.
16
+ """
17
+
18
+ def __init__(self, password_store_dir: str | None = None) -> None:
19
+ """Open the password store in ``password_store_dir``.
20
+
21
+ Args:
22
+ password_store_dir (str | None): Directory of the password store. If not given, the
23
+ ``PASSWORD_STORE_DIR`` environment variable is used.
24
+
25
+ Raises:
26
+ RuntimeError: If no directory is given and ``PASSWORD_STORE_DIR`` is not set.
27
+ ValueError: If the directory does not exist or its path contains characters other
28
+ than letters, digits, ``.``, ``_``, ``/`` and ``-`` (so no spaces or ``~``).
29
+ """
30
+
31
+ self.password_store_dir = password_store_dir or os.environ.get("PASSWORD_STORE_DIR", "")
32
+
33
+ if not self.password_store_dir:
34
+ raise RuntimeError(
35
+ "password_store_dir not set. Please provide PASSWORD_STORE_DIR in the "
36
+ "environment or pass a directory to the constructor"
37
+ )
38
+
39
+ validate_path(self.password_store_dir)
40
+
41
+ def show(self, entry: str) -> str:
42
+ """Decrypt and return an entry, like ``pass show <entry>``.
43
+
44
+ Prompts for the GPG key passphrase on every call.
45
+
46
+ Args:
47
+ entry (str): Name of the entry, relative to the store and without ``.gpg``,
48
+ e.g. ``example/api_key``.
49
+
50
+ Returns:
51
+ str: The decrypted content with leading and trailing whitespace stripped.
52
+ Multi-line entries are returned in full.
53
+
54
+ Raises:
55
+ RuntimeError: If the entry name is empty or the entry cannot be decrypted.
56
+ ValueError: If the entry contains disallowed characters, escapes the password
57
+ store directory, or does not exist.
58
+ """
59
+ if not entry:
60
+ raise RuntimeError("Entry name cannot be empty")
61
+
62
+ gpg = gnupg.GPG()
63
+ password_store_file = self.password_store_dir + "/" + entry + ".gpg"
64
+
65
+ validate_path(password_store_file, self.password_store_dir)
66
+
67
+ passphrase = getpass.getpass("Enter gpg key password: ")
68
+
69
+ with open(password_store_file, "rb") as fh:
70
+ decrypted_data = gpg.decrypt_file(fh, passphrase=passphrase)
71
+
72
+ if not decrypted_data.ok:
73
+ raise RuntimeError(
74
+ f"Failed to decrypt password file for entry '{entry}': {decrypted_data.status}"
75
+ )
76
+
77
+ data = decrypted_data.data
78
+ # python-gnupg sets data to bytes on a successful decrypt; '' is only its placeholder.
79
+ assert isinstance(data, bytes)
80
+
81
+ return data.decode().strip()
@@ -0,0 +1,47 @@
1
+ import os
2
+ import re
3
+
4
+
5
+ class ValidPath(str):
6
+ """A validated path that is safe to use in filesystem operations."""
7
+
8
+ pass
9
+
10
+
11
+ def validate_path(path: str, password_store_dir: str | None = None) -> ValidPath:
12
+ """Validate that a path is safe, doesn't contain malicious characters, and is within the
13
+ store dir.
14
+
15
+ Args:
16
+ path: The path to validate
17
+ password_store_dir: The root directory of the password store (optional, but recommended)
18
+
19
+ Raises:
20
+ ValueError: If the path contains unsafe characters or escapes the store dir
21
+ """
22
+ if not path:
23
+ raise ValueError("Path cannot be empty")
24
+
25
+ # Explicitly check for path traversal attempts first (security-critical)
26
+ if ".." in path or "\\" in path:
27
+ raise ValueError(f"Path traversal attempt detected: {path}")
28
+
29
+ # Only allow alphanumeric characters, hyphens, underscores, dots, and slashes
30
+ if not re.match(r"^[a-zA-Z0-9._/-]+$", path):
31
+ raise ValueError(
32
+ f"Invalid path: {path}. "
33
+ "Only alphanumeric, hyphens, underscores, dots, and slashes allowed"
34
+ )
35
+
36
+ # Absolute path enforcement: ensure path is within password_store_dir if provided
37
+ if password_store_dir is not None:
38
+ real_path = os.path.realpath(path)
39
+ real_store = os.path.realpath(password_store_dir)
40
+ if not real_path.startswith(real_store + os.sep):
41
+ raise ValueError(f"Resolved path escapes password store directory: {path}")
42
+
43
+ # Check if the path points to an existing directory or file
44
+ if not os.path.isdir(path) and not os.path.isfile(path):
45
+ raise ValueError(f"Invalid path: {path}. Path does not point to a directory or file")
46
+
47
+ return ValidPath(path)