pwdlib 0.2.0__tar.gz → 0.3.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.
Files changed (41) hide show
  1. pwdlib-0.3.0/.github/copilot-instructions.md +25 -0
  2. pwdlib-0.3.0/.github/dependabot.yml +13 -0
  3. pwdlib-0.3.0/.github/workflows/build.yml +71 -0
  4. pwdlib-0.3.0/.github/workflows/copilot-setup-steps.yml +31 -0
  5. pwdlib-0.3.0/.github/workflows/documentation.yml +58 -0
  6. pwdlib-0.3.0/.zed/settings.json +30 -0
  7. {pwdlib-0.2.0 → pwdlib-0.3.0}/PKG-INFO +9 -18
  8. {pwdlib-0.2.0 → pwdlib-0.3.0}/README.md +2 -11
  9. pwdlib-0.3.0/justfile +29 -0
  10. {pwdlib-0.2.0 → pwdlib-0.3.0}/mkdocs.yml +19 -19
  11. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/__init__.py +1 -1
  12. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/_hash.py +13 -14
  13. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/exceptions.py +2 -5
  14. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/hashers/argon2.py +31 -17
  15. pwdlib-0.3.0/pwdlib/hashers/base.py +38 -0
  16. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/hashers/bcrypt.py +12 -16
  17. {pwdlib-0.2.0 → pwdlib-0.3.0}/pyproject.toml +36 -59
  18. pwdlib-0.3.0/tests/data/argon2id_large_hash +1 -0
  19. pwdlib-0.3.0/tests/hashers/test_argon2.py +109 -0
  20. {pwdlib-0.2.0 → pwdlib-0.3.0}/tests/hashers/test_bcrypt.py +24 -4
  21. {pwdlib-0.2.0 → pwdlib-0.3.0}/tests/test_hash.py +24 -4
  22. pwdlib-0.3.0/uv.lock +1180 -0
  23. pwdlib-0.2.0/.github/workflows/build.yml +0 -86
  24. pwdlib-0.2.0/.github/workflows/documentation.yml +0 -56
  25. pwdlib-0.2.0/.vscode/settings.json +0 -21
  26. pwdlib-0.2.0/pwdlib/hashers/base.py +0 -32
  27. pwdlib-0.2.0/tests/hashers/test_argon2.py +0 -52
  28. {pwdlib-0.2.0 → pwdlib-0.3.0}/.editorconfig +0 -0
  29. {pwdlib-0.2.0 → pwdlib-0.3.0}/.github/FUNDING.yml +0 -0
  30. {pwdlib-0.2.0 → pwdlib-0.3.0}/.gitignore +0 -0
  31. {pwdlib-0.2.0 → pwdlib-0.3.0}/LICENSE +0 -0
  32. {pwdlib-0.2.0 → pwdlib-0.3.0}/docs/guide.md +0 -0
  33. {pwdlib-0.2.0 → pwdlib-0.3.0}/docs/index.md +0 -0
  34. {pwdlib-0.2.0 → pwdlib-0.3.0}/docs/reference/pwdlib.exceptions.md +0 -0
  35. {pwdlib-0.2.0 → pwdlib-0.3.0}/docs/reference/pwdlib.hashers.md +0 -0
  36. {pwdlib-0.2.0 → pwdlib-0.3.0}/docs/reference/pwdlib.md +0 -0
  37. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/hashers/__init__.py +0 -0
  38. {pwdlib-0.2.0 → pwdlib-0.3.0}/pwdlib/py.typed +0 -0
  39. {pwdlib-0.2.0 → pwdlib-0.3.0}/tests/__init__.py +0 -0
  40. {pwdlib-0.2.0 → pwdlib-0.3.0}/tests/conftest.py +0 -0
  41. {pwdlib-0.2.0 → pwdlib-0.3.0}/tests/hashers/__init__.py +0 -0
@@ -0,0 +1,25 @@
1
+ # GitHub Copilot Instructions
2
+
3
+ This document provides essential guidance for AI agents contributing to pwdlib. Imagine this file as a new joiner to the team who needs to understand the coding standards, practices, and conventions used in this repository.
4
+
5
+ ## General Guidelines
6
+
7
+ - Do not add comments to the code unless necessary. The code should be self-explanatory.
8
+ - Use meaningful variable and function names.
9
+ - Follow good practices and code conventions.
10
+ - Make sure that all the new code is maintanable and follows the SOLID principles.
11
+ - Do not modify unrelated code to the task or issue you are working on.
12
+
13
+ ### Linting and testing
14
+
15
+ The project requires to be linted and type-checked. To do so, run:
16
+
17
+ ```bash
18
+ just lint
19
+ ```
20
+
21
+ Tests are located in the `tests/` directory. It uses `pytest` for testing. To run the tests, use:
22
+
23
+ ```bash
24
+ just test
25
+ ```
@@ -0,0 +1,13 @@
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+
4
+ version: 2
5
+ updates:
6
+ - package-ecosystem: "github-actions" # See documentation for possible values
7
+ directory: "/" # Location of package manifests
8
+ schedule:
9
+ interval: "weekly"
10
+ - package-ecosystem: "pip"
11
+ directory: "/"
12
+ schedule:
13
+ interval: "weekly"
@@ -0,0 +1,71 @@
1
+ name: Build
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ test:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python_version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
11
+
12
+ steps:
13
+ - uses: actions/checkout@v5
14
+ - name: Set up Python
15
+ uses: actions/setup-python@v6
16
+ with:
17
+ python-version: ${{ matrix.python_version }}
18
+ - name: Setup Just
19
+ uses: extractions/setup-just@v3
20
+ - name: Install uv and set the Python version
21
+ uses: astral-sh/setup-uv@v6
22
+ with:
23
+ python-version: ${{ matrix.python-version }}
24
+ - name: Install the project
25
+ run: uv sync --locked --all-extras --dev
26
+ - name: Lint and typecheck
27
+ run: |
28
+ just lint-check
29
+ - name: Test
30
+ run: |
31
+ just test-cov-xml
32
+ - uses: codecov/codecov-action@v5
33
+ with:
34
+ token: ${{ secrets.CODECOV_TOKEN }}
35
+ fail_ci_if_error: true
36
+ verbose: true
37
+
38
+ release:
39
+ runs-on: ubuntu-latest
40
+ environment: release
41
+ needs: test
42
+ if: startsWith(github.ref, 'refs/tags/')
43
+ permissions:
44
+ contents: write
45
+ id-token: write
46
+
47
+ steps:
48
+ - uses: actions/checkout@v5
49
+ - name: Set up Python
50
+ uses: actions/setup-python@v6
51
+ with:
52
+ python-version: "3.10"
53
+ - name: Setup Just
54
+ uses: extractions/setup-just@v3
55
+ - name: Install uv and set the Python version
56
+ uses: astral-sh/setup-uv@v6
57
+ with:
58
+ python-version: "3.10"
59
+ - name: Install the project
60
+ run: uv sync --locked --all-extras --dev
61
+ - name: Build and publish on PyPI
62
+ run: |
63
+ uv build
64
+ uv publish
65
+ - name: Create release
66
+ uses: ncipollo/release-action@v1
67
+ with:
68
+ draft: true
69
+ body: ${{ github.event.head_commit.message }}
70
+ artifacts: dist/*.whl,dist/*.tar.gz
71
+ token: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,31 @@
1
+ name: "Copilot Setup Steps"
2
+
3
+ # Automatically run the setup steps when they are changed to allow for easy validation, and
4
+ # allow manual testing through the repository's "Actions" tab
5
+ on:
6
+ workflow_dispatch:
7
+ push:
8
+ paths:
9
+ - .github/workflows/copilot-setup-steps.yml
10
+ pull_request:
11
+ paths:
12
+ - .github/workflows/copilot-setup-steps.yml
13
+
14
+ jobs:
15
+ # The job MUST be called `copilot-setup-steps` or it will not be picked up by Copilot.
16
+ copilot-setup-steps:
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - uses: actions/checkout@v5
20
+ - name: Set up Python
21
+ uses: actions/setup-python@v6
22
+ with:
23
+ python-version: "3.10"
24
+ - name: Setup Just
25
+ uses: extractions/setup-just@v3
26
+ - name: Install uv and set the Python version
27
+ uses: astral-sh/setup-uv@v6
28
+ with:
29
+ python-version: "3.10"
30
+ - name: Install the project
31
+ run: uv sync --locked --all-extras --dev
@@ -0,0 +1,58 @@
1
+ name: Build documentation
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
9
+ permissions:
10
+ contents: read
11
+ pages: write
12
+ id-token: write
13
+
14
+ # Allow one concurrent deployment
15
+ concurrency:
16
+ group: "pages"
17
+ cancel-in-progress: true
18
+
19
+ # Default to bash
20
+ defaults:
21
+ run:
22
+ shell: bash
23
+
24
+ jobs:
25
+ build:
26
+ runs-on: ubuntu-latest
27
+
28
+ steps:
29
+ - uses: actions/checkout@v5
30
+ - name: Set up Python
31
+ uses: actions/setup-python@v6
32
+ with:
33
+ python-version: "3.10"
34
+ - name: Setup Just
35
+ uses: extractions/setup-just@v3
36
+ - name: Install uv and set the Python version
37
+ uses: astral-sh/setup-uv@v6
38
+ with:
39
+ python-version: "3.10"
40
+ - name: Install the project
41
+ run: uv sync --locked --all-extras --dev
42
+ - name: Build
43
+ run: just docs-build
44
+ - name: Upload artifact
45
+ uses: actions/upload-pages-artifact@v4
46
+ with:
47
+ path: ./site
48
+
49
+ deploy:
50
+ environment:
51
+ name: github-pages
52
+ url: ${{ steps.deployment.outputs.page_url }}
53
+ runs-on: ubuntu-latest
54
+ needs: build
55
+ steps:
56
+ - name: Deploy to GitHub Pages
57
+ id: deployment
58
+ uses: actions/deploy-pages@v4
@@ -0,0 +1,30 @@
1
+ {
2
+ "languages": {
3
+ "Python": {
4
+ "language_servers": ["ty", "basedpyright", "ruff", "!pylsp"],
5
+ "format_on_save": "on",
6
+ "wrap_guides": [88],
7
+ "formatter": [
8
+ { "code_action": "source.organizeImports.ruff" },
9
+ { "code_action": "source.fixAll.ruff" },
10
+ {
11
+ "language_server": {
12
+ "name": "ruff"
13
+ }
14
+ }
15
+ ]
16
+ }
17
+ },
18
+ "lsp": {
19
+ "basedpyright": {
20
+ "settings": {
21
+ "python": {
22
+ "pythonPath": ".hatch/pwdlib/bin/python"
23
+ },
24
+ "basedpyright.analysis": {
25
+ "autoImportCompletions": true
26
+ }
27
+ }
28
+ }
29
+ }
30
+ }
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: pwdlib
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Modern password hashing for Python
5
5
  Project-URL: Documentation, https://frankie567.github.io/pwdlib/
6
6
  Project-URL: Source, https://github.com/frankie567/pwdlib
@@ -10,18 +10,18 @@ Classifier: Development Status :: 4 - Beta
10
10
  Classifier: Intended Audience :: Developers
11
11
  Classifier: License :: OSI Approved :: MIT License
12
12
  Classifier: Programming Language :: Python :: 3 :: Only
13
- Classifier: Programming Language :: Python :: 3.8
14
- Classifier: Programming Language :: Python :: 3.9
15
13
  Classifier: Programming Language :: Python :: 3.10
16
14
  Classifier: Programming Language :: Python :: 3.11
17
15
  Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
18
  Classifier: Topic :: Security
19
19
  Classifier: Topic :: Security :: Cryptography
20
- Requires-Python: >=3.8
20
+ Requires-Python: >=3.10
21
21
  Provides-Extra: argon2
22
- Requires-Dist: argon2-cffi==23.1.0; extra == 'argon2'
22
+ Requires-Dist: argon2-cffi<26,>=23.1.0; extra == 'argon2'
23
23
  Provides-Extra: bcrypt
24
- Requires-Dist: bcrypt==4.1.2; extra == 'bcrypt'
24
+ Requires-Dist: bcrypt<6,>=4.1.2; extra == 'bcrypt'
25
25
  Description-Content-Type: text/markdown
26
26
 
27
27
  # pwdlib
@@ -35,15 +35,6 @@ Description-Content-Type: text/markdown
35
35
  [![PyPI version](https://badge.fury.io/py/pwdlib.svg)](https://badge.fury.io/py/pwdlib)
36
36
  [![Downloads](https://pepy.tech/badge/pwdlib)](https://pepy.tech/project/pwdlib)
37
37
 
38
- <p align="center">
39
- <a href="https://polar.sh/frankie567">
40
- <picture>
41
- <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/embed/subscribe.svg?org=frankie567&darkmode=1">
42
- <img alt="Subscribe" src="https://polar.sh/embed/subscribe.svg?org=frankie567">
43
- </picture>
44
- </a>
45
- </p>
46
-
47
38
  ---
48
39
 
49
40
  **Documentation**: <a href="https://frankie567.github.io/pwdlib/" target="_blank">https://frankie567.github.io/pwdlib/</a>
@@ -86,14 +77,14 @@ That's why I decided to start `pwdlib`, a password hash helper for the modern Py
86
77
 
87
78
  ### Setup environment
88
79
 
89
- We use [Hatch](https://hatch.pypa.io/latest/install/) to manage the development environment and production build. Ensure it's installed on your system.
80
+ We use [uv](https://docs.astral.sh/uv/) to manage the development environment and production build, and [just](https://github.com/casey/just) to manage command shortcuts. Ensure they are installed on your system.
90
81
 
91
82
  ### Run unit tests
92
83
 
93
84
  You can run all the tests with:
94
85
 
95
86
  ```bash
96
- hatch run test
87
+ just test
97
88
  ```
98
89
 
99
90
  ### Format the code
@@ -9,15 +9,6 @@
9
9
  [![PyPI version](https://badge.fury.io/py/pwdlib.svg)](https://badge.fury.io/py/pwdlib)
10
10
  [![Downloads](https://pepy.tech/badge/pwdlib)](https://pepy.tech/project/pwdlib)
11
11
 
12
- <p align="center">
13
- <a href="https://polar.sh/frankie567">
14
- <picture>
15
- <source media="(prefers-color-scheme: dark)" srcset="https://polar.sh/embed/subscribe.svg?org=frankie567&darkmode=1">
16
- <img alt="Subscribe" src="https://polar.sh/embed/subscribe.svg?org=frankie567">
17
- </picture>
18
- </a>
19
- </p>
20
-
21
12
  ---
22
13
 
23
14
  **Documentation**: <a href="https://frankie567.github.io/pwdlib/" target="_blank">https://frankie567.github.io/pwdlib/</a>
@@ -60,14 +51,14 @@ That's why I decided to start `pwdlib`, a password hash helper for the modern Py
60
51
 
61
52
  ### Setup environment
62
53
 
63
- We use [Hatch](https://hatch.pypa.io/latest/install/) to manage the development environment and production build. Ensure it's installed on your system.
54
+ We use [uv](https://docs.astral.sh/uv/) to manage the development environment and production build, and [just](https://github.com/casey/just) to manage command shortcuts. Ensure they are installed on your system.
64
55
 
65
56
  ### Run unit tests
66
57
 
67
58
  You can run all the tests with:
68
59
 
69
60
  ```bash
70
- hatch run test
61
+ just test
71
62
  ```
72
63
 
73
64
  ### Format the code
pwdlib-0.3.0/justfile ADDED
@@ -0,0 +1,29 @@
1
+ # https://just.systems
2
+
3
+ install:
4
+ uv sync --all-extras
5
+
6
+ lint:
7
+ uv run ruff format .
8
+ uv run ruff check --fix .
9
+ uv run mypy pwdlib/
10
+
11
+ lint-check:
12
+ uv run ruff format --check .
13
+ uv run ruff check .
14
+ uv run mypy pwdlib/
15
+
16
+ test:
17
+ uv run pytest
18
+
19
+ test-cov-xml:
20
+ uv run pytest --cov-report=xml
21
+
22
+ docs-serve:
23
+ uv run mkdocs serve
24
+
25
+ docs-build:
26
+ uv run mkdocs build
27
+
28
+ version bump:
29
+ uvx hatch version {{bump}}
@@ -12,8 +12,8 @@ theme:
12
12
  # Palette toggle for automatic mode
13
13
  - media: "(prefers-color-scheme)"
14
14
  toggle:
15
- icon: material/brightness-auto
16
- name: Switch to light mode
15
+ icon: material/brightness-auto
16
+ name: Switch to light mode
17
17
 
18
18
  # Palette toggle for light mode
19
19
  - media: "(prefers-color-scheme: light)"
@@ -21,8 +21,8 @@ theme:
21
21
  primary: amber
22
22
  accent: amber
23
23
  toggle:
24
- icon: material/brightness-7
25
- name: Switch to dark mode
24
+ icon: material/brightness-7
25
+ name: Switch to dark mode
26
26
 
27
27
  # Palette toggle for dark mode
28
28
  - media: "(prefers-color-scheme: dark)"
@@ -30,18 +30,18 @@ theme:
30
30
  primary: amber
31
31
  accent: amber
32
32
  toggle:
33
- icon: material/brightness-4
34
- name: Switch to light mode
33
+ icon: material/brightness-4
34
+ name: Switch to light mode
35
35
  features:
36
- - content.code.copy
36
+ - content.code.copy
37
37
 
38
38
  markdown_extensions:
39
39
  - toc:
40
- permalink: true
40
+ permalink: true
41
41
  - pymdownx.highlight:
42
- anchor_linenums: true
42
+ anchor_linenums: true
43
43
  - pymdownx.tasklist:
44
- custom_checkbox: true
44
+ custom_checkbox: true
45
45
  - pymdownx.inlinehilite
46
46
  - pymdownx.snippets
47
47
  - pymdownx.superfences
@@ -51,12 +51,12 @@ plugins:
51
51
  - search
52
52
  - autorefs
53
53
  - mkdocstrings:
54
- handlers:
55
- python:
56
- import:
57
- - https://docs.python.org/3.8/objects.inv
58
- options:
59
- docstring_style: google
54
+ handlers:
55
+ python:
56
+ import:
57
+ - https://docs.python.org/3.10/objects.inv
58
+ options:
59
+ docstring_style: google
60
60
 
61
61
  watch:
62
62
  - docs
@@ -66,6 +66,6 @@ nav:
66
66
  - About: index.md
67
67
  - Guide: guide.md
68
68
  - Reference:
69
- - pwdlib: reference/pwdlib.md
70
- - pwdlib.exceptions: reference/pwdlib.exceptions.md
71
- - pwdlib.hashers: reference/pwdlib.hashers.md
69
+ - pwdlib: reference/pwdlib.md
70
+ - pwdlib.exceptions: reference/pwdlib.exceptions.md
71
+ - pwdlib.hashers: reference/pwdlib.hashers.md
@@ -1,6 +1,6 @@
1
1
  """Modern password hashing for Python"""
2
2
 
3
- __version__ = "0.2.0"
3
+ __version__ = "0.3.0"
4
4
 
5
5
  from ._hash import PasswordHash
6
6
 
@@ -1,7 +1,8 @@
1
- import typing
1
+ import collections.abc
2
2
 
3
3
  from . import exceptions
4
4
  from .hashers import HasherProtocol
5
+ from .hashers.base import validate_str_or_bytes
5
6
 
6
7
 
7
8
  class PasswordHash:
@@ -9,7 +10,7 @@ class PasswordHash:
9
10
  Represents a password hashing utility.
10
11
  """
11
12
 
12
- def __init__(self, hashers: typing.Sequence[HasherProtocol]) -> None:
13
+ def __init__(self, hashers: collections.abc.Sequence[HasherProtocol]) -> None:
13
14
  """
14
15
  Args:
15
16
  hashers: A sequence of hashers to be used for password hashing.
@@ -38,12 +39,7 @@ class PasswordHash:
38
39
 
39
40
  return cls((Argon2Hasher(),))
40
41
 
41
- def hash(
42
- self,
43
- password: typing.Union[str, bytes],
44
- *,
45
- salt: typing.Union[bytes, None] = None,
46
- ) -> str:
42
+ def hash(self, password: str | bytes, *, salt: bytes | None = None) -> str:
47
43
  """
48
44
  Hashes a password using the current hasher.
49
45
 
@@ -57,11 +53,10 @@ class PasswordHash:
57
53
  Examples:
58
54
  >>> hash = password_hash.hash("herminetincture")
59
55
  """
56
+ validate_str_or_bytes(password, "password")
60
57
  return self.current_hasher.hash(password, salt=salt)
61
58
 
62
- def verify(
63
- self, password: typing.Union[str, bytes], hash: typing.Union[str, bytes]
64
- ) -> bool:
59
+ def verify(self, password: str | bytes, hash: str | bytes) -> bool:
65
60
  """
66
61
  Verifies if a password matches a given hash.
67
62
 
@@ -82,14 +77,16 @@ class PasswordHash:
82
77
  >>> password_hash.verify("INVALID_PASSWORD", hash)
83
78
  False
84
79
  """
80
+ validate_str_or_bytes(password, "password")
81
+ validate_str_or_bytes(hash, "hash")
85
82
  for hasher in self.hashers:
86
83
  if hasher.identify(hash):
87
84
  return hasher.verify(password, hash)
88
85
  raise exceptions.UnknownHashError(hash)
89
86
 
90
87
  def verify_and_update(
91
- self, password: typing.Union[str, bytes], hash: typing.Union[str, bytes]
92
- ) -> typing.Tuple[bool, typing.Union[str, None]]:
88
+ self, password: str | bytes, hash: str | bytes
89
+ ) -> tuple[bool, str | None]:
93
90
  """
94
91
  Verifies if a password matches a given hash and updates the hash if necessary.
95
92
 
@@ -107,12 +104,14 @@ class PasswordHash:
107
104
  Examples:
108
105
  >>> valid, updated_hash = password_hash.verify_and_update("herminetincture", hash)
109
106
  """
107
+ validate_str_or_bytes(password, "password")
108
+ validate_str_or_bytes(hash, "hash")
110
109
  for hasher in self.hashers:
111
110
  if hasher.identify(hash):
112
111
  if not hasher.verify(password, hash):
113
112
  return False, None
114
113
  else:
115
- updated_hash: typing.Union[str, None] = None
114
+ updated_hash: str | None = None
116
115
  if hasher != self.current_hasher or hasher.check_needs_rehash(hash):
117
116
  updated_hash = self.current_hasher.hash(password)
118
117
  return True, updated_hash
@@ -1,6 +1,3 @@
1
- import typing
2
-
3
-
4
1
  class PwdlibError(Exception):
5
2
  """
6
3
  Base pwdlib error.
@@ -31,7 +28,7 @@ class HasherNotAvailable(PwdlibError):
31
28
  message = (
32
29
  f"The {hasher} hash algorithm is not available. "
33
30
  "Are you sure it's installed? "
34
- f"Try to run `pip install pdwlib[{hasher}]`."
31
+ f"Try to run `pip install pwdlib[{hasher}]`."
35
32
  )
36
33
  super().__init__(message)
37
34
 
@@ -41,7 +38,7 @@ class UnknownHashError(PwdlibError):
41
38
  Error raised when the hash can't be identified from the list of provided hashers.
42
39
  """
43
40
 
44
- def __init__(self, hash: typing.Union[str, bytes]) -> None:
41
+ def __init__(self, hash: str | bytes) -> None:
45
42
  """
46
43
  Args:
47
44
  hash:
@@ -1,14 +1,24 @@
1
- import typing
1
+ import re
2
2
 
3
3
  try:
4
4
  import argon2.exceptions
5
5
  from argon2 import PasswordHasher
6
- except ImportError as e:
6
+ except ImportError as e: # pragma: no cover
7
7
  from ..exceptions import HasherNotAvailable
8
8
 
9
9
  raise HasherNotAvailable("argon2") from e
10
10
 
11
- from .base import HasherProtocol, ensure_str
11
+ from .base import HasherProtocol, ensure_str, validate_str_or_bytes
12
+
13
+ # Pattern for identifying and validating an Argon2 encoded hash, covering all currently
14
+ # supported type variants (i.e., `id`, `i`, `d`). Pattern uses deterministic matching,
15
+ # explicit anchors, and a non-greedy terminal quantifier to ensure linear run time
16
+ # relative to input hash length and resilience against catastrophic backtracking attacks.
17
+ ARGON2_ENCODED_HASH_REGEX: re.Pattern = re.compile(
18
+ r"^\$(?P<variant>argon2(id|i|d))\$(?:v=(?P<version>\d+)\$)?"
19
+ r"m=(?P<memory_cost>\d+),t=(?P<time_cost>\d+),p=(?P<parallelism>\d+)"
20
+ r"(?:\$(?P<salt>[^$]+)(?:\$(?P<digest>.+?))?)?$"
21
+ )
12
22
 
13
23
 
14
24
  class Argon2Hasher(HasherProtocol):
@@ -41,22 +51,25 @@ class Argon2Hasher(HasherProtocol):
41
51
  )
42
52
 
43
53
  @classmethod
44
- def identify(cls, hash: typing.Union[str, bytes]) -> bool:
45
- return ensure_str(hash).startswith("$argon2id$")
54
+ def identify(cls, hash: str | bytes) -> bool:
55
+ validate_str_or_bytes(hash, "hash")
56
+ try:
57
+ hash_str = ensure_str(hash)
58
+ except UnicodeDecodeError:
59
+ return False
60
+ match = ARGON2_ENCODED_HASH_REGEX.fullmatch(hash_str)
61
+ if match is None:
62
+ return False
63
+ variant: str = match.group("variant")
64
+ return variant in {"argon2id", "argon2i", "argon2d"}
46
65
 
47
- def hash(
48
- self,
49
- password: typing.Union[str, bytes],
50
- *,
51
- salt: typing.Union[bytes, None] = None,
52
- ) -> str:
66
+ def hash(self, password: str | bytes, *, salt: bytes | None = None) -> str:
67
+ validate_str_or_bytes(password, "password")
53
68
  return self._hasher.hash(password, salt=salt)
54
69
 
55
- def verify(
56
- self,
57
- password: typing.Union[str, bytes],
58
- hash: typing.Union[str, bytes],
59
- ) -> bool:
70
+ def verify(self, password: str | bytes, hash: str | bytes) -> bool:
71
+ validate_str_or_bytes(password, "password")
72
+ validate_str_or_bytes(hash, "hash")
60
73
  try:
61
74
  return self._hasher.verify(hash, password)
62
75
  except (
@@ -65,5 +78,6 @@ class Argon2Hasher(HasherProtocol):
65
78
  ):
66
79
  return False
67
80
 
68
- def check_needs_rehash(self, hash: typing.Union[str, bytes]) -> bool:
81
+ def check_needs_rehash(self, hash: str | bytes) -> bool:
82
+ validate_str_or_bytes(hash, "hash")
69
83
  return self._hasher.check_needs_rehash(ensure_str(hash))
@@ -0,0 +1,38 @@
1
+ import typing
2
+
3
+
4
+ def validate_str_or_bytes(value: typing.Any, param_name: str) -> None:
5
+ """
6
+ Validate that a value is a string or bytes.
7
+
8
+ Args:
9
+ value: The value to validate.
10
+ param_name: The name of the parameter being validated.
11
+
12
+ Raises:
13
+ TypeError: If the value is not a string or bytes.
14
+ """
15
+ if not isinstance(value, (str, bytes)):
16
+ raise TypeError(f"{param_name} must be str or bytes") # noqa: TRY003
17
+
18
+
19
+ def ensure_str(v: str | bytes, *, encoding: str = "utf-8") -> str:
20
+ return v.decode(encoding) if isinstance(v, bytes) else v
21
+
22
+
23
+ def ensure_bytes(v: str | bytes, *, encoding: str = "utf-8") -> bytes:
24
+ return v.encode(encoding) if isinstance(v, str) else v
25
+
26
+
27
+ class HasherProtocol(typing.Protocol):
28
+ @classmethod
29
+ def identify(cls, hash: str | bytes) -> bool: ...
30
+
31
+ def hash(self, password: str | bytes, *, salt: bytes | None = None) -> str: ...
32
+
33
+ def verify(self, password: str | bytes, hash: str | bytes) -> bool: ...
34
+
35
+ def check_needs_rehash(self, hash: str | bytes) -> bool: ...
36
+
37
+
38
+ __all__ = ["HasherProtocol", "ensure_str", "validate_str_or_bytes"]