diff --git a/.git_archival.txt b/.git_archival.txt new file mode 100644 index 0000000..7c51009 --- /dev/null +++ b/.git_archival.txt @@ -0,0 +1,3 @@ +node: $Format:%H$ +node-date: $Format:%cI$ +describe-name: $Format:%(describe:tags=true,match=*[0-9]*)$ diff --git a/.gitignore b/.gitignore index 95203bd..d449d2a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,16 @@ -*.dylib -*.egg-info *.pyc -*.so +.DS_Store .cache .coverage .coverage.* -.eggs +.direnv +.envrc .hypothesis +.mypy_cache .pytest_cache/ .tox +.vscode __pycache__ -_build dist -pip-wheel-metadata/ -src/argon2/_ffi.py +docs/_build/ +Justfile diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 33e9a32..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "libargon2"] - path = extras/libargon2 - url = https://github.com/p-h-c/phc-winner-argon2 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70af9ec..1955da9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,25 +1,30 @@ --- +ci: + autoupdate_schedule: monthly + repos: - - repo: https://github.com/psf/black - rev: 21.7b0 + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.11.12 hooks: - - id: black - language_version: python3.8 + - id: ruff-check + args: [--fix, --exit-non-zero-on-fix] + - id: ruff-format - - repo: https://github.com/PyCQA/isort - rev: 5.9.3 + - repo: https://github.com/econchick/interrogate + rev: 1.7.0 hooks: - - id: isort - additional_dependencies: [toml] + - id: interrogate + args: [tests] - - repo: https://github.com/PyCQA/flake8 - rev: 3.9.2 + - repo: https://github.com/codespell-project/codespell + rev: v2.4.1 hooks: - - id: flake8 + - id: codespell - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.0.1 + rev: v5.0.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - - id: debug-statements + - id: check-toml + - id: check-yaml diff --git a/.python-version-default b/.python-version-default new file mode 100644 index 0000000..24ee5b1 --- /dev/null +++ b/.python-version-default @@ -0,0 +1 @@ +3.13 diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..e08ea38 --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,20 @@ +--- +version: 2 + +build: + os: ubuntu-lts-latest + tools: + # Keep version in sync with tox.ini/docs. + python: "3.13" + jobs: + create_environment: + # Need the tags to calculate the version (sometimes). + - git fetch --tags + + - asdf plugin add uv + - asdf install uv latest + - asdf global uv latest + + build: + html: + - uvx --with tox-uv tox run -e docs-build -- $READTHEDOCS_OUTPUT diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index e73bd84..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,14 +0,0 @@ ---- -version: 2 -python: - # Keep version in sync with tox.ini (docs and gh-actions). - version: 3.7 - - install: - - method: pip - path: . - extra_requirements: - - docs - -submodules: - include: all diff --git a/AUTHORS.rst b/AUTHORS.rst deleted file mode 100644 index 35c08be..0000000 --- a/AUTHORS.rst +++ /dev/null @@ -1,30 +0,0 @@ -Credits & License -================= - -``argon2-cffi`` is maintained by Hynek Schlawack and released under the `MIT license `_. - -The development is kindly supported by `Variomedia AG `_. - -A full list of contributors can be found in GitHub's `overview `_. - - -Vendored Code -------------- - -Argon2 -^^^^^^ - -The original Argon2 repo can be found at https://github.com/P-H-C/phc-winner-argon2/. - -Except for the components listed below, the Argon2 code in this repository is copyright (c) 2015 Daniel Dinu, Dmitry Khovratovich (main authors), Jean-Philippe Aumasson and Samuel Neves, and under CC0_ license. - -The string encoding routines in src/encoding.c are copyright (c) 2015 Thomas Pornin, and under CC0_ license. - -The `BLAKE2 `_ code in ``src/blake2/`` is copyright (c) Samuel Neves, 2013-2015, and under CC0_ license. - -The authors of Argon2 also were very helpful to get the library to compile on ancient versions of Visual Studio for ancient versions of Python. - -The documentation also quotes frequently from the Argon2 paper_ to avoid mistakes by rephrasing. - -.. _CC0: https://creativecommons.org/publicdomain/zero/1.0/ -.. _paper: https://www.password-hashing.net/argon2-specs.pdf diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..59a5ddc --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,330 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Calendar Versioning](https://calver.org/). + +The **first number** of the version is the year. +The **second number** is incremented with each release, starting at 1 for each year. +The **third number** is when we need to start branches for older releases (only for emergencies). + +You can find our backwards-compatibility policy [here](https://github.com/hynek/argon2-cffi/blob/main/.github/SECURITY.md). + + + + +## [25.1.0](https://github.com/hynek/argon2-cffi/compare/23.1.0...25.1.0) - 2025-06-03 + +### Added + +- Official support for Python 3.13 and 3.14. + No code changes were necessary. + + +### Removed + +- Python 3.7 is not supported anymore. + [#186](https://github.com/hynek/argon2-cffi/pull/186) + + +### Changed + +- `argon2.PasswordHasher.check_needs_rehash()` now also accepts bytes like the rest of the API. + [#174](https://github.com/hynek/argon2-cffi/pull/174) + +- Improved parameter compatibility handling for Pyodide / WebAssembly environments. + [#190](https://github.com/hynek/argon2-cffi/pull/190) + + +## [23.1.0](https://github.com/hynek/argon2-cffi/compare/21.3.0...23.1.0) - 2023-08-15 + +### Removed + +- Python 3.6 is not supported anymore. + + +### Deprecated + +- The `InvalidHash` exception is deprecated in favor of `InvalidHashError`. + No plans for removal currently exist and the names can (but shouldn't) be used interchangeably. + +- `argon2.hash_password()`, `argon2.hash_password_raw()`, and `argon2.verify_password()` that have been soft-deprecated since 2016 are now hard-deprecated. + They now raise `DeprecationWarning`s and will be removed in 2024. + + +### Added + +- Official support for Python 3.11 and 3.12. + No code changes were necessary. + +- `argon2.exceptions.InvalidHashError` as a replacement for `InvalidHash`. + +- *salt* parameter to `argon2.PasswordHasher.hash()` to allow for custom salts. + This is only useful for specialized use-cases -- leave it on None unless you know exactly what you are doing. + [#153](https://github.com/hynek/argon2-cffi/pull/153) + + +## [21.3.0](https://github.com/hynek/argon2-cffi/compare/21.2.0...21.3.0) - 2021-12-11 + +### Fixed + +- While the last release added type hints, the fact that it's been missing a `py.typed` file made Mypy ignore them. + [#113](https://github.com/hynek/argon2-cffi/pull/113) + + +## [21.2.0](https://github.com/hynek/argon2-cffi/compare/21.1.0...21.2.0) - 2021-12-08 + +### Removed + +- Python 3.5 is not supported anymore. + +- The CFFI bindings have been extracted into a separate project: [*argon2-cffi-bindings*] + This makes *argon2-cffi* a Python-only project und should make it easier to contribute to and have more frequent releases with high-level features. + + This change is breaking for users who want to use a system-wide installation of Argon2 instead of our vendored code, because the argument to the ``--no-binary`` argument changed. + Please refer to the [installation guide](https://argon2-cffi.readthedocs.io/en/stable/installation.html). + + +### Added + +- Thanks to lots of work within [*argon2-cffi-bindings*], there're pre-compiled wheels for many new platforms. + Including: + - Apple Silicon via `universal2` + - Linux on `amd64` and `arm64` + - [*musl libc*](https://musl.libc.org) ([Alpine Linux!](https://www.alpinelinux.org)) on `i686`, `amd64`, and `arm64` + - PyPy 3.8 + + We hope to provide wheels for Windows on `arm64` soon, but are waiting for GitHub Actions to support that. + +- `argon2.Parameters.from_parameters()` together with the `argon2.profiles` module that offers easy access to the RFC-recommended configuration parameters and then some. + [#101](https://github.com/hynek/argon2-cffi/pull/101) + [#110](https://github.com/hynek/argon2-cffi/pull/110) + +- The CLI interface now has a `--profile` option that takes any name from `argon2.profiles`. + +- Types! + *argon2-cffi* is now fully typed. + [#112](https://github.com/hynek/argon2-cffi/pull/112) + + +### Changed + +- `argon2.PasswordHasher` now uses the RFC 9106 low-memory profile by default. + The old defaults are available as `argon2.profiles.PRE_21_2`. + + +## [21.1.0](https://github.com/hynek/argon2-cffi/compare/20.1.0...21.1.0) - 2021-08-29 + +Vendoring Argon2 @ [62358ba](https://github.com/P-H-C/phc-winner-argon2/tree/62358ba2123abd17fccf2a108a301d4b52c01a7c) (20190702) + +### Removed + +- Microsoft stopped providing the necessary SDKs to ship Python 2.7 wheels and currently the downloads amount to 0.09%. + Therefore we have decided that Python 2.7 is not supported anymore. + + +### Changed + +- There are indeed no changes whatsoever to the code of *argon2-cffi*. + The Argon2 project also hasn't tagged a new release since July 2019. + There also don't seem to be any important pending fixes. + + This release is mainly about improving the way binary wheels are built (`abi3` on all platforms). + + +## [20.1.0](https://github.com/hynek/argon2-cffi/compare/19.2.0...20.1.0) - 2020-05-11 + +Vendoring Argon2 @ [62358ba](https://github.com/P-H-C/phc-winner-argon2/tree/62358ba2123abd17fccf2a108a301d4b52c01a7c) (20190702) + + +### Added + +- It is now possible to manually override the detection of SSE2 using the `ARGON2_CFFI_USE_SSE2` environment variable. + + +## [19.2.0](https://github.com/hynek/argon2-cffi/compare/18.3.0...19.1.0) - 2019-10-27 + +Vendoring Argon2 @ [62358ba](https://github.com/P-H-C/phc-winner-argon2/tree/62358ba2123abd17fccf2a108a301d4b52c01a7c) (20190702) + +### Removed + +- Python 3.4 is not supported anymore. It has been unsupported by the Python core team for a while now and its PyPI downloads are negligible. + + It's very unlikely that *argon2-cffi* will break under 3.4 anytime soon, but we don't test it and don't ship binary wheels for it anymore. + +### Fixed + +- The dependency on `enum34` is now protected using a PEP 508 marker. + This fixes problems when the sdist is handled by a different interpreter version than the one running it. + [#48](https://github.com/hynek/argon2-cffi/issues/48) + + +## [19.1.0](https://github.com/hynek/argon2-cffi/compare/18.3.0...19.1.0) - 2019-01-17 + +Vendoring Argon2 @ [670229c](https://github.com/P-H-C/phc-winner-argon2/tree/670229c849b9fe882583688b74eb7dfdc846f9f6) (20171227) + +### Added + +- Added support for Argon2 v1.2 hashes in `argon2.extract_parameters()`. + + +## [18.3.0](https://github.com/hynek/argon2-cffi/compare/18.2.0...18.3.0) - 2018-08-19 + +Vendoring Argon2 @ [670229c](https://github.com/P-H-C/phc-winner-argon2/tree/670229c849b9fe882583688b74eb7dfdc846f9f6) (20171227) + +### Added + +- `argon2.PasswordHasher`'s hash type is configurable now. + + +## [18.2.0](https://github.com/hynek/argon2-cffi/compare/18.1.0...18.2.0) - 2018-08-19 + +Vendoring Argon2 @ [670229c](https://github.com/P-H-C/phc-winner-argon2/tree/670229c849b9fe882583688b74eb7dfdc846f9f6) (20171227) + +### Changed + +- The hash type for `argon2.PasswordHasher` is Argon2**id** now. + + This decision has been made based on the recommendations in the latest [Argon2 RFC draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-argon2-04#section-4). + [#33](https://github.com/hynek/argon2-cffi/issues/33) + [#34](https://github.com/hynek/argon2-cffi/pull/34) + +- Some of the hash parameters have been made stricter to be closer to said recommendations. + The current goal for a hash verification times is around 50ms. + [#41](https://github.com/hynek/argon2-cffi/pull/41) + +### Added + +- To make the change of hash type backward compatible, `argon2.PasswordHasher.verify()` now determines the type of the hash and verifies it accordingly. + +- To allow for bespoke decisions about upgrading Argon2 parameters, it's now possible to extract them from a hash via the `argon2.extract_parameters()` function. + [#41](https://github.com/hynek/argon2-cffi/pull/41) + +- Additionally `argon2.PasswordHasher` now has a `check_needs_rehash()` method that allows to verify whether a hash has been created with the instance's parameters or whether it should be rehashed. + [#41](https://github.com/hynek/argon2-cffi/pull/41) + + +## [18.1.0](https://github.com/hynek/argon2-cffi/compare/16.3.0...18.1.0) - 2018-01-06 + +Vendoring Argon2 @ [670229c](https://github.com/P-H-C/phc-winner-argon2/tree/670229c849b9fe882583688b74eb7dfdc846f9f6) (20171227) + +### Added + +- It is now possible to use the *argon2-cffi* bindings against an Argon2 library that is provided by the system. + + +## [16.3.0](https://github.com/hynek/argon2-cffi/compare/16.2.0...16.3.0) - 2016-11-10 + +Vendoring Argon2 @ [1c4fc41f81f358283755eea88d4ecd05e43b7fd3](https://github.com/P-H-C/phc-winner-argon2/tree/1c4fc41f81f358283755eea88d4ecd05e43b7fd3) (20161029) + +### Added + +- Add low-level bindings for Argon2id functions. + +### Fixed + +- Prevent side-effects like the installation of `cffi` if `setup.py` is called with a command that doesn't require it. + [#20](https://github.com/hynek/argon2-cffi/pull/20) +- Fix a bunch of warnings with new `cffi` versions and Python 3.6. + [#14](https://github.com/hynek/argon2-cffi/pull/14) + [#16](https://github.com/hynek/argon2-cffi/issues/16) + + +## [16.2.0](https://github.com/hynek/argon2-cffi/compare/16.1.0...16.2.0) - 2016-09-10 + +Vendoring Argon2 @ [4844d2fee15d44cb19296ddf36029326d17c5aa3](https://github.com/P-H-C/phc-winner-argon2/tree/4844d2fee15d44cb19296ddf36029326d17c5aa3) + +### Fixed + +- Fixed compilation on Debian 8 (Jessie). + [#13](https://github.com/hynek/argon2-cffi/pull/13) + + +## [16.1.0](https://github.com/hynek/argon2-cffi/compare/16.0.0...16.1.0) - 2016-04-19 + +Vendoring Argon2 @ [00aaa6604501fade85853a4b2f5695611ff6e7c5](https://github.com/P-H-C/phc-winner-argon2/tree/00aaa6604501fade85853a4b2f5695611ff6e7c5). + +### Added + + - Add `VerifyMismatchError` that is raised if verification fails only because of a password/hash mismatch. + It's a subclass of `VerificationError` therefore this change is completely backwards-compatible. + +### Changed + +- Add support for [Argon2 1.3](https://mailarchive.ietf.org/arch/msg/cfrg/beOzPh41Hz3cjl5QD7MSRNTi3lA/). + Old hashes remain functional but opportunistic rehashing is strongly recommended. + +### Removed + +- Python 3.3 and 2.6 aren't supported anymore. + They may work by chance but any support to them has been ceased. + + The last Python 2.6 release was on October 29, 2013 and isn't supported by the CPython core team anymore. + Major Python packages like Django and Twisted dropped Python 2.6 a while ago already. + + Python 3.3 never had a significant user base and wasn't part of any distribution's LTS release. + + +## [16.0.0](https://github.com/hynek/argon2-cffi/compare/15.0.1...16.0.0) - 2016-01-02 + +Vendoring Argon2 @ [421dafd2a8af5cbb215e16da5953663eb101d139](https://github.com/P-H-C/phc-winner-argon2/tree/421dafd2a8af5cbb215e16da5953663eb101d139). + +### Deprecated + +- `hash_password()`, `hash_password_raw()`, and `verify_password()` should not be used anymore. + For hashing passwords, use the new `argon2.PasswordHasher`. + If you want to implement your own higher-level abstractions, use the new low-level APIs `hash_secret()`, `hash_secret_raw()`, and `verify_secret()` from the `argon2.low_level` module. + If you want to go *really* low-level, `core()` is for you. + The old functions will *not* raise any warnings though and there are *no* immediate plans to remove them. + +### Added + +- Added `argon2.PasswordHasher`. + A higher-level class specifically for hashing passwords that also works on Unicode strings. +- Added `argon2.low_level` module with low-level API bindings for building own high-level abstractions. + + +## [15.0.1](https://github.com/hynek/argon2-cffi/compare/15.0.0...15.0.1) - 2015-12-18 + +Vendoring Argon2 @ [4fe0d8cda37691228dd5a96a310be57369403a4b](https://github.com/P-H-C/phc-winner-argon2/tree/4fe0d8cda37691228dd5a96a310be57369403a4b). + +### Fixed + +- Fix `long_description` on PyPI. + + +## [15.0.0](https://github.com/hynek/argon2-cffi/compare/15.0.0b5...15.0.0) - 2015-12-18 + +Vendoring Argon2 @ [4fe0d8cda37691228dd5a96a310be57369403a4b](https://github.com/P-H-C/phc-winner-argon2/tree/4fe0d8cda37691228dd5a96a310be57369403a4b). + +### Added + +- Conditionally use the [SSE2](https://en.wikipedia.org/wiki/SSE2)-optimized version of `argon2` on x86 architectures. + +### Changed + +- `verify_password()` doesn't guess the hash type if passed `None` anymore. + Supporting this resulted in measurable overhead (~0.6ms vs 0.8ms on my notebook) since it had to happen in Python. + That means that naïve usage of the API would give attackers an edge. + The new behavior is that it has the same default value as `hash_password()` such that `verify_password(hash_password(b"password"), b"password")` still works. +- Tweaked default parameters to more reasonable values. + Verification should take between 0.5ms and 1ms on recent-ish hardware. + +### Fixed + +- More packaging fixes. + Most notably compilation on Visual Studio 2010 for Python 3.3 and 3.4. + + +## [15.0.0b5](https://github.com/hynek/argon2-cffi/tree/15.0.0b5) - 2015-12-10 + +Vendoring Argon2 @ [4fe0d8cda37691228dd5a96a310be57369403a4b](https://github.com/P-H-C/phc-winner-argon2/tree/4fe0d8cda37691228dd5a96a310be57369403a4b). + +### Added + +- Initial work. + Previous betas were only for fixing Windows packaging. + The authors of Argon2 were kind enough to [help me](https://github.com/P-H-C/phc-winner-argon2/issues/44) to get it building under Visual Studio 2008 that we’re forced to use for Python 2.7 on Windows. + + +[*argon2-cffi-bindings*]: https://github.com/hynek/argon2-cffi-bindings diff --git a/CHANGELOG.rst b/CHANGELOG.rst deleted file mode 100644 index eff0f98..0000000 --- a/CHANGELOG.rst +++ /dev/null @@ -1,330 +0,0 @@ -Changelog -========= - -Versions are year-based with a strict backward compatibility policy. -The third digit is only for regressions. - - -21.1.0 (2021-08-29) -------------------- - -Vendoring Argon2 @ `62358ba `_ (20190702) - - -Backward-incompatible changes: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Microsoft stopped providing the necessary SDKs to ship Python 2.7 wheels and currenly the downloads amount to 0.09%. -Therefore we have decided that Python 2.7 is not supported anymore. - - -Deprecations: -^^^^^^^^^^^^^ - -*none* - - -Changes: -^^^^^^^^ - -There are indeed no changes whatsoever to the code of *argon2-cffi*. -The *Argon2* project also hasn't tagged a new release since July 2019. -There also don't seem to be any important pending fixes. - -This release is mainly about improving the way binary wheels are built (abi3 on all platforms). - - ----- - - -20.1.0 (2020-05-11) -------------------- - -Vendoring Argon2 @ `62358ba `_ (20190702) - - -Backward-incompatible changes: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -*none* - - -Deprecations: -^^^^^^^^^^^^^ - -*none* - - -Changes: -^^^^^^^^ - -- It is now possible to manually override the detection of SSE2 using the ``ARGON2_CFFI_USE_SSE2`` environment variable. - - ----- - - -19.2.0 (2019-10-27) -------------------- - -Vendoring Argon2 @ `62358ba `_ (20190702) - - -Backward-incompatible changes: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -- Python 3.4 is not supported anymore. - It has been unsupported by the Python core team for a while now and its PyPI downloads are negligible. - - It's very unlikely that ``argon2-cffi`` will break under 3.4 anytime soon, but we don't test it and don't ship binary wheels for it anymore. - - -Deprecations: -^^^^^^^^^^^^^ - -*none* - - -Changes: -^^^^^^^^ - -- The dependency on ``enum34`` is now protected using a PEP 508 marker. - This fixes problems when the sdist is handled by a different interpreter version than the one running it. - `#48 `_ - - ----- - - -19.1.0 (2019-01-17) -------------------- - -Vendoring Argon2 @ `670229c `_ (20171227) - - -Backward-incompatible changes: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -*none* - - -Deprecations: -^^^^^^^^^^^^^ - -*none* - - -Changes: -^^^^^^^^ - -- Added support for Argon2 v1.2 hashes in ``argon2.extract_parameters()``. - - ----- - - -18.3.0 (2018-08-19) -------------------- - -Vendoring Argon2 @ `670229c `_ (20171227) - - -Backward-incompatible changes: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -*none* - - -Deprecations: -^^^^^^^^^^^^^ - -*none* - - -Changes: -^^^^^^^^ - -- ``argon2.PasswordHasher``'s hash type is configurable now. - - ----- - - -18.2.0 (2018-08-19) -------------------- - -Vendoring Argon2 @ `670229c `_ (20171227) - - -Changes: -^^^^^^^^ - -- The hash type for ``argon2.PasswordHasher`` is Argon2\ **id** now. - - This decision has been made based on the recommendations in the latest `Argon2 RFC draft `_. - `#33 `_ - `#34 `_ -- To make the change of hash type backward compatible, ``argon2.PasswordHasher.verify()`` now determines the type of the hash and verifies it accordingly. -- Some of the hash parameters have been made stricter to be closer to said recommendations. - The current goal for a hash verification times is around 50ms. - `#41 `_ -- To allow for bespoke decisions about upgrading Argon2 parameters, it's now possible to extract them from a hash via the ``argon2.extract_parameters()`` function. - `#41 `_ -- Additionally ``argon2.PasswordHasher`` now has a ``check_needs_rehash()`` method that allows to verify whether a hash has been created with the instance's parameters or whether it should be rehashed. - `#41 `_ - - ----- - - -18.1.0 (2018-01-06) -------------------- - -Vendoring Argon2 @ `670229c `_ (20171227) - - -Changes: -^^^^^^^^ - -- It is now possible to use the ``argon2-cffi`` bindings against an Argon2 library that is provided by the system. - - ----- - - -16.3.0 (2016-11-10) -------------------- - -Vendoring Argon2 @ `1c4fc41f81f358283755eea88d4ecd05e43b7fd3 `_ (20161029) - -Changes: -^^^^^^^^ - -- Prevent side-effects like the installation of ``cffi`` if ``setup.py`` is called with a command that doesn't require it. - `#20 `_ -- Fix a bunch of warnings with new ``cffi`` versions and Python 3.6. - `#14 `_ - `#16 `_ -- Add low-level bindings for Argon2id functions. - - ----- - - -16.2.0 (2016-09-10) -------------------- - -Vendoring Argon2 @ `4844d2fee15d44cb19296ddf36029326d17c5aa3 `_ - -Changes: -^^^^^^^^ - -- Fix compilation on debian jessie. - `#13 `_ - - ----- - - -16.1.0 (2016-04-19) -------------------- - -Vendoring Argon2 @ 00aaa6604501fade85853a4b2f5695611ff6e7c5_. - -Backward-incompatible changes: -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -- Python 3.3 and 2.6 aren't supported anymore. - They may work by chance but any support to them has been ceased. - - The last Python 2.6 release was on October 29, 2013 and isn't supported by the CPython core team anymore. - Major Python packages like Django and Twisted dropped Python 2.6 a while ago already. - - Python 3.3 never had a significant user base and wasn't part of any distribution's LTS release. - -Changes: -^^^^^^^^ - -- Add ``VerifyMismatchError`` that is raised if verification fails only because of a password/hash mismatch. - It's a subclass of ``VerificationError`` therefore this change is completely backward compatible. -- Add support for `Argon2 1.3 `_. - Old hashes remain functional but opportunistic rehashing is strongly recommended. - - ----- - - -16.0.0 (2016-01-02) -------------------- - -Vendoring Argon2 @ 421dafd2a8af5cbb215e16da5953663eb101d139_. - -Deprecations: -^^^^^^^^^^^^^ - -- ``hash_password()``, ``hash_password_raw()``, and ``verify_password()`` should not be used anymore. - For hashing passwords, use the new ``argon2.PasswordHasher``. - If you want to implement your own higher-level abstractions, use the new low-level APIs ``hash_secret()``, ``hash_secret_raw()``, and ``verify_secret()`` from the ``argon2.low_level`` module. - If you want to go *really* low-level, ``core()`` is for you. - The old functions will *not* raise any warnings though and there are *no* immediate plans to remove them. - -Changes: -^^^^^^^^ - -- Add ``argon2.PasswordHasher``. - A higher-level class specifically for hashing passwords that also works on Unicode strings. -- Add ``argon2.low_level`` module with low-level API bindings for building own high-level abstractions. - - ----- - - -15.0.1 (2015-12-18) -------------------- - -Vendoring Argon2 @ 4fe0d8cda37691228dd5a96a310be57369403a4b_. - -Changes: -^^^^^^^^ - -- Fix ``long_description`` on PyPI. - - ----- - - -15.0.0 (2015-12-18) -------------------- - -Vendoring Argon2 @ 4fe0d8cda37691228dd5a96a310be57369403a4b_. - -Changes: -^^^^^^^^ - -- ``verify_password()`` doesn't guess the hash type if passed ``None`` anymore. - Supporting this resulted in measurable overhead (~ 0.6ms vs 0.8ms on my notebook) since it had to happen in Python. - That means that naïve usage of the API would give attackers an edge. - The new behavior is that it has the same default value as ``hash_password()`` such that ``verify_password(hash_password(b"password"), b"password")`` still works. -- Conditionally use the `SSE2 `_-optimized version of ``argon2`` on x86 architectures. -- More packaging fixes. - Most notably compilation on Visual Studio 2010 for Python 3.3 and 3.4. -- Tweaked default parameters to more reasonable values. - Verification should take between 0.5ms and 1ms on recent-ish hardware. - - ----- - - -15.0.0b5 (2015-12-10) ---------------------- - -Vendoring Argon2 @ 4fe0d8cda37691228dd5a96a310be57369403a4b_. - -Initial work. -Previous betas were only for fixing Windows packaging. -The authors of Argon2 were kind enough to `help me `_ to get it building under Visual Studio 2008 that we’re forced to use for Python 2.7 on Windows. - - -.. _421dafd2a8af5cbb215e16da5953663eb101d139: https://github.com/P-H-C/phc-winner-argon2/tree/421dafd2a8af5cbb215e16da5953663eb101d139 -.. _4fe0d8cda37691228dd5a96a310be57369403a4b: https://github.com/P-H-C/phc-winner-argon2/tree/4fe0d8cda37691228dd5a96a310be57369403a4b -.. _00aaa6604501fade85853a4b2f5695611ff6e7c5: https://github.com/P-H-C/phc-winner-argon2/tree/00aaa6604501fade85853a4b2f5695611ff6e7c5 diff --git a/FAQ.md b/FAQ.md new file mode 100644 index 0000000..bcbcb55 --- /dev/null +++ b/FAQ.md @@ -0,0 +1,27 @@ +# Frequently Asked Questions + +## I'm using *bcrypt* / *PBKDF2* / *scrypt* / *yescrypt*, do I need to migrate? + +Using password hashes that aren't memory hard carries a certain risk but there's **no immediate danger or need for action**. +If however you are deciding how to hash password *today*, Argon2 is the superior, future-proof choice. + +But if you already use one of the hashes mentioned in the question, you should be fine for the foreseeable future. +If you're using *scrypt* or *yescrypt*, you will be probably fine for good. + + +## Why do the `verify()` methods raise an Exception instead of returning `False`? + +1. The Argon2 library had no concept of a "wrong password" error in the beginning. + Therefore when writing these bindings, an exception with the full error had to be raised so you could inspect what went actually wrong. + + Changing that now would be a very dangerous break of backwards-compatibility. + +2. In my opinion, a wrong password should raise an exception such that it can't pass unnoticed by accident. + See also The Zen of Python: "Errors should never pass silently." + +3. It's more [Pythonic](https://docs.python.org/3/glossary.html#term-EAFP). + + +## Does *argon2-cffi* release the GIL? + +[Yes](https://cffi.readthedocs.io/en/latest/ref.html#conversions). diff --git a/FAQ.rst b/FAQ.rst deleted file mode 100644 index 7c8d669..0000000 --- a/FAQ.rst +++ /dev/null @@ -1,18 +0,0 @@ -Frequently Asked Questions -========================== - -I'm using ``bcrypt``/``PBKDF2``/``scrypt``/``yescrypt``, do I need to migrate? - Using password hashes that aren't memory hard carries a certain risk but there's **no immediate danger or need for action**. - If however you are deciding how to hash password *today*, Argon2 is the superior, future-proof choice. - - But if you already use one of the hashes mentioned in the question, you should be fine for the foreseeable future. - If you're using ``scrypt`` or ``yescrypt``, you will be probably fine for good. - -Why do the ``verify()`` methods raise an Exception instead of returning ``False``? - #. The Argon2 library had no concept of a "wrong password" error in the beginning. - Therefore when writing these bindings, an exception with the full error had to be raised so you could inspect what went actually wrong. - - It goes without saying that it's impossible to switch now for backward-compatibility reasons. - #. In my opinion, a wrong password should raise an exception such that it can't pass unnoticed by accident. - See also The Zen of Python: "Errors should never pass silently." - #. It's more `Pythonic `_. diff --git a/LICENSE b/LICENSE index 7ae3df9..d1b626b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2015 Hynek Schlawack +Copyright (c) 2015 Hynek Schlawack and the argon2-cffi contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/MANIFEST.in b/MANIFEST.in deleted file mode 100644 index b2f1bc2..0000000 --- a/MANIFEST.in +++ /dev/null @@ -1,9 +0,0 @@ -include *.rst *.md *.txt *.ini .coveragerc LICENSE .pre-commit-config.yaml pyproject.toml -exclude src/argon2/_ffi.py .gitmodules extras/libargon2/.git *.yml -graft tests -graft .github -graft .azure-pipelines -recursive-exclude tests *.pyc -graft extras -graft docs -prune docs/_build diff --git a/README.md b/README.md new file mode 100644 index 0000000..fea54cf --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +# *argon2-cffi*: Argon2 for Python + +[![Documentation](https://img.shields.io/badge/Docs-Read%20The%20Docs-black)](https://argon2-cffi.readthedocs.io/) +[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/6671/badge)](https://bestpractices.coreinfrastructure.org/projects/6671) +[![PyPI version](https://img.shields.io/pypi/v/argon2-cffi)](https://pypi.org/project/argon2-cffi/) +[![Downloads / Month](https://static.pepy.tech/personalized-badge/argon2-cffi?period=month&units=international_system&left_color=grey&right_color=blue&left_text=Downloads%20/%20Month)](https://pepy.tech/project/argon2-cffi) + + + + +[Argon2](https://github.com/p-h-c/phc-winner-argon2) won the [Password Hashing Competition](https://www.password-hashing.net/) and *argon2-cffi* is the simplest way to use it in Python: + +```pycon +>>> from argon2 import PasswordHasher +>>> ph = PasswordHasher() +>>> hash = ph.hash("correct horse battery staple") +>>> hash # doctest: +SKIP +'$argon2id$v=19$m=65536,t=3,p=4$MIIRqgvgQbgj220jfp0MPA$YfwJSVjtjSU0zzV/P3S9nnQ/USre2wvJMjfCIjrTQbg' +>>> ph.verify(hash, "correct horse battery staple") +True +>>> ph.check_needs_rehash(hash) +False +>>> ph.verify(hash, "Tr0ub4dor&3") +Traceback (most recent call last): + ... +argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash + +``` + + +## Project Links + +- [**PyPI**](https://pypi.org/project/argon2-cffi/) +- [**GitHub**](https://github.com/hynek/argon2-cffi) +- [**Documentation**](https://argon2-cffi.readthedocs.io/) +- [**Changelog**](https://github.com/hynek/argon2-cffi/blob/main/CHANGELOG.md) +- [**Funding**](https://hynek.me/say-thanks/) +- The low-level Argon2 CFFI bindings are maintained in the separate [*argon2-cffi-bindings*](https://github.com/hynek/argon2-cffi-bindings) project. + + + +## Credits + +*argon2-cffi* is maintained by [Hynek Schlawack](https://hynek.me/). + +The development is kindly supported by my employer [Variomedia AG](https://www.variomedia.de/), *argon2-cffi* [Tidelift subscribers](https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek), and my amazing [GitHub Sponsors](https://github.com/sponsors/hynek). + + +## *argon2-cffi* for Enterprise + +Available as part of the [Tidelift Subscription](https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek). + +The maintainers of *argon2-cffi* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open-source packages you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. diff --git a/README.rst b/README.rst deleted file mode 100644 index a2099bd..0000000 --- a/README.rst +++ /dev/null @@ -1,55 +0,0 @@ -================= -Argon2 for Python -================= - -.. image:: https://img.shields.io/badge/Docs-Read%20The%20Docs-black - :target: https://argon2-cffi.readthedocs.io/ - :alt: Documentation - -.. image:: https://img.shields.io/badge/license-MIT-C06524 - :target: https://github.com/hynek/argon2-cffi/blob/main/LICENSE - :alt: License: MIT - -.. image:: https://img.shields.io/pypi/v/argon2-cffi - :target: https://pypi.org/project/argon2-cffi/ - :alt: PyPI version - -.. image:: https://static.pepy.tech/personalized-badge/argon2-cffi?period=month&units=international_system&left_color=grey&right_color=blue&left_text=Downloads%20/%20Month - :target: https://pepy.tech/project/argon2-cffi - :alt: Downloads / Month - - -.. teaser-begin - -`Argon2 `_ won the `Password Hashing Competition `_ and *argon2-cffi* is the simplest way to use it in Python and PyPy: - -.. code-block:: pycon - - >>> from argon2 import PasswordHasher - >>> ph = PasswordHasher() - >>> hash = ph.hash("s3kr3tp4ssw0rd") - >>> hash # doctest: +SKIP - '$argon2id$v=19$m=102400,t=2,p=8$tSm+JOWigOgPZx/g44K5fQ$WDyus6py50bVFIPkjA28lQ' - >>> ph.verify(hash, "s3kr3tp4ssw0rd") - True - >>> ph.check_needs_rehash(hash) - False - >>> ph.verify(hash, "t0t411ywr0ng") - Traceback (most recent call last): - ... - argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash - - -*argon2-cffi*'s documentation lives at `Read the Docs `_, the code on `GitHub `_. -It’s rigorously tested on Python 3.5+, and PyPy3. - -It implements *Argon2* version 1.3, as described in -`Argon2: the memory-hard function for password hashing and other applications `_. - - -argon2-cffi for Enterprise -========================== - -Available as part of the Tidelift Subscription. - -The maintainers of *argon2-cffi* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. `Learn more. `_ diff --git a/SECURITY.md b/SECURITY.md deleted file mode 100644 index d10a387..0000000 --- a/SECURITY.md +++ /dev/null @@ -1,12 +0,0 @@ -# Security Policy - -## Supported Versions - -We are following [CalVer](https://calver.org) with generous backward-compatibility guarantees. Therefore we only support the latest version. - - -## Reporting a Vulnerability - -If you think you found a Vulnerability, please contact Hynek Schlawack at . - -If you insist on using PGP, you can use the key `0xAE2536227F69F181`. The fingerprint must be `C2A0 4F86 ACE2 8ADC F817 DBB7 AE25 3622 7F69 F181`. You can also find it on [Keybase](https://keybase.io/hynek). diff --git a/codecov.yml b/codecov.yml deleted file mode 100644 index 60a1e5c..0000000 --- a/codecov.yml +++ /dev/null @@ -1,10 +0,0 @@ ---- -comment: false -coverage: - status: - patch: - default: - target: "100" - project: - default: - target: "100" diff --git a/debian/changelog b/debian/changelog index 4ae0f58..9551ce5 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,48 @@ +python-argon2 (25.1.0-2) unstable; urgency=medium + + * Team upload. + * Upstream stopped signing tags with GPG after 23.1.0. + * d/watch: disabled GPG-key verification (Closes: #1111266). + * d/upstream/signing-key.asc: removed obsolete GPG key. + + -- Carl Keinath Mon, 18 Aug 2025 00:14:46 +0200 + +python-argon2 (25.1.0-1) unstable; urgency=medium + + * Team upload. + * New upstream release 25.1.0. + * d/watch: + + Tags do not use prefix 'v' anymore. + * Drop support for python <= 3.7. + * Added CI/CD config. + * Fix FTBFS (Closes: #1048524). + + -- Carl Keinath Sun, 03 Aug 2025 12:15:03 +0200 + +python-argon2 (23.1.0-1) experimental; urgency=medium + + * Team upload. + * New upstream release 23.1.0. + * d/control: + + Bump Standards-Version to 4.7.2. + + Switched to dh-sequence-python3. + + Migrate from setuptools to hatchling (upstream change). + + Drop unnecessary shlibs dependency. + * d/watch: + + Set mode to git. + + Update upstream signing key (minified export version). + * Port patch for generic Sphinx theme. + * d/rules: Remove obsolete overrides. + + -- Carl Keinath Sun, 06 Apr 2025 17:03:34 +0200 + +python-argon2 (21.1.0-3) unstable; urgency=medium + + * Team upload. + * Port to Sphinx 8.0 (closes: #1090133). + + -- Colin Watson Tue, 24 Dec 2024 18:39:04 +0000 + python-argon2 (21.1.0-2) unstable; urgency=medium * Team Upload. diff --git a/debian/control b/debian/control index 9a8edec..58f79ed 100644 --- a/debian/control +++ b/debian/control @@ -4,23 +4,31 @@ Uploaders: Nicolas Dandrimont Section: python Priority: optional Build-Depends: debhelper-compat (= 13), - dh-python, - libargon2-dev, - python3-all-dev, - python3-cffi, + dh-sequence-python3, + python3-all, + pybuild-plugin-pyproject, + python3-hatchling, + python3-hatch-vcs, + python3-hatch-fancy-pypi-readme, + python3-argon2-cffi-bindings, + python3-typing-extensions, python3-hypothesis, python3-pytest, - python3-setuptools, - python3-sphinx -Standards-Version: 4.6.0 + python3-mypy, + python3-sphinx, + python3-sphinx-notfound-page, + python3-sphinx-copybutton, + python3-myst-parser, +Standards-Version: 4.7.2 Rules-Requires-Root: no +Testsuite: autopkgtest-pkg-python Homepage: https://argon2-cffi.readthedocs.io/ Vcs-Git: https://salsa.debian.org/python-team/packages/python-argon2.git Vcs-Browser: https://salsa.debian.org/python-team/packages/python-argon2 Package: python3-argon2 Architecture: any -Depends: ${misc:Depends}, ${python3:Depends}, ${shlibs:Depends} +Depends: ${misc:Depends}, ${python3:Depends} Suggests: python-argon2-doc (= ${source:Version}) Description: Argon2 password hashing library - Python 3.x Module Argon2 is a password-hashing function that can be used to hash passwords diff --git a/debian/patches/0001-Use-generic-sphinx-theme-for-documentation.patch b/debian/patches/0001-Use-generic-sphinx-theme-for-documentation.patch deleted file mode 100644 index b269382..0000000 --- a/debian/patches/0001-Use-generic-sphinx-theme-for-documentation.patch +++ /dev/null @@ -1,21 +0,0 @@ -From: Gordon Ball -Date: Sun, 10 Oct 2021 18:10:09 +0000 -Subject: Use generic sphinx theme for documentation - ---- - docs/conf.py | 2 +- - 1 file changed, 1 insertion(+), 1 deletion(-) - -diff --git a/docs/conf.py b/docs/conf.py -index fc4f0db..47cc689 100644 ---- a/docs/conf.py -+++ b/docs/conf.py -@@ -130,7 +130,7 @@ exclude_patterns = ["_build"] - # The theme to use for HTML and HTML Help pages. See the documentation for - # a list of builtin themes. - --html_theme = "furo" -+# html_theme = "furo" - - # Theme options are theme-specific and customize the look and feel of a theme - # further. For a list of options available for each theme, see the diff --git a/debian/patches/0001-use-generic-sphinx-theme.patch b/debian/patches/0001-use-generic-sphinx-theme.patch new file mode 100644 index 0000000..2a357bd --- /dev/null +++ b/debian/patches/0001-use-generic-sphinx-theme.patch @@ -0,0 +1,38 @@ +From: Carl Keinath +Date: Sun, 3 Aug 2025 12:24:56 +0200 +Subject: use-generic-sphinx-theme +Forwarded: not-needed + +--- + docs/conf.py | 18 +++++++++--------- + 1 file changed, 9 insertions(+), 9 deletions(-) + +diff --git a/docs/conf.py b/docs/conf.py +index 7da440f..f28b864 100644 +--- a/docs/conf.py ++++ b/docs/conf.py +@@ -65,15 +65,15 @@ add_function_parentheses = True + + # -- Options for HTML output ---------------------------------------------- + +-html_theme = "furo" +-html_theme_options = { +- "top_of_page_buttons": [], +- "light_css_variables": { +- "font-stack": "Inter,sans-serif", +- "font-stack--monospace": "BerkeleyMono, MonoLisa, ui-monospace, " +- "SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace", +- }, +-} ++# html_theme = "furo" ++# html_theme_options = { ++# "top_of_page_buttons": [], ++# "light_css_variables": { ++# "font-stack": "Inter,sans-serif", ++# "font-stack--monospace": "BerkeleyMono, MonoLisa, ui-monospace, " ++# "SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace", ++# }, ++# } + html_static_path = ["_static"] + html_css_files = ["custom.css"] + diff --git a/debian/patches/0002-do-not-build-external-clib.patch b/debian/patches/0002-do-not-build-external-clib.patch deleted file mode 100644 index 62b213a..0000000 --- a/debian/patches/0002-do-not-build-external-clib.patch +++ /dev/null @@ -1,16 +0,0 @@ -Description: Do not try to build external libs when it is specified to use system argon2 lib -Author: Nilesh Patra -Forwarded: not-needed. Upstream split the package into cffi bindings and a pure python package and - also switched their build system to flit. So forwarding is it un-necessary. -Bug-Debian: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=1020022 -Last-Update: 2022-10-13 ---- a/setup.py -+++ b/setup.py -@@ -193,6 +193,7 @@ - ) - if use_system_argon2: - disable_subcommand(build, "build_clib") -+ LIBRARIES = [] - cmdclass = {"build_clib": BuildCLibWithCompilerFlags} - if BDistWheel is not None: - cmdclass["bdist_wheel"] = BDistWheel diff --git a/debian/patches/series b/debian/patches/series index 7a05ef6..e39c609 100644 --- a/debian/patches/series +++ b/debian/patches/series @@ -1,2 +1 @@ -0001-Use-generic-sphinx-theme-for-documentation.patch -0002-do-not-build-external-clib.patch +0001-use-generic-sphinx-theme.patch diff --git a/debian/python-argon2-doc.doc-base b/debian/python-argon2-doc.doc-base new file mode 100644 index 0000000..08a98c1 --- /dev/null +++ b/debian/python-argon2-doc.doc-base @@ -0,0 +1,12 @@ +Document: python-argon2-doc +Title: Argon2 password hashing for Python +Author: Hynek Schlawack +Abstract: This documentation describes python-argon2, a library for secure password + hashing in Python using the Argon2 algorithm. It provides an easy-to-use interface + and secure defaults based on the Argon2id variant, standardized in RFC 9106. +Section: Programming/Python + +Format: HTML +Index: /usr/share/doc/python-argon2-doc/html/index.html +Files: /usr/share/doc/python-argon2-doc/html/*.html + diff --git a/debian/python3-argon2.install b/debian/python3-argon2.install deleted file mode 100644 index fef6392..0000000 --- a/debian/python3-argon2.install +++ /dev/null @@ -1 +0,0 @@ -/usr/lib/python3* diff --git a/debian/rules b/debian/rules index 2c90ca2..c5d96f2 100755 --- a/debian/rules +++ b/debian/rules @@ -2,22 +2,18 @@ export DEB_BUILD_MAINT_OPTIONS = hardening=+all -export ARGON2_CFFI_USE_SYSTEM = 1 +export PYBUILD_NAME = argon2 %: - dh $@ --with python3,sphinxdoc --buildsystem=pybuild + dh $@ --with sphinxdoc --buildsystem=pybuild override_dh_auto_clean: dh_auto_clean rm -rf $(CURDIR)/debian/hypothesis + rm -rf docs/_build override_dh_auto_build: dh_auto_build ifeq (,$(filter nodoc,$(DEB_BUILD_OPTIONS))) PYTHONPATH=`pybuild --print build_dir --interpreter python3` $(MAKE) -C docs html endif - -override_dh_python3: - dh_python3 - # Remove extra cffi bindings, identical to the default version - rm -rf debian/python3-argon2/usr/lib/python3.? diff --git a/debian/salsa-ci.yml b/debian/salsa-ci.yml new file mode 100644 index 0000000..8424db4 --- /dev/null +++ b/debian/salsa-ci.yml @@ -0,0 +1,3 @@ +--- +include: + - https://salsa.debian.org/salsa-ci-team/pipeline/raw/master/recipes/debian.yml diff --git a/debian/upstream/signing-key.asc b/debian/upstream/signing-key.asc deleted file mode 100644 index be5b7b4..0000000 --- a/debian/upstream/signing-key.asc +++ /dev/null @@ -1,282 +0,0 @@ ------BEGIN PGP PUBLIC KEY BLOCK----- - -mQINBFKUg9MBEADDu4GmD3ftC71sws/Ic/sbCzPb4L2Ts+PZFmS1JNm2vl0QkPJY -xt2pRCBj7Iw7U+BPrDjuZbqMZfiRB1Pw06zzLvVeroQ6SdYkeK6bMarQOyB+UNin -AYR6D4axWgqjsOFRNogjOk4sFaC6ugWjKkKJIuuXl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3dn8AaVdWBy4fxBi8haDIseMCwOQOlZZ -oUE9zcrKfs0dnIMatcS9NHqW0uaUwl2uImkv2+xk/dVPNiOFNlPdgGM/2PNfoS47 -19ZKNWYUfmpEyglSR9OvLtHo8MdI6WyRrBm07xc/sZgnox9228u8JnzZQ2XFVnO5 -20iNdU/1YzQ3/gdOycDlOK/w8UL9km2tCHwzwkpDQwtNAeY3NvoOlQKboUfJuNM9 -L3f3evMbxBzyF0a0zHyYfBH5QlHbReU6xQw/OBCwtzjcJtjYkuHhyop/CTKOpGNN -cxt+/YAFb9WVpqxqbGxC00JJEIHNvK/N9fe5DWC/8fKssfsQkiAz7RpRAcXUcpUj -2JLQJ63PIWu5wEgtOObHRUhcV0/rtoEOneLZVeFu5zNEc8eBihtQdj/ZDXnRWKEi -e7MY3orZUTjDLO7TmRw63lIXD08xfZWiDc0YoDGp7gmzFZxJzw8MBz/EwAuMpEbF -Qzpk5EX8r9spVkYI0clrV3os+SWc0gcMABQorLiccG3hj7Yae9Exq0Y22EQEz0po -ezyrSRNb/RKIub6zcadBjH083ai1zum+AsfAnTjrbaiw4IjIO62eHX2FTDBOpaHP -mHpnsCGTwxu58YMunFasHIS1gDGV5peZZLNahaKTll683RWxcQ== -=dRxp ------END PGP PUBLIC KEY BLOCK----- diff --git a/debian/watch b/debian/watch index 5d8789a..ff1be7c 100644 --- a/debian/watch +++ b/debian/watch @@ -1,2 +1,4 @@ version=4 -https://github.com/hynek/argon2-cffi/tags .*/@ANY_VERSION@@ARCHIVE_EXT@ +opts="mode=git,pgpmode=none" \ + https://github.com/hynek/argon2-cffi.git \ + refs/tags/@ANY_VERSION@ diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..72083fe --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,10 @@ +@import url('https://rsms.me/inter/inter.css'); +@import url('https://assets.hynek.me/css/bm.css'); + + +:root { + font-feature-settings: 'liga' 1, 'calt' 1; /* fix for Chrome */ +} +@supports (font-variation-settings: normal) { + :root { font-family: InterVariable, sans-serif; } +} diff --git a/docs/api.rst b/docs/api.rst index 2ab944f..e6a7e2d 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -3,56 +3,86 @@ API Reference .. module:: argon2 -``argon2-cffi`` comes with an high-level API and hopefully reasonable defaults for Argon2 parameters that result in a verification time of 40--50ms on recent-ish hardware. +.. autoclass:: PasswordHasher + :members: from_parameters, hash, verify, check_needs_rehash -.. warning:: +If you don't specify any parameters, the following constants are used: - The current memory requirement is set to rather conservative 100 MB. - However, in memory constrained environments like Docker containers that can lead to problems. - One possible non-obvious symptom are apparent freezes that are caused by swapping. +.. data:: DEFAULT_RANDOM_SALT_LENGTH +.. data:: DEFAULT_HASH_LENGTH +.. data:: DEFAULT_TIME_COST +.. data:: DEFAULT_MEMORY_COST +.. data:: DEFAULT_PARALLELISM - Please check :doc:`parameters` for more details. +They are taken from :data:`argon2.profiles.RFC_9106_LOW_MEMORY`, but they may vary depending on the platform. +You can use :func:`argon2.profiles.get_default_parameters` to get the current platform's defaults. -Unless you have any special needs, all you need to know is: -.. doctest:: +Profiles +-------- - >>> from argon2 import PasswordHasher - >>> ph = PasswordHasher() - >>> hash = ph.hash("s3kr3tp4ssw0rd") - >>> hash # doctest: +SKIP - '$argon2id$v=19$m=102400,t=2,p=8$tSm+JOWigOgPZx/g44K5fQ$WDyus6py50bVFIPkjA28lQ' - >>> ph.verify(hash, "s3kr3tp4ssw0rd") - True - >>> ph.check_needs_rehash(hash) - False - >>> ph.verify(hash, "t0t411ywr0ng") - Traceback (most recent call last): - ... - argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash +.. automodule:: argon2.profiles -A login function could thus look like this: +You can try them out using the :doc:`cli` interface. +For example: -.. literalinclude:: login_example.py - :language: python +.. code-block:: console ----- + $ python -m argon2 --profile RFC_9106_HIGH_MEMORY + Running Argon2id 100 times with: + hash_len: 32 bytes + memory_cost: 2097152 KiB + parallelism: 4 threads + time_cost: 1 iterations -While the :class:`PasswordHasher` class has the aspiration to be good to use out of the box, it has all the parametrization you'll need: + Measuring... -.. autoclass:: PasswordHasher - :members: hash, verify, check_needs_rehash + 866.5ms per password verification -If you don't specify any parameters, the following constants are used: +That should give you a feeling on how they perform in *your* environment. -.. data:: DEFAULT_RANDOM_SALT_LENGTH -.. data:: DEFAULT_HASH_LENGTH -.. data:: DEFAULT_TIME_COST -.. data:: DEFAULT_MEMORY_COST -.. data:: DEFAULT_PARALLELISM +.. data:: RFC_9106_HIGH_MEMORY + + Called "FIRST RECOMMENDED option" by `RFC 9106`_. + + Requires beefy 2 GiB, so be careful in memory-contrained systems. + + .. versionadded:: 21.2.0 + +.. data:: RFC_9106_LOW_MEMORY + + Called "SECOND RECOMMENDED option" by `RFC 9106`_. + + The main difference is that it only takes 64 MiB of RAM. + + The values from this profile are the default parameters used by :class:`argon2.PasswordHasher`. + + .. versionadded:: 21.2.0 + +.. data:: PRE_21_2 -You can see their values in :class:`PasswordHasher`. + The default values that *argon2-cffi* used from 18.2.0 until 21.2.0. + + Needs 100 MiB of RAM. + + .. versionadded:: 21.2.0 + +.. data:: CHEAPEST + + This is the cheapest-possible profile. + + .. warning:: + + This is only for testing purposes! + Do **not** use in production! + + .. versionadded:: 21.2.0 + + +.. autofunction:: argon2.profiles.get_default_parameters + +.. _`RFC 9106`: https://www.rfc-editor.org/rfc/rfc9106.html Exceptions @@ -64,16 +94,20 @@ Exceptions .. autoexception:: argon2.exceptions.HashingError +.. autoexception:: argon2.exceptions.InvalidHashError + .. autoexception:: argon2.exceptions.InvalidHash +.. autoexception:: argon2.exceptions.UnsupportedParametersError + + Utilities --------- +.. autofunction:: argon2.extract_parameters -.. autofunction:: extract_parameters - -.. autoclass:: Parameters +.. autoclass:: argon2.Parameters Low Level @@ -81,8 +115,23 @@ Low Level .. automodule:: argon2.low_level -.. autoclass:: Type - :members: D, I, ID +.. autoclass:: Type() + + .. attribute:: D + + Argon2\ **d** is faster and uses data-depending memory access. + That makes it less suitable for hashing secrets and more suitable for cryptocurrencies and applications with no threats from side-channel timing attacks. + + .. attribute:: I + + Argon2\ **i** uses data-independent memory access. + Argon2i is slower as it makes more passes over the memory to protect from tradeoff attacks. + + .. attribute:: ID + + Argon2\ **id** is a hybrid of Argon2i and Argon2d, using a combination of data-depending and data-independent memory accesses, which gives some of Argon2i's resistance to side-channel cache timing attacks and much of Argon2d's resistance to GPU cracking attacks. + + .. versionadded:: 16.3.0 .. autodata:: ARGON2_VERSION @@ -117,43 +166,65 @@ The super low-level ``argon2_core()`` function is exposed too if you need access .. autofunction:: core -In order to use :func:`core`, you need access to ``argon2-cffi``'s FFI objects. -Therefore it is OK to use ``argon2.low_level.ffi`` and ``argon2.low_level.lib`` when working with it: +In order to use :func:`core`, you need access to *argon2-cffi*'s FFI objects. +Therefore, it is OK to use ``argon2.low_level.ffi`` and ``argon2.low_level.lib`` when working with it. +For example, if you wanted to check the :rfc:`9106` test vectors for Argon2id that include a secret and associated data that both get mixed into the hash and aren't exposed by the high-level APIs: .. doctest:: - >>> from argon2.low_level import ARGON2_VERSION, Type, core, ffi, lib - >>> pwd = b"secret" - >>> salt = b"12345678" - >>> hash_len = 8 - >>> # Make sure you keep FFI objects alive until *after* the core call! - >>> cout = ffi.new("uint8_t[]", hash_len) - >>> cpwd = ffi.new("uint8_t[]", pwd) - >>> csalt = ffi.new("uint8_t[]", salt) - >>> ctx = ffi.new( - ... "argon2_context *", dict( - ... version=ARGON2_VERSION, - ... out=cout, outlen=hash_len, - ... pwd=cpwd, pwdlen=len(pwd), - ... salt=csalt, saltlen=len(salt), - ... secret=ffi.NULL, secretlen=0, - ... ad=ffi.NULL, adlen=0, - ... t_cost=1, - ... m_cost=8, - ... lanes=1, threads=1, - ... allocate_cbk=ffi.NULL, free_cbk=ffi.NULL, - ... flags=lib.ARGON2_DEFAULT_FLAGS, + >>> from argon2.low_level import Type, core, ffi, lib + + >>> def low_level_hash( + ... password, salt, secret, associated, + ... hash_len, version, t_cost, m_cost, lanes, threads): + ... cout = ffi.new("uint8_t[]", hash_len) + ... cpwd = ffi.new("uint8_t[]", password) + ... cad = ffi.new("uint8_t[]", associated) + ... csalt = ffi.new("uint8_t[]", salt) + ... csecret = ffi.new("uint8_t[]", secret) + ... + ... ctx = ffi.new( + ... "argon2_context *", + ... { + ... "out": cout, + ... "outlen": hash_len, + ... "version": version, + ... "pwd": cpwd, + ... "pwdlen": len(cpwd) - 1, + ... "salt": csalt, + ... "saltlen": len(csalt) - 1, + ... "secret": csecret, + ... "secretlen": len(csecret) - 1, + ... "ad": cad, + ... "adlen": len(cad) - 1, + ... "t_cost": t_cost, + ... "m_cost": m_cost, + ... "lanes": lanes, + ... "threads": threads, + ... "allocate_cbk": ffi.NULL, + ... "free_cbk": ffi.NULL, + ... "flags": lib.ARGON2_DEFAULT_FLAGS, + ... }, + ... ) + ... + ... assert lib.ARGON2_OK == core(ctx, Type.ID.value) + ... + ... return bytes(ffi.buffer(ctx.out, ctx.outlen)).hex() + + >>> password = bytes.fromhex( + ... "0101010101010101010101010101010101010101010101010101010101010101" + ... ) + >>> associated = bytes.fromhex("040404040404040404040404") + >>> salt = bytes.fromhex("02020202020202020202020202020202") + >>> secret = bytes.fromhex("0303030303030303") + + >>> assert ( + ... "0d640df58d78766c08c037a34a8b53c9d01ef0452d75b65eb52520e96b01e659" + ... == low_level_hash( + ... password, salt, secret, associated, + ... 32, 19, 3, 32, 4, 4, ... ) ... ) - >>> ctx - - >>> core(ctx, Type.D.value) - 0 - >>> out = bytes(ffi.buffer(ctx.out, ctx.outlen)) - >>> out - b'\xb4\xe2HjO\x14d\x9b' - >>> out == argon2.low_level.hash_secret_raw(pwd, salt, 1, 8, 1, 8, Type.D) - True All constants and types on ``argon2.low_level.lib`` are guaranteed to stay as long they are not altered by Argon2 itself. @@ -163,11 +234,11 @@ All constants and types on ``argon2.low_level.lib`` are guaranteed to stay as lo Deprecated APIs --------------- -These APIs are from the first release of ``argon2-cffi`` and proved to live in an unfortunate mid-level. +These APIs are from the first release of *argon2-cffi* and proved to live in an unfortunate mid-level. On one hand they have defaults and check parameters but on the other hand they only consume byte strings. Therefore the decision has been made to replace them by a high-level (:class:`argon2.PasswordHasher`) and a low-level (:mod:`argon2.low_level`) solution. -There are no immediate plans to remove them though. +They will be removed in 2024. .. autofunction:: argon2.hash_password .. autofunction:: argon2.hash_password_raw diff --git a/docs/argon2.md b/docs/argon2.md new file mode 100644 index 0000000..1ee3e76 --- /dev/null +++ b/docs/argon2.md @@ -0,0 +1,61 @@ +# What is Argon2? + +:::{note} +**TL;DR**: Use {class}`argon2.PasswordHasher` with its default parameters to securely hash your passwords. + +You do **not** need to read or understand anything below this box. +::: + +Argon2 is a secure password hashing algorithm. +It is designed to have both a configurable runtime as well as memory consumption. + +This means that you can decide how long it takes to hash a password and how much memory is required. + +In September 2021, Argon2 has been standardized by the IETF in {rfc}`9106`. + +Argon2 comes in three variants: Argon2**d**, Argon2**i**, and Argon2**id**. +Argon2**d**'s strength is the resistance against [time–memory trade-offs], while Argon2**i**'s focus is on resistance against [side-channel attacks]. + +Accordingly, Argon2**i** was originally considered the correct choice for password hashing and password-based key derivation. +In practice it turned out that a *combination* of d and i -- that combines their strengths -- is the better choice. +And so Argon2**id** was born and is now considered the *main variant* -- and the only variant required by the RFC to be implemented. + + +## Why “just use bcrypt” Is Not the Best Answer (Anymore) + +The current workhorses of password hashing are unquestionably [*bcrypt*] and [PBKDF2]. +And while they're still fine to use, the password cracking community embraced new technologies like [GPU]s and [ASIC]s to crack password in a highly parallel fashion. + +An effective measure against extreme parallelism proved making computation of password hashes also *memory* hard. +The best known implementation of that approach is to date [*scrypt*]. +However according to the [Argon2 paper] [^outdated], page 2: + +> \[…\] the existence of a trivial time-memory tradeoff allows compact implementations with the same energy cost. + +Therefore a new algorithm was needed. +This time future-proof and with committee-vetting instead of single implementers. + +[^outdated]: Please note that the paper is in some parts outdated. + For instance it predates the genesis of Argon2**id**. + Generally please refer to {rfc}`9106` instead. + + +## Password Hashing Competition + +The [Password Hashing Competition] took place between 2012 and 2015 to find a new, secure, and future-proof password hashing algorithm. +Previously the NIST was in charge but after certain events and [revelations] their integrity has been put into question by the general public. +So a group of independent cryptographers and security researchers came together. + +In the end, Argon2 was [announced] as the winner. + +[announced]: https://groups.google.com/forum/#!topic/crypto-competitions/3QNdmwBS98o +[argon2 paper]: https://www.password-hashing.net/argon2-specs.pdf +[asic]: https://en.wikipedia.org/wiki/Application-specific_integrated_circuit +[*bcrypt*]: https://en.wikipedia.org/wiki/Bcrypt +[gpu]: https://hashcat.net/hashcat/ +[password hashing competition]: https://www.password-hashing.net/ +[pbkdf2]: https://en.wikipedia.org/wiki/PBKDF2 +[revelations]: https://en.wikipedia.org/wiki/Dual_EC_DRBG +[*scrypt*]: https://en.wikipedia.org/wiki/Scrypt +[side-channel attacks]: https://en.wikipedia.org/wiki/Side-channel_attack +[time–memory trade-offs]: https://en.wikipedia.org/wiki/Space–time_tradeoff diff --git a/docs/argon2.rst b/docs/argon2.rst deleted file mode 100644 index 3ab3b37..0000000 --- a/docs/argon2.rst +++ /dev/null @@ -1,62 +0,0 @@ -Argon2 -====== - -.. note:: - - **TL;DR**: Use :class:`argon2.PasswordHasher` with its default parameters to securely hash your passwords. - - You do **not** need to read or understand anything below this box. - -Argon2 is a secure password hashing algorithm. -It is designed to have both a configurable runtime as well as memory consumption. - -This means that you can decide how long it takes to hash a password and how much memory is required. - -Argon2 comes in three variants: - -Argon2d - is faster and uses data-depending memory access, which makes it less suitable for hashing secrets and more suitable for cryptocurrencies and applications with no threats from side-channel timing attacks. - -Argon2i - uses data-independent memory access, which is preferred for password hashing and password-based key derivation. - Argon2i is slower as it makes more passes over the memory to protect from tradeoff attacks. - -Argon2id - is a hybrid of Argon2i and Argon2d, using a combination of data-depending and data-independent memory accesses, which gives some of Argon2i's resistance to side-channel cache timing attacks and much of Argon2d's resistance to GPU cracking attacks. - - -Why “just use bcrypt” Is Not the Best Answer (Anymore) ------------------------------------------------------- - -The current workhorses of password hashing are unquestionably bcrypt_ and PBKDF2_. -And while they're still fine to use, the password cracking community embraced new technologies like GPU_\ s and ASIC_\ s to crack password in a highly parallel fashion. - -An effective measure against extreme parallelism proved making computation of password hashes also *memory* hard. -The best known implementation of that approach is to date scrypt_. -However according to the `Argon2 paper`_, page 2: - - […] the existence of a trivial time-memory tradeoff allows compact implementations with the same energy cost. - -Therefore a new algorithm was needed. -This time future-proof and with committee-vetting instead of single implementors. - -.. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt -.. _PBKDF2: https://en.wikipedia.org/wiki/PBKDF2 -.. _GPU: https://hashcat.net/hashcat/ -.. _ASIC: https://en.wikipedia.org/wiki/Application-specific_integrated_circuit -.. _scrypt: https://en.wikipedia.org/wiki/Scrypt -.. _Argon2 paper: https://www.password-hashing.net/argon2-specs.pdf - - -Password Hashing Competition ----------------------------- - -The `Password Hashing Competition`_ took place between 2012 and 2015 to find a new, secure, and future-proof password hashing algorithm. -Previously the NIST was in charge but after certain events and revelations_ their integrity has been put into question by the general public. -So a group of independent cryptographers and security researchers came together. - -In the end, Argon2 was announced_ as the winner. - -.. _Password Hashing Competition: https://www.password-hashing.net/ -.. _revelations: https://en.wikipedia.org/wiki/Dual_EC_DRBG -.. _announced: https://groups.google.com/forum/#!topic/crypto-competitions/3QNdmwBS98o diff --git a/docs/backward-compatibility.rst b/docs/backward-compatibility.rst deleted file mode 100644 index acf7a12..0000000 --- a/docs/backward-compatibility.rst +++ /dev/null @@ -1,15 +0,0 @@ -Backward Compatibility -====================== - -``argon2-cffi`` has a very strong backward compatibility policy. -Generally speaking, you shouldn't ever be afraid of updating. - -If breaking changes are needed do be done, they are: - -#. …announced in the changelog_. -#. …the old behavior raises a :exc:`DeprecationWarning` for a year. -#. …are done with another announcement in the changelog_. - -What explicitly *may* change over time are the default hashing parameters and the behavior of the :doc:`cli`. - -.. _changelog: https://argon2-cffi.readthedocs.io/en/stable/changelog.html diff --git a/docs/changelog.rst b/docs/changelog.rst deleted file mode 100644 index 565b052..0000000 --- a/docs/changelog.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../CHANGELOG.rst diff --git a/docs/cli.md b/docs/cli.md new file mode 100644 index 0000000..536d59d --- /dev/null +++ b/docs/cli.md @@ -0,0 +1,24 @@ +# CLI + +To aid you with finding the parameters, *argon2-cffi* offers a CLI interface that can be accessed using `python -m argon2`. +It will benchmark Argon2's password *verification* in the current environment: + +```console +$ python -m argon2 +Running Argon2id 100 times with: +hash_len: 32 bytes +memory_cost: 65536 KiB +parallelism: 4 threads +time_cost: 3 iterations + +Measuring... + +45.7ms per password verification +``` + +You can use command line arguments to set hashing parameters. +Either by setting them one by one (`-t` for time, `-m` for memory, `-p` for parallelism, `-l` for hash length), or by passing `--profile` followed by one of the names from {mod}`argon2.profiles`. +In that case, the other parameters are ignored. +If you don't pass any arguments as above, it runs with {class}`argon2.PasswordHasher`'s default values. + +This should make it much easier to determine the right parameters for your use case and your environment. diff --git a/docs/cli.rst b/docs/cli.rst deleted file mode 100644 index 1a60941..0000000 --- a/docs/cli.rst +++ /dev/null @@ -1,21 +0,0 @@ -CLI -=== - -To aid you with finding the parameters, ``argon2-cffi`` offers a CLI interface that can be accessed using ``python -m argon2``. -It will benchmark Argon2’s password *verification* in the current environment. -You can use command line arguments to set hashing parameters: - -.. code-block:: text - - $ python -m argon2 - Running Argon2id 100 times with: - hash_len: 16 bytes - memory_cost: 102400 KiB - parallelism: 8 threads - time_cost: 2 iterations - - Measuring... - - 45.3ms per password verification - -This should make it much easier to determine the right parameters for your use case and your environment. diff --git a/docs/conf.py b/docs/conf.py index fc4f0db..7da440f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,227 +1,86 @@ -# -# argon2-cffi documentation build configuration file, created by -# sphinx-quickstart on Sun May 11 16:17:15 2014. -# -# This file is execfile()d with the current directory set to its -# containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. +# SPDX-License-Identifier: MIT -import codecs -import datetime -import os -import re +from importlib import metadata -def read(*parts): - """ - Build an absolute path from *parts* and and return the contents of the - resulting file. Assume UTF-8 encoding. - """ - here = os.path.abspath(os.path.dirname(__file__)) - with codecs.open(os.path.join(here, *parts), "rb", "utf-8") as f: - return f.read() - - -def find_version(*file_paths): - """ - Build a path from *file_paths* and search for a ``__version__`` - string inside. - """ - version_file = read(*file_paths) - version_match = re.search( - r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M - ) - if version_match: - return version_match.group(1) - raise RuntimeError("Unable to find version string.") - - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# sys.path.insert(0, os.path.abspath('.')) - -# -- General configuration ------------------------------------------------ - -# If your documentation needs a minimal Sphinx version, state it here. -# needs_sphinx = '1.0' - # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ + "myst_parser", + "notfound.extension", "sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx", "sphinx.ext.todo", + "sphinx.ext.napoleon", + "sphinx_copybutton", ] +myst_enable_extensions = ["deflist", "colon_fence"] + # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix of source filenames. source_suffix = ".rst" -# The encoding of source files. -# source_encoding = 'utf-8-sig' - # The master toctree document. master_doc = "index" # General information about the project. project = "argon2-cffi" -year = datetime.date.today().year copyright = "2015, Hynek Schlawack" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # -# The short X.Y version. -release = find_version("..", "src", "argon2", "__init__.py") -version = release.rsplit(".", 1)[0] # The full version, including alpha/beta/rc tags. +if "dev" in (release := metadata.version("argon2-cffi")): + release = version = "UNRELEASED" +else: + # The short X.Y version. + version = release.rsplit(".", 1)[0] -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# language = None +# Move type hints into the description block, instead of the func definition. +autodoc_typehints = "description" +autodoc_typehints_description_target = "documented" -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -# today = '' -# Else, today_fmt is used as the format for a strftime call. -# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] +# nitpick_ignore = [] + # The reST default role (used for this markup: `text`) to use for all # documents. -# default_role = None +default_role = "any" # If true, '()' will be appended to :func: etc. cross-reference text. -# add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -# add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -# show_authors = False - - -# A list of ignored prefixes for module index sorting. -# modindex_common_prefix = [] - -# If true, keep warnings as "system message" paragraphs in the built documents. -# keep_warnings = False +add_function_parentheses = True # -- Options for HTML output ---------------------------------------------- -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. - html_theme = "furo" - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -# html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -# html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -# html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -# html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -# html_static_path = ['_static'] - -# Add any extra paths that contain custom files (such as robots.txt or -# .htaccess) here, relative to this directory. These files are copied -# directly to the root of the documentation. -# html_extra_path = [] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -# html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -# html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -# html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -# html_additional_pages = {} - -# If false, no module index is generated. -# html_domain_indices = True - -# If false, no index is generated. -# html_use_index = True - -# If true, the index is split into individual pages for each letter. -# html_split_index = False - -# If true, links to the reST sources are added to the pages. -# html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -# html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -# html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -# html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -# html_file_suffix = None +html_theme_options = { + "top_of_page_buttons": [], + "light_css_variables": { + "font-stack": "Inter,sans-serif", + "font-stack--monospace": "BerkeleyMono, MonoLisa, ui-monospace, " + "SFMono-Regular, Menlo, Consolas, Liberation Mono, monospace", + }, +} +html_static_path = ["_static"] +html_css_files = ["custom.css"] # Output file base name for HTML help builder. htmlhelp_basename = "argon2-cffidoc" -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # 'preamble': '', -} - # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). @@ -235,27 +94,6 @@ def find_version(*file_paths): ) ] -# The name of an image file (relative to this directory) to place at the top of -# the title page. -# latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -# latex_use_parts = False - -# If true, show page references after internal links. -# latex_show_pagerefs = False - -# If true, show URL addresses after external links. -# latex_show_urls = False - -# Documents to append as an appendix to all manuals. -# latex_appendices = [] - -# If false, no module index is generated. -# latex_domain_indices = True - - # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples @@ -270,9 +108,6 @@ def find_version(*file_paths): ) ] -# If true, show URL addresses after external links. -# man_show_urls = False - # -- Options for Texinfo output ------------------------------------------- @@ -286,23 +121,10 @@ def find_version(*file_paths): "argon2-cffi Documentation", "Hynek Schlawack", "argon2-cffi", - "One line description of project.", + "Argon2 for Python", "Miscellaneous", ) ] -# Documents to append as an appendix to all manuals. -# texinfo_appendices = [] - -# If false, no module index is generated. -# texinfo_domain_indices = True - -# How to display URL addresses: 'footnote', 'no', or 'inline'. -# texinfo_show_urls = 'footnote' - -# If true, do not generate a @detailmenu in the "Top" node's menu. -# texinfo_no_detailmenu = False - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/3": None} +intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} diff --git a/docs/contributing.rst b/docs/contributing.rst deleted file mode 100644 index 8fbb03c..0000000 --- a/docs/contributing.rst +++ /dev/null @@ -1,3 +0,0 @@ -.. _contributing: - -.. include:: ../.github/CONTRIBUTING.rst diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..0659233 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,2 @@ +```{include} ../FAQ.md +``` diff --git a/docs/faq.rst b/docs/faq.rst deleted file mode 100644 index 6a3b77b..0000000 --- a/docs/faq.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../FAQ.rst diff --git a/docs/howto.md b/docs/howto.md new file mode 100644 index 0000000..ec9aac2 --- /dev/null +++ b/docs/howto.md @@ -0,0 +1,38 @@ +# How to Hash a Password + +*argon2-cffi* comes with an high-level API and uses the officially recommended low-memory Argon2 parameters that result in a verification time of 40--50ms on recent-ish hardware. + +:::{warning} +The current memory requirement is set to rather conservative 64 MB. +However, in memory constrained environments such as Docker containers that can lead to problems. +One possible non-obvious symptom are apparent freezes that are caused by swapping. + +Please check {doc}`parameters` for more details. +::: + +Unless you have any special requirements, all you need to know is: + +```python +>>> from argon2 import PasswordHasher +>>> ph = PasswordHasher() +>>> hash = ph.hash("correct horse battery staple") +>>> hash # doctest: +SKIP +'$argon2id$v=19$m=65536,t=3,p=4$MIIRqgvgQbgj220jfp0MPA$YfwJSVjtjSU0zzV/P3S9nnQ/USre2wvJMjfCIjrTQbg' +>>> ph.verify(hash, "correct horse battery staple") +True +>>> ph.check_needs_rehash(hash) +False +>>> ph.verify(hash, "Tr0ub4dor&3") +Traceback (most recent call last): +... +argon2.exceptions.VerifyMismatchError: The password does not match the supplied hash +``` + +A login function could thus look like this: + +```{literalinclude} login_example.py +``` + +--- + +While the {class}`argon2.PasswordHasher` class has the aspiration to be good to use out of the box, it has all the parametrization you'll need. diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..5f033df --- /dev/null +++ b/docs/index.md @@ -0,0 +1,44 @@ +# *argon2-cffi*: Argon2 for Python + +Release **{sub-ref}`release`** ([What's new?](https://github.com/hynek/argon2-cffi/blob/main/CHANGELOG.md)) + +```{include} ../README.md +:end-before: +:start-after: +``` + +If you don't know where to start, learn {doc}`argon2` and take it from there! + + +## Indices and Tables + +- {doc}`api` +- {ref}`genindex` +- {ref}`search` + + +```{toctree} +:hidden: +:maxdepth: 1 + +argon2 +installation +howto +api +parameters +cli +faq +``` + + +```{toctree} +:hidden: +:caption: Meta + +PyPI +GitHub +Changelog +Contributing +Security Policy +Funding +``` diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index ee39b48..0000000 --- a/docs/index.rst +++ /dev/null @@ -1,41 +0,0 @@ -``argon2-cffi`` -=============== - -Release v\ |release| (:doc:`What's new? `). - - -.. include:: ../README.rst - :start-after: teaser-begin - - -User's Guide ------------- - -.. toctree:: - :maxdepth: 1 - - argon2 - installation - api - parameters - cli - faq - - -Project Information -------------------- - -.. toctree:: - :maxdepth: 1 - - backward-compatibility - contributing - changelog - license - - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`search` diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..89c5862 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,78 @@ +# Installation + +## Using a Vendored Argon2 + +```console +$ python -Im pip install argon2-cffi +``` + +should be all it takes. + +But since *argon2-cffi* depends on [argon2-cffi-bindings] that vendors Argon2's C code by default, it can lead to complications depending on the platform. + +The C code is known to compile and work on all common platforms (including x86, ARM, and PPC). +On x86, an [SSE2]-optimized version is used. + +If something goes wrong, please try to update your *pip* package first: + +```console +$ python -Im pip install -U pip +``` + +Overall this should be the safest bet because *argon2-cffi* has been specifically tested against the vendored version. + + +### Wheels + +Binary [wheels](https://pythonwheels.com) for macOS, Windows, and Linux are provided on [PyPI] by [argon2-cffi-bindings]. +With a recent-enough *pip* they should be used automatically. + + +### Source Distribution + +A working C compiler and [CFFI environment] are required to build the [argon2-cffi-bindings] dependency. +If you've been able to compile Python CFFI extensions before, *argon2-cffi* should install without any problems. + + +## Using a System-wide Installation of Argon2 + +If you set `ARGON2_CFFI_USE_SYSTEM` to `1` (and *only* `1`), *argon2-cffi-bindings* will not build its bindings. +However binary wheels are preferred by *pip* and Argon2 gets installed along with *argon2-cffi* anyway. + +Therefore you also have to instruct *pip* to use a source distribution of [argon2-cffi-bindings]: + +```console +$ env ARGON2_CFFI_USE_SYSTEM=1 \ + python -m pip install --no-binary=argon2-cffi-bindings argon2-cffi +``` + +This approach can lead to problems around your build chain and you can run into incompatibilities between Argon2 and *argon2-cffi* if the latter has been tested against a different version. + +**It is your own responsibility to deal with these risks if you choose this path.** + +:::{versionadded} 18.1.0 +::: + +:::{versionchanged} 21.2.0 +The `--no-binary` option value changed due to the outsourcing of the binary bindings. +::: + + +## Override Automatic SSE2 Detection + +Usually the build process tries to guess whether or not it should use [SSE2]-optimized code. +Despite our best efforts, this can go wrong. + +Therefore you can use the `ARGON2_CFFI_USE_SSE2` environment variable to control the process: + +- If you set it to `1`, *argon2-cffi* will build **with** SSE2 support. +- If you set it to `0`, *argon2-cffi* will build **without** SSE2 support. +- If you set it to anything else, it will be ignored and *argon2-cffi* will try to guess. + +:::{versionadded} 20.1.0 +::: + +[argon2-cffi-bindings]: https://github.com/hynek/argon2-cffi-bindings +[cffi environment]: https://cffi.readthedocs.io/en/latest/installation.html +[pypi]: https://pypi.org/project/argon2-cffi-bindings/ +[sse2]: https://en.wikipedia.org/wiki/SSE2 diff --git a/docs/installation.rst b/docs/installation.rst deleted file mode 100644 index 587994e..0000000 --- a/docs/installation.rst +++ /dev/null @@ -1,79 +0,0 @@ -Installation -============ - -Using the Vendored Argon2 -------------------------- - -.. code-block:: bash - - python -m pip install argon2-cffi - -should be all it takes. - -But since ``argon2-cffi`` vendors Argon2's C code by default, it can lead to complications depending on the platform. - -The C code is known to compile and work on all common platforms (including x86, ARM, and PPC). -On x86, an SSE2_-optimized version is used. - -If something goes wrong, please try to update your ``cffi``, ``pip`` and ``setuptools`` first: - -.. code-block:: bash - - python -m pip install -U cffi pip setuptools - - -Overall this should be the safest bet because ``argon2-cffi`` has been specifically tested against the vendored version. - - -Wheels -^^^^^^ - -Binary `wheels `_ for macOS, Windows, and Linux are provided on PyPI_. -With a recent-enough ``pip`` and ``setuptools``, they should be used automatically. - - -Source Distribution -^^^^^^^^^^^^^^^^^^^ - -A working C compiler and `CFFI environment`_ are required. -If you've been able to compile Python CFFI extensions before, ``argon2-cffi`` should install without any problems. - - -Using a System-wide Installation of Argon2 ------------------------------------------- - -If you set ``ARGON2_CFFI_USE_SYSTEM`` to ``1`` (and *only* ``1``), ``argon2-cffi`` will not build its bindings. -However binary wheels are preferred by ``pip`` and Argon2 gets installed along with ``argon2-cffi`` anyway. - -Therefore you also have to instruct ``pip`` to use a source distribution: - -.. code-block:: bash - - env ARGON2_CFFI_USE_SYSTEM=1 \ - python -m pip install --no-binary=argon2-cffi argon2-cffi - -This approach can lead to problems around your build chain and you can run into incompatibilities between Argon2 and ``argon2-cffi`` if the latter has been tested against a different version. - -**It is your own responsibility to deal with these risks if you choose this path.** - -Available since version 18.1.0. - - -Override Automatic SSE2 Detection ---------------------------------- - -Usually the build process tries to guess whether or not it should use SSE2_-optimized code. -This can go wrong and is problematic for cross-compiling. - -Therefore you can use the ``ARGON2_CFFI_USE_SSE2`` environment variable to control the process: - -- If you set it to ``1``, ``argon2-cffi`` will build **with** SSE2 support. -- If you set it to ``0``, ``argon2-cffi`` will build **without** SSE2 support. -- If you set it to anything else, it will be ignored and ``argon2-cffi`` will try to guess. - -Available since version 20.1.0. - - -.. _SSE2: https://en.wikipedia.org/wiki/SSE2 -.. _PyPI: https://pypi.org/project/argon2-cffi/ -.. _CFFI environment: https://cffi.readthedocs.io/en/latest/installation.html diff --git a/docs/license.rst b/docs/license.rst deleted file mode 100644 index e122f91..0000000 --- a/docs/license.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../AUTHORS.rst diff --git a/docs/parameters.md b/docs/parameters.md new file mode 100644 index 0000000..03952bb --- /dev/null +++ b/docs/parameters.md @@ -0,0 +1,54 @@ +# Choosing Parameters + +:::{note} +You can probably just use {class}`argon2.PasswordHasher` with its default values and be fine. +But it's good to double check using *argon2-cffi*'s {doc}`cli` client, whether its defaults are too slow or too fast for your use case. +::: + +Finding the right parameters for a password hashing algorithm is a daunting task. +As of September 2021, we have the official Internet standard [RFC 9106] to help us with it. + +It comes with two recommendations in [section 4](https://www.rfc-editor.org/rfc/rfc9106.html#section-4), that (as of *argon2-cffi* 21.2.0) you can load directly from the {mod}`argon2.profiles` module: {data}`argon2.profiles.RFC_9106_HIGH_MEMORY` (called "FIRST RECOMMENDED") and {data}`argon2.profiles.RFC_9106_LOW_MEMORY` ("SECOND RECOMMENDED") into {meth}`argon2.PasswordHasher.from_parameters()`. + +Please use the {doc}`cli` interface together with its `--profile` argument to see if they work for you. + +--- + +If you need finer tuning, the current recommended best practice is as follow: + +1. Choose whether you want Argon2i, Argon2d, or Argon2id (`type`). + If you don't know what that means, choose Argon2id ({attr}`argon2.low_level.Type.ID`). + +2. Figure out how many threads can be used on each call to Argon2 (`parallelism`, called "lanes" in the RFC). + They recommend 4 threads. + +3. Figure out how much memory each call can afford (`memory_cost`). + The APIs use [Kibibytes] (1024 bytes) as base unit. + +4. Select the salt length. + 16 bytes is sufficient for all applications, but can be reduced to 8 bytes in the case of space constraints. + +5. Choose a hash length (`hash_len`, called "tag length" in the documentation). + 16 bytes is sufficient for password verification. + +6. Figure out how long each call can take. + One [recommendation](https://web.archive.org/web/20160304024620/https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2015/march/enough-with-the-salts-updates-on-secure-password-schemes/) for concurrent user logins is to keep it under 0.5 ms. + The RFC used to recommend under 500 ms. + The truth is somewhere between those two values: more is more secure, less is a better user experience. + *argon2-cffi*'s current defaults land with ~50ms somewhere in the middle, but the actual time depends on your hardware. + + Please note though, that even a verification time of 1 second won't protect you against bad passwords from the "top 10,000 passwords" lists that you can find online. + +7. Measure the time for hashing using your chosen parameters. + Start with `time_cost=1` and measure the time it takes. + Raise `time_cost` until it is within your accounted time. + If `time_cost=1` takes too long, lower `memory_cost`. + +*argon2-cffi*'s {doc}`cli` will help you with this process. + +:::{note} +Alternatively, you can also refer to the [OWASP cheatsheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#argon2id). +::: + +[kibibytes]: https://en.wikipedia.org/wiki/Kibibyte +[rfc 9106]: https://www.rfc-editor.org/rfc/rfc9106.html diff --git a/docs/parameters.rst b/docs/parameters.rst deleted file mode 100644 index 5038b39..0000000 --- a/docs/parameters.rst +++ /dev/null @@ -1,45 +0,0 @@ -Choosing Parameters -=================== - -.. note:: - - You can probably just use :class:`argon2.PasswordHasher` with its default values and be fine. - But it's good to double check using ``argon2-cffi``'s :doc:`cli` client, whether its defaults are too slow or too fast for your use case. - -Finding the right parameters for a password hashing algorithm is a daunting task. -The authors of Argon2 specified a method in their `paper `_, however some parts of it have been revised in the `RFC draft`_ for Argon2 that is currently being written. - -The current recommended best practice is as follow: - -#. Choose whether you want Argon2i, Argon2d, or Argon2id (``type``). - If you don't know what that means, choose Argon2id (:attr:`argon2.Type.ID`). -#. Figure out how many threads can be used on each call to Argon2 (``parallelism``, called "lanes" in the RFC). - They recommend twice as many as the number of cores dedicated to hashing passwords. - :class:`~argon2.PasswordHasher` will *not* determine this for you and use a default value that you can find in the linked API docs. -#. Figure out how much memory each call can afford (``memory_cost``). - The RFC recommends 4 GB for backend authentication and 1 GB for frontend authentication. - The APIs use Kibibytes_ (1024 bytes) as base unit. -#. Select the salt length. - 16 bytes is sufficient for all applications, but can be reduced to 8 bytes in the case of space constraints. -#. Choose a hash length (``hash_len``, called "tag length" in the documentation). - 16 bytes is sufficient for password verification. -#. Figure out how long each call can take. - One `recommendation `_ for concurent user logins is to keep it under 0.5 ms. - The RFC recommends under 500 ms. - The truth is somewhere between those two values: more is more secure, less is a better user experience. - ``argon2-cffi``'s defaults try to land somewhere in the middle and aim for ~50ms, but the actual time depends on your hardware. - - Please note though, that even a verification time of 1 second won't protect you against bad passwords from the "top 10,000 passwords" lists that you can find online. -#. Measure the time for hashing using your chosen parameters. - Find a ``time_cost`` that is within your accounted time. - If ``time_cost=1`` takes too long, lower ``memory_cost``. - -``argon2-cffi``'s :doc:`cli` will help you with this process. - - -.. note:: - Alternatively, you can also refer to the `OWASP cheatsheet `_. - - -.. _`RFC draft`: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-argon2-13#section-4 -.. _kibibytes: https://en.wikipedia.org/wiki/Kibibyte diff --git a/pyproject.toml b/pyproject.toml index 43893cf..f569729 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,15 +1,109 @@ +# SPDX-License-Identifier: MIT + [build-system] -requires = ["setuptools>=40.6.0", "wheel", "cffi>=1.0"] -build-backend = "setuptools.build_meta" +requires = ["hatchling", "hatch-vcs", "hatch-fancy-pypi-readme"] +build-backend = "hatchling.build" + + +[tool.hatch.build.targets.wheel] +packages = ["src/argon2"] + + +[project] +name = "argon2-cffi" +description = "Argon2 for Python" +authors = [{ name = "Hynek Schlawack", email = "hs@ox.cx" }] +dynamic = ["version", "readme"] +requires-python = ">=3.8" +license = "MIT" +license-files = ["LICENSE"] +keywords = ["password", "hash", "hashing", "security"] +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Operating System :: MacOS :: MacOS X", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: Implementation :: CPython", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Security :: Cryptography", + "Typing :: Typed", +] +dependencies = ["argon2-cffi-bindings"] + +[dependency-groups] +tests = ["hypothesis", "pytest"] +typing = ["mypy"] +docs = [ + "sphinx", + "sphinx-notfound-page", + "sphinx-copybutton", + "furo", + "myst-parser", +] +dev = [{ include-group = "tests" }, { include-group = "typing" }, "tox>4"] + +[project.urls] +Documentation = "https://argon2-cffi.readthedocs.io/" +Changelog = "https://github.com/hynek/argon2-cffi/blob/main/CHANGELOG.md" +GitHub = "https://github.com/hynek/argon2-cffi" +Funding = "https://github.com/sponsors/hynek" +Tidelift = "https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek" + + +[tool.hatch.version] +source = "vcs" +raw-options = { local_scheme = "no-local-version" } + + +[tool.hatch.metadata.hooks.fancy-pypi-readme] +content-type = "text/markdown" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +text = "# *argon2-cffi*: Argon2 for Python\n\n" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +path = "README.md" +start-after = "\n" +end-before = "\n" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +text = """ + +## Release Information + +""" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +path = "CHANGELOG.md" +start-after = "" +pattern = "\n(###.+?\n)## " + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +text = """ +--- + +[Full Changelog →](https://github.com/hynek/argon2-cffi/blob/main/CHANGELOG.md) + + +""" + +[[tool.hatch.metadata.hooks.fancy-pypi-readme.fragments]] +path = "README.md" +start-at = "## Credits" [tool.pytest.ini_options] -addopts = "-ra --strict-markers --capture=no" +addopts = ["-ra", "--strict-markers", "--strict-config"] xfail_strict = true testpaths = "tests" -filterwarnings = [ - "once::Warning", -] +filterwarnings = ["once::Warning"] [tool.coverage.run] @@ -18,16 +112,98 @@ branch = true source = ["argon2"] [tool.coverage.paths] -source = ["src", ".tox/*/site-packages"] +source = ["src", ".tox/py*/**/site-packages"] [tool.coverage.report] show_missing = true -omit = ["src/argon2/_ffi_build.py"] +skip_covered = true +exclude_lines = [ + # a more strict default pragma + "\\# pragma: no cover\\b", + + # allow defensive code + "^\\s*raise AssertionError\\b", + "^\\s*raise NotImplementedError\\b", + "^\\s*return NotImplemented\\b", + "^\\s*raise$", + + # typing-related code + "^if (False|TYPE_CHECKING):", + ": \\.\\.\\.(\\s*#.*)?$", + "^ +\\.\\.\\.$", + "-> ['\"]?NoReturn['\"]?:", +] +omit = [] + + +[tool.interrogate] +verbose = 2 +fail-under = 100 +whitelist-regex = ["test_.*"] + + +[tool.pyright] +ignore = ["conftest.py", "docs", "tests"] +disableBytesTypePromotions = true -[tool.black] +[tool.mypy] +strict = true +pretty = true + +show_error_codes = true +enable_error_code = ["ignore-without-code"] + +ignore_missing_imports = true + + +[[tool.mypy.overrides]] +module = "tests.*" +ignore_errors = true + + +[tool.ruff] +src = ["src", "tests", "noxfile.py"] line-length = 79 +[tool.ruff.lint] +select = ["ALL"] +ignore = [ + "A001", # shadowing is fine + "A002", # shadowing is fine + "A003", # shadowing is fine + "ANN", # Mypy is better at this + "ARG001", # unused arguments are normal when implementing interfaces + "COM", # Formatter takes care of our commas + "D", # We prefer our own docstring style. + "E501", # leave line-length enforcement to formatter + "ERA001", # Dead code detection is overly eager. + "FBT", # we have one function that takes one bool; c'mon! + "FIX", # Yes, we want XXX as a marker. + "INP001", # sometimes we want Python files outside of packages + "ISC001", # conflicts with ruff format + "PLR0913", # yes, many arguments, but most have defaults + "PLR2004", # numbers are sometimes fine + "PLW2901", # re-assigning within loop bodies is fine + "RUF001", # leave my smart characters alone + "SLF001", # private members are accessed by friendly functions + "TCH", # TYPE_CHECKING blocks break autodocs + "TD", # we don't follow other people's todo style +] + +[tool.ruff.lint.per-file-ignores] +"src/argon2/__main__.py" = ["T201"] # need print in CLI +"tests/*" = [ + "ARG", # stubs don't care about arguments + "S101", # assert + "SIM300", # Yoda rocks in asserts + "PT005", # we always add underscores and explicit name + "PT011", # broad is fine + "TRY002", # stock exceptions are fine in tests + "EM101", # no need for exception msg hygiene in tests +] + -[tool.isort] -profile = "attrs" +[tool.ruff.lint.isort] +lines-between-types = 1 +lines-after-imports = 2 diff --git a/setup.py b/setup.py deleted file mode 100644 index e06fe7a..0000000 --- a/setup.py +++ /dev/null @@ -1,372 +0,0 @@ -import codecs -import os -import platform -import re -import sys - -from distutils.command.build import build -from distutils.command.build_clib import build_clib -from distutils.errors import DistutilsSetupError - -from setuptools import find_packages, setup -from setuptools.command.install import install - - -############################################################################### - -NAME = "argon2-cffi" -PACKAGES = find_packages(where="src") - -use_sse2 = os.environ.get("ARGON2_CFFI_USE_SSE2", None) -if use_sse2 == "1": - optimized = True -elif use_sse2 == "0": - optimized = False -else: - # Optimized version requires SSE2 extensions. They have been around since - # 2001 so we try to compile it on every recent-ish x86. - optimized = platform.machine() in ("i686", "x86", "x86_64", "AMD64") - -CFFI_MODULES = ["src/argon2/_ffi_build.py:ffi"] -lib_base = os.path.join("extras", "libargon2", "src") -include_dirs = [ - os.path.join(lib_base, "..", "include"), - os.path.join(lib_base, "blake2"), -] -sources = [ - os.path.join(lib_base, path) - for path in [ - "argon2.c", - os.path.join("blake2", "blake2b.c"), - "core.c", - "encoding.c", - "opt.c" if optimized else "ref.c", - "thread.c", - ] -] - -# Add vendored integer types headers if necessary. -windows = "win32" in str(sys.platform).lower() - -LIBRARIES = [("argon2", {"include_dirs": include_dirs, "sources": sources})] -META_PATH = os.path.join("src", "argon2", "__init__.py") -KEYWORDS = ["password", "hash", "hashing", "security"] -PROJECT_URLS = { - "Documentation": "https://argon2-cffi.readthedocs.io/", - "Bug Tracker": "https://github.com/hynek/argon2-cffi/issues", - "Source Code": "https://github.com/hynek/argon2-cffi", - "Funding": "https://github.com/sponsors/hynek", - "Tidelift": "https://tidelift.com/subscription/pkg/pypi-argon2-cffi?" - "utm_source=pypi-argon2-cffi&utm_medium=pypi", - "Ko-fi": "https://ko-fi.com/the_hynek", -} -CLASSIFIERS = [ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", - "Natural Language :: English", - "Operating System :: MacOS :: MacOS X", - "Operating System :: Microsoft :: Windows", - "Operating System :: POSIX", - "Operating System :: Unix", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: Implementation :: CPython", - "Programming Language :: Python :: Implementation :: PyPy", - "Programming Language :: Python", - "Topic :: Security :: Cryptography", - "Topic :: Security", - "Topic :: Software Development :: Libraries :: Python Modules", -] - -PYTHON_REQUIRES = ">=3.5" -SETUP_REQUIRES = ["cffi"] -INSTALL_REQUIRES = ["cffi>=1.0.0"] -EXTRAS_REQUIRE = { - "docs": ["sphinx", "furo"], - "tests": ["coverage[toml]>=5.0.2", "hypothesis", "pytest"], -} -EXTRAS_REQUIRE["dev"] = ( - EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["docs"] + ["wheel", "pre-commit"] -) - -############################################################################### - - -def keywords_with_side_effects(argv): - """ - Get a dictionary with setup keywords that (can) have side effects. - - :param argv: A list of strings with command line arguments. - - :returns: A dictionary with keyword arguments for the ``setup()`` function. - This setup.py script uses the setuptools 'setup_requires' feature - because this is required by the cffi package to compile extension - modules. The purpose of ``keywords_with_side_effects()`` is to avoid - triggering the cffi build process as a result of setup.py invocations - that don't need the cffi module to be built (setup.py serves the dual - purpose of exposing package metadata). - - Stolen from pyca/cryptography. - """ - no_setup_requires_arguments = ( - "-h", - "--help", - "-n", - "--dry-run", - "-q", - "--quiet", - "-v", - "--verbose", - "-V", - "--version", - "--author", - "--author-email", - "--classifiers", - "--contact", - "--contact-email", - "--description", - "--egg-base", - "--fullname", - "--help-commands", - "--keywords", - "--licence", - "--license", - "--long-description", - "--maintainer", - "--maintainer-email", - "--name", - "--no-user-cfg", - "--obsoletes", - "--platforms", - "--provides", - "--requires", - "--url", - "clean", - "egg_info", - "register", - "sdist", - "upload", - ) - - def is_short_option(argument): - """Check whether a command line argument is a short option.""" - return len(argument) >= 2 and argument[0] == "-" and argument[1] != "-" - - def expand_short_options(argument): - """Expand combined short options into canonical short options.""" - return ("-" + char for char in argument[1:]) - - def argument_without_setup_requirements(argv, i): - """Check whether a command line argument needs setup requirements.""" - if argv[i] in no_setup_requires_arguments: - # Simple case: An argument which is either an option or a command - # which doesn't need setup requirements. - return True - elif is_short_option(argv[i]) and all( - option in no_setup_requires_arguments - for option in expand_short_options(argv[i]) - ): - # Not so simple case: Combined short options none of which need - # setup requirements. - return True - elif argv[i - 1 : i] == ["--egg-base"]: - # Tricky case: --egg-info takes an argument which should not make - # us use setup_requires (defeating the purpose of this code). - return True - else: - return False - - if all( - argument_without_setup_requirements(argv, i) - for i in range(1, len(argv)) - ): - return {"cmdclass": {"build": DummyBuild, "install": DummyInstall}} - else: - use_system_argon2 = ( - os.environ.get("ARGON2_CFFI_USE_SYSTEM", "0") == "1" - ) - if use_system_argon2: - disable_subcommand(build, "build_clib") - cmdclass = {"build_clib": BuildCLibWithCompilerFlags} - if BDistWheel is not None: - cmdclass["bdist_wheel"] = BDistWheel - return { - "setup_requires": SETUP_REQUIRES, - "cffi_modules": CFFI_MODULES, - "libraries": LIBRARIES, - "cmdclass": cmdclass, - } - - -def disable_subcommand(command, subcommand_name): - for name, method in command.sub_commands: - if name == subcommand_name: - command.sub_commands.remove((subcommand_name, method)) - break - - -setup_requires_error = ( - "Requested setup command that needs 'setup_requires' while command line " - "arguments implied a side effect free command or option." -) - - -class DummyBuild(build): - """ - This class makes it very obvious when ``keywords_with_side_effects()`` has - incorrectly interpreted the command line arguments to ``setup.py build`` as - one of the 'side effect free' commands or options. - """ - - def run(self): - raise RuntimeError(setup_requires_error) - - -class DummyInstall(install): - """ - This class makes it very obvious when ``keywords_with_side_effects()`` has - incorrectly interpreted the command line arguments to ``setup.py install`` - as one of the 'side effect free' commands or options. - """ - - def run(self): - raise RuntimeError(setup_requires_error) - - -HERE = os.path.abspath(os.path.dirname(__file__)) - - -def read(*parts): - """ - Build an absolute path from *parts* and and return the contents of the - resulting file. Assume UTF-8 encoding. - """ - with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: - return f.read() - - -META_FILE = read(META_PATH) - - -def find_meta(meta): - """ - Extract __*meta*__ from META_FILE. - """ - meta_match = re.search( - r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M - ) - if meta_match: - return meta_match.group(1) - raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) - - -VERSION = find_meta("version") -URL = find_meta("url") -LONG = ( - read("README.rst") - + "\n\n" - + "Release Information\n" - + "===================\n\n" - + re.search( - r"(\d+.\d.\d \(.*?\)\r?\n.*?)\r?\n\r?\n\r?\n----\r?\n\r?\n\r?\n", - read("CHANGELOG.rst"), - re.S, - ).group(1) - + "\n\n`Full changelog " - + "<{url}en/stable/changelog.html>`_.\n\n".format(url=URL) - + read("AUTHORS.rst") -) - - -class BuildCLibWithCompilerFlags(build_clib): - """ - We need to pass ``-msse2`` for the optimized build. - """ - - def build_libraries(self, libraries): - """ - Mostly copy pasta from ``distutils.command.build_clib``. - """ - for (lib_name, build_info) in libraries: - sources = build_info.get("sources") - if sources is None or not isinstance(sources, (list, tuple)): - raise DistutilsSetupError( - "in 'libraries' option (library '%s'), " - "'sources' must be present and must be " - "a list of source filenames" % lib_name - ) - sources = list(sources) - - print("building '{}' library".format(lib_name)) - - # First, compile the source code to object files in the library - # directory. (This should probably change to putting object - # files in a temporary build directory.) - macros = build_info.get("macros") - include_dirs = build_info.get("include_dirs") - objects = self.compiler.compile( - sources, - extra_preargs=["-msse2"] if optimized and not windows else [], - output_dir=self.build_temp, - macros=macros, - include_dirs=include_dirs, - debug=self.debug, - ) - - # Now "link" the object files together into a static library. - # (On Unix at least, this isn't really linking -- it just - # builds an archive. Whatever.) - self.compiler.create_static_lib( - objects, lib_name, output_dir=self.build_clib, debug=self.debug - ) - - -if sys.version_info > (3,) and platform.python_implementation() == "CPython": - try: - import wheel.bdist_wheel - except ImportError: - BDistWheel = None - else: - - class BDistWheel(wheel.bdist_wheel.bdist_wheel): - def finalize_options(self): - self.py_limited_api = "cp3{}".format(sys.version_info[1]) - wheel.bdist_wheel.bdist_wheel.finalize_options(self) - - -else: - BDistWheel = None - - -if __name__ == "__main__": - setup( - name=NAME, - description=find_meta("description"), - license=find_meta("license"), - url=URL, - project_urls=PROJECT_URLS, - version=VERSION, - author=find_meta("author"), - author_email=find_meta("email"), - maintainer=find_meta("author"), - maintainer_email=find_meta("email"), - long_description=LONG, - long_description_content_type="text/x-rst", - keywords=KEYWORDS, - packages=PACKAGES, - package_dir={"": "src"}, - classifiers=CLASSIFIERS, - python_requires=PYTHON_REQUIRES, - install_requires=INSTALL_REQUIRES, - extras_require=EXTRAS_REQUIRE, - # CFFI - zip_safe=False, - ext_package="argon2", - **keywords_with_side_effects(sys.argv) - ) diff --git a/src/argon2/__init__.py b/src/argon2/__init__.py index a290b15..bea9839 100644 --- a/src/argon2/__init__.py +++ b/src/argon2/__init__.py @@ -1,4 +1,10 @@ -from . import exceptions, low_level +# SPDX-License-Identifier: MIT + +""" +Argon2 for Python +""" + +from . import exceptions, low_level, profiles from ._legacy import hash_password, hash_password_raw, verify_password from ._password_hasher import ( DEFAULT_HASH_LENGTH, @@ -12,19 +18,11 @@ from .low_level import Type -__version__ = "21.1.0" - __title__ = "argon2-cffi" -__description__ = "The secure Argon2 password hashing algorithm." -__url__ = "https://argon2-cffi.readthedocs.io/" -__uri__ = __url__ -__doc__ = __description__ + " <" + __url__ + ">" __author__ = "Hynek Schlawack" -__email__ = "hs@ox.cx" - -__license__ = "MIT" __copyright__ = "Copyright (c) 2015 " + __author__ +__license__ = "MIT" __all__ = [ @@ -41,5 +39,41 @@ "hash_password", "hash_password_raw", "low_level", + "profiles", "verify_password", ] + + +def __getattr__(name: str) -> str: + dunder_to_metadata = { + "__version__": "version", + "__description__": "summary", + "__uri__": "", + "__url__": "", + "__email__": "", + } + if name not in dunder_to_metadata: + msg = f"module {__name__} has no attribute {name}" + raise AttributeError(msg) + + import warnings + + from importlib.metadata import metadata + + warnings.warn( + f"Accessing argon2.{name} is deprecated and will be " + "removed in a future release. Use importlib.metadata directly " + "to query for argon2-cffi's packaging metadata.", + DeprecationWarning, + stacklevel=2, + ) + + meta = metadata("argon2-cffi") + + if name in ("__uri__", "__url__"): + return meta["Project-URL"].split(" ", 1)[-1] + + if name == "__email__": + return meta["Author-email"].split("<", 1)[1].rstrip(">") + + return meta[dunder_to_metadata[name]] diff --git a/src/argon2/__main__.py b/src/argon2/__main__.py index 63cfcb3..80ba933 100644 --- a/src/argon2/__main__.py +++ b/src/argon2/__main__.py @@ -1,3 +1,7 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + import argparse import sys import timeit @@ -8,11 +12,15 @@ DEFAULT_PARALLELISM, DEFAULT_TIME_COST, PasswordHasher, + profiles, ) -def main(argv): - parser = argparse.ArgumentParser(description="Benchmark Argon2.") +def main(argv: list[str]) -> None: + parser = argparse.ArgumentParser( + description="Benchmark Argon2.", + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) parser.add_argument( "-n", type=int, default=100, help="Number of iterations to measure." ) @@ -28,56 +36,56 @@ def main(argv): parser.add_argument( "-l", type=int, help="`hash_length`", default=DEFAULT_HASH_LENGTH ) + parser.add_argument( + "--profile", + type=str, + help="A profile from `argon2.profiles. Takes precedence.", + default=None, + ) args = parser.parse_args(argv[1:]) password = b"secret" - ph = PasswordHasher( - time_cost=args.t, - memory_cost=args.m, - parallelism=args.p, - hash_len=args.l, - ) + if args.profile: + ph = PasswordHasher.from_parameters( + getattr(profiles, args.profile.upper()) + ) + else: + ph = PasswordHasher( + time_cost=args.t, + memory_cost=args.m, + parallelism=args.p, + hash_len=args.l, + ) hash = ph.hash(password) - params = { - "time_cost": (args.t, "iterations"), - "memory_cost": (args.m, "KiB"), - "parallelism": (args.p, "threads"), - "hash_len": (args.l, "bytes"), - } + print(f"Running Argon2id {args.n} times with:") - print("Running Argon2id %d times with:" % (args.n,)) - - for k, v in sorted(params.items()): - print("%s: %d %s" % (k, v[0], v[1])) + for name, value, units in [ + ("hash_len", ph.hash_len, "bytes"), + ("memory_cost", ph.memory_cost, "KiB"), + ("parallelism", ph.parallelism, "threads"), + ("time_cost", ph.time_cost, "iterations"), + ]: + print(f"{name}: {value} {units}") print("\nMeasuring...") duration = timeit.timeit( - "ph.verify({hash!r}, {password!r})".format( - hash=hash, password=password - ), - setup="""\ -from argon2 import PasswordHasher, Type + f"ph.verify({hash!r}, {password!r})", + setup=f"""\ +from argon2 import PasswordHasher ph = PasswordHasher( - time_cost={time_cost!r}, - memory_cost={memory_cost!r}, - parallelism={parallelism!r}, - hash_len={hash_len!r}, + time_cost={args.t!r}, + memory_cost={args.m!r}, + parallelism={args.p!r}, + hash_len={args.l!r}, ) -gc.enable()""".format( - time_cost=args.t, - memory_cost=args.m, - parallelism=args.p, - hash_len=args.l, - ), +gc.enable()""", number=args.n, ) - print( - "\n{:.1f}ms per password verification".format(duration / args.n * 1000) - ) + print(f"\n{duration / args.n * 1000:.1f}ms per password verification") -if __name__ == "__main__": # pragma: nocover +if __name__ == "__main__": # pragma: no cover main(sys.argv) diff --git a/src/argon2/_ffi_build.py b/src/argon2/_ffi_build.py deleted file mode 100644 index cfd3bb6..0000000 --- a/src/argon2/_ffi_build.py +++ /dev/null @@ -1,175 +0,0 @@ -import os - -from cffi import FFI - - -include_dirs = [os.path.join("extras", "libargon2", "include")] -use_system_argon2 = os.environ.get("ARGON2_CFFI_USE_SYSTEM", "0") == "1" -if use_system_argon2: - include_dirs = [] - - -ffi = FFI() -ffi.set_source( - "_ffi", - "#include ", - include_dirs=include_dirs, - libraries=["argon2"], -) - -ffi.cdef( - """\ -typedef enum Argon2_type { - Argon2_d = ..., - Argon2_i = ..., - Argon2_id = ..., -} argon2_type; -typedef enum Argon2_version { - ARGON2_VERSION_10 = ..., - ARGON2_VERSION_13 = ..., - ARGON2_VERSION_NUMBER = ... -} argon2_version; - -int argon2_hash(const uint32_t t_cost, const uint32_t m_cost, - const uint32_t parallelism, const void *pwd, - const size_t pwdlen, const void *salt, - const size_t saltlen, void *hash, - const size_t hashlen, char *encoded, - const size_t encodedlen, argon2_type type, - const uint32_t version); - -int argon2_verify(const char *encoded, const void *pwd, - const size_t pwdlen, argon2_type type); - -const char *argon2_error_message(int error_code); - - -typedef int (*allocate_fptr)(uint8_t **memory, size_t bytes_to_allocate); -typedef void (*deallocate_fptr)(uint8_t *memory, size_t bytes_to_allocate); - -typedef struct Argon2_Context { - uint8_t *out; /* output array */ - uint32_t outlen; /* digest length */ - - uint8_t *pwd; /* password array */ - uint32_t pwdlen; /* password length */ - - uint8_t *salt; /* salt array */ - uint32_t saltlen; /* salt length */ - - uint8_t *secret; /* key array */ - uint32_t secretlen; /* key length */ - - uint8_t *ad; /* associated data array */ - uint32_t adlen; /* associated data length */ - - uint32_t t_cost; /* number of passes */ - uint32_t m_cost; /* amount of memory requested (KB) */ - uint32_t lanes; /* number of lanes */ - uint32_t threads; /* maximum number of threads */ - - uint32_t version; /* version number */ - - allocate_fptr allocate_cbk; /* pointer to memory allocator */ - deallocate_fptr free_cbk; /* pointer to memory deallocator */ - - uint32_t flags; /* array of bool options */ -} argon2_context; - -int argon2_ctx(argon2_context *context, argon2_type type); - -/* Error codes */ -typedef enum Argon2_ErrorCodes { - ARGON2_OK = ..., - - ARGON2_OUTPUT_PTR_NULL = ..., - - ARGON2_OUTPUT_TOO_SHORT = ..., - ARGON2_OUTPUT_TOO_LONG = ..., - - ARGON2_PWD_TOO_SHORT = ..., - ARGON2_PWD_TOO_LONG = ..., - - ARGON2_SALT_TOO_SHORT = ..., - ARGON2_SALT_TOO_LONG = ..., - - ARGON2_AD_TOO_SHORT = ..., - ARGON2_AD_TOO_LONG = ..., - - ARGON2_SECRET_TOO_SHORT = ..., - ARGON2_SECRET_TOO_LONG = ..., - - ARGON2_TIME_TOO_SMALL = ..., - ARGON2_TIME_TOO_LARGE = ..., - - ARGON2_MEMORY_TOO_LITTLE = ..., - ARGON2_MEMORY_TOO_MUCH = ..., - - ARGON2_LANES_TOO_FEW = ..., - ARGON2_LANES_TOO_MANY = ..., - - ARGON2_PWD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ - ARGON2_SALT_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ - ARGON2_SECRET_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ - ARGON2_AD_PTR_MISMATCH = ..., /* NULL ptr with non-zero length */ - - ARGON2_MEMORY_ALLOCATION_ERROR = ..., - - ARGON2_FREE_MEMORY_CBK_NULL = ..., - ARGON2_ALLOCATE_MEMORY_CBK_NULL = ..., - - ARGON2_INCORRECT_PARAMETER = ..., - ARGON2_INCORRECT_TYPE = ..., - - ARGON2_OUT_PTR_MISMATCH = ..., - - ARGON2_THREADS_TOO_FEW = ..., - ARGON2_THREADS_TOO_MANY = ..., - - ARGON2_MISSING_ARGS = ..., - - ARGON2_ENCODING_FAIL = ..., - - ARGON2_DECODING_FAIL = ..., - - ARGON2_THREAD_FAIL = ..., - - ARGON2_DECODING_LENGTH_FAIL= ..., - - ARGON2_VERIFY_MISMATCH = ..., -} argon2_error_codes; - -#define ARGON2_FLAG_CLEAR_PASSWORD ... -#define ARGON2_FLAG_CLEAR_SECRET ... -#define ARGON2_DEFAULT_FLAGS ... - -#define ARGON2_MIN_LANES ... -#define ARGON2_MAX_LANES ... -#define ARGON2_MIN_THREADS ... -#define ARGON2_MAX_THREADS ... -#define ARGON2_SYNC_POINTS ... -#define ARGON2_MIN_OUTLEN ... -#define ARGON2_MAX_OUTLEN ... -#define ARGON2_MIN_MEMORY ... -#define ARGON2_MAX_MEMORY_BITS ... -#define ARGON2_MAX_MEMORY ... -#define ARGON2_MIN_TIME ... -#define ARGON2_MAX_TIME ... -#define ARGON2_MIN_PWD_LENGTH ... -#define ARGON2_MAX_PWD_LENGTH ... -#define ARGON2_MIN_AD_LENGTH ... -#define ARGON2_MAX_AD_LENGTH ... -#define ARGON2_MIN_SALT_LENGTH ... -#define ARGON2_MAX_SALT_LENGTH ... -#define ARGON2_MIN_SECRET ... -#define ARGON2_MAX_SECRET ... - -uint32_t argon2_encodedlen(uint32_t t_cost, uint32_t m_cost, - uint32_t parallelism, uint32_t saltlen, - uint32_t hashlen, argon2_type type); - -""" -) - -if __name__ == "__main__": - ffi.compile() diff --git a/src/argon2/_legacy.py b/src/argon2/_legacy.py index bd1bc60..05a1e81 100644 --- a/src/argon2/_legacy.py +++ b/src/argon2/_legacy.py @@ -1,9 +1,15 @@ +# SPDX-License-Identifier: MIT + """ Legacy mid-level functions. """ +from __future__ import annotations import os +import warnings + +from typing import Literal from ._password_hasher import ( DEFAULT_HASH_LENGTH, @@ -15,21 +21,28 @@ from .low_level import Type, hash_secret, hash_secret_raw, verify_secret +_INSTEAD = " is deprecated, use argon2.PasswordHasher instead" + + def hash_password( - password, - salt=None, - time_cost=DEFAULT_TIME_COST, - memory_cost=DEFAULT_MEMORY_COST, - parallelism=DEFAULT_PARALLELISM, - hash_len=DEFAULT_HASH_LENGTH, - type=Type.I, -): + password: bytes, + salt: bytes | None = None, + time_cost: int = DEFAULT_TIME_COST, + memory_cost: int = DEFAULT_MEMORY_COST, + parallelism: int = DEFAULT_PARALLELISM, + hash_len: int = DEFAULT_HASH_LENGTH, + type: Type = Type.I, +) -> bytes: """ - Legacy alias for :func:`hash_secret` with default parameters. + Legacy alias for :func:`argon2.low_level.hash_secret` with default + parameters. .. deprecated:: 16.0.0 Use :class:`argon2.PasswordHasher` for passwords. """ + warnings.warn( + "argon2.hash_password" + _INSTEAD, DeprecationWarning, stacklevel=2 + ) if salt is None: salt = os.urandom(DEFAULT_RANDOM_SALT_LENGTH) return hash_secret( @@ -38,20 +51,24 @@ def hash_password( def hash_password_raw( - password, - salt=None, - time_cost=DEFAULT_TIME_COST, - memory_cost=DEFAULT_MEMORY_COST, - parallelism=DEFAULT_PARALLELISM, - hash_len=DEFAULT_HASH_LENGTH, - type=Type.I, -): + password: bytes, + salt: bytes | None = None, + time_cost: int = DEFAULT_TIME_COST, + memory_cost: int = DEFAULT_MEMORY_COST, + parallelism: int = DEFAULT_PARALLELISM, + hash_len: int = DEFAULT_HASH_LENGTH, + type: Type = Type.I, +) -> bytes: """ - Legacy alias for :func:`hash_secret_raw` with default parameters. + Legacy alias for :func:`argon2.low_level.hash_secret_raw` with default + parameters. .. deprecated:: 16.0.0 Use :class:`argon2.PasswordHasher` for passwords. """ + warnings.warn( + "argon2.hash_password_raw" + _INSTEAD, DeprecationWarning, stacklevel=2 + ) if salt is None: salt = os.urandom(DEFAULT_RANDOM_SALT_LENGTH) return hash_secret_raw( @@ -59,11 +76,17 @@ def hash_password_raw( ) -def verify_password(hash, password, type=Type.I): +def verify_password( + hash: bytes, password: bytes, type: Type = Type.I +) -> Literal[True]: """ - Legacy alias for :func:`verify_secret` with default parameters. + Legacy alias for :func:`argon2.low_level.verify_secret` with default + parameters. .. deprecated:: 16.0.0 Use :class:`argon2.PasswordHasher` for passwords. """ + warnings.warn( + "argon2.verify_password" + _INSTEAD, DeprecationWarning, stacklevel=2 + ) return verify_secret(hash, password, type) diff --git a/src/argon2/_password_hasher.py b/src/argon2/_password_hasher.py index 89bd2cc..ddf1ce5 100644 --- a/src/argon2/_password_hasher.py +++ b/src/argon2/_password_hasher.py @@ -1,18 +1,32 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + import os -from ._utils import Parameters, _check_types, extract_parameters -from .exceptions import InvalidHash +from typing import ClassVar, Literal + +from ._utils import ( + Parameters, + _check_types, + extract_parameters, + validate_params_for_platform, +) +from .exceptions import InvalidHashError from .low_level import Type, hash_secret, verify_secret +from .profiles import get_default_parameters -DEFAULT_RANDOM_SALT_LENGTH = 16 -DEFAULT_HASH_LENGTH = 16 -DEFAULT_TIME_COST = 2 -DEFAULT_MEMORY_COST = 102400 -DEFAULT_PARALLELISM = 8 +default_params = get_default_parameters() +DEFAULT_RANDOM_SALT_LENGTH = default_params.salt_len +DEFAULT_HASH_LENGTH = default_params.hash_len +DEFAULT_TIME_COST = default_params.time_cost +DEFAULT_MEMORY_COST = default_params.memory_cost +DEFAULT_PARALLELISM = default_params.parallelism -def _ensure_bytes(s, encoding): + +def _ensure_bytes(s: bytes | str, encoding: str) -> bytes: """ Ensure *s* is a bytes string. Encode using *encoding* if it isn't. """ @@ -25,27 +39,36 @@ class PasswordHasher: r""" High level class to hash passwords with sensible defaults. - Uses Argon2\ **id** by default and always uses a random salt_ for hashing. - But it can verify any type of Argon2 as long as the hash is correctly - encoded. + Uses Argon2\ **id** by default and uses a random salt_ for hashing. But it + can verify any type of Argon2 as long as the hash is correctly encoded. The reason for this being a class is both for convenience to carry parameters and to verify the parameters only *once*. Any unnecessary - slowdown when hashing is a tangible advantage for a brute force attacker. - - :param int time_cost: Defines the amount of computation realized and - therefore the execution time, given in number of iterations. - :param int memory_cost: Defines the memory usage, given in kibibytes_. - :param int parallelism: Defines the number of parallel threads (*changes* - the resulting hash value). - :param int hash_len: Length of the hash in bytes. - :param int salt_len: Length of random salt to be generated for each - password. - :param str encoding: The Argon2 C library expects bytes. So if - :meth:`hash` or :meth:`verify` are passed an unicode string, it will be - encoded using this encoding. - :param Type type: Argon2 type to use. Only change for interoperability - with legacy systems. + slowdown when hashing is a tangible advantage for a brute-force attacker. + + Args: + time_cost: + Defines the amount of computation realized and therefore the + execution time, given in number of iterations. + + memory_cost: Defines the memory usage, given in kibibytes_. + + parallelism: + Defines the number of parallel threads (*changes* the resulting + hash value). + + hash_len: Length of the hash in bytes. + + salt_len: Length of random salt to be generated for each password. + + encoding: + The Argon2 C library expects bytes. So if :meth:`hash` or + :meth:`verify` are passed a ``str``, it will be encoded using this + encoding. + + type: + Argon2 type to use. Only change for interoperability with legacy + systems. .. versionadded:: 16.0.0 .. versionchanged:: 18.2.0 @@ -55,21 +78,28 @@ class PasswordHasher: Changed default *memory_cost* to 100 MiB and default *parallelism* to 8. .. versionchanged:: 18.2.0 ``verify`` now will determine the type of hash. .. versionchanged:: 18.3.0 The Argon2 type is configurable now. + .. versionadded:: 21.2.0 :meth:`from_parameters` + .. versionchanged:: 21.2.0 + Changed defaults to :data:`argon2.profiles.RFC_9106_LOW_MEMORY`. .. _salt: https://en.wikipedia.org/wiki/Salt_(cryptography) .. _kibibytes: https://en.wikipedia.org/wiki/Binary_prefix#kibi """ + __slots__ = ["_parameters", "encoding"] + _parameters: Parameters + encoding: str + def __init__( self, - time_cost=DEFAULT_TIME_COST, - memory_cost=DEFAULT_MEMORY_COST, - parallelism=DEFAULT_PARALLELISM, - hash_len=DEFAULT_HASH_LENGTH, - salt_len=DEFAULT_RANDOM_SALT_LENGTH, - encoding="utf-8", - type=Type.ID, + time_cost: int = DEFAULT_TIME_COST, + memory_cost: int = DEFAULT_MEMORY_COST, + parallelism: int = DEFAULT_PARALLELISM, + hash_len: int = DEFAULT_HASH_LENGTH, + salt_len: int = DEFAULT_RANDOM_SALT_LENGTH, + encoding: str = "utf-8", + type: Type = Type.ID, ): e = _check_types( time_cost=(time_cost, int), @@ -83,8 +113,7 @@ def __init__( if e: raise TypeError(e) - # Cache a Parameters object for check_needs_rehash. - self._parameters = Parameters( + params = Parameters( type=type, version=19, salt_len=salt_len, @@ -93,46 +122,83 @@ def __init__( memory_cost=memory_cost, parallelism=parallelism, ) + + validate_params_for_platform(params) + + # Cache a Parameters object for check_needs_rehash. + self._parameters = params self.encoding = encoding + @classmethod + def from_parameters(cls, params: Parameters) -> PasswordHasher: + """ + Construct a `PasswordHasher` from *params*. + + Returns: + A `PasswordHasher` instance with the parameters from *params*. + + .. versionadded:: 21.2.0 + """ + + return cls( + time_cost=params.time_cost, + memory_cost=params.memory_cost, + parallelism=params.parallelism, + hash_len=params.hash_len, + salt_len=params.salt_len, + type=params.type, + ) + @property - def time_cost(self): + def time_cost(self) -> int: return self._parameters.time_cost @property - def memory_cost(self): + def memory_cost(self) -> int: return self._parameters.memory_cost @property - def parallelism(self): + def parallelism(self) -> int: return self._parameters.parallelism @property - def hash_len(self): + def hash_len(self) -> int: return self._parameters.hash_len @property - def salt_len(self): + def salt_len(self) -> int: return self._parameters.salt_len @property - def type(self): + def type(self) -> Type: return self._parameters.type - def hash(self, password): + def hash(self, password: str | bytes, *, salt: bytes | None = None) -> str: """ Hash *password* and return an encoded hash. - :param password: Password to hash. - :type password: ``bytes`` or ``unicode`` + Args: + password: Password to hash. - :raises argon2.exceptions.HashingError: If hashing fails. + salt: + If None, a random salt is securely created. - :rtype: unicode + .. danger:: + + You should **not** pass a salt unless you really know what + you are doing. + + Raises: + argon2.exceptions.HashingError: If hashing fails. + + Returns: + Hashed *password*. + + .. versionadded:: 23.1.0 *salt* parameter """ return hash_secret( secret=_ensure_bytes(password, self.encoding), - salt=os.urandom(self.salt_len), + salt=salt or os.urandom(self.salt_len), time_cost=self.time_cost, memory_cost=self.memory_cost, parallelism=self.parallelism, @@ -140,13 +206,15 @@ def hash(self, password): type=self.type, ).decode("ascii") - _header_to_type = { + _header_to_type: ClassVar[dict[bytes, Type]] = { b"$argon2i$": Type.I, b"$argon2d$": Type.D, b"$argon2id": Type.ID, } - def verify(self, hash, password): + def verify( + self, hash: str | bytes, password: str | bytes + ) -> Literal[True]: """ Verify that *password* matches *hash*. @@ -154,25 +222,27 @@ def verify(self, hash, password): It is assumed that the caller is in full control of the hash. No other parsing than the determination of the hash type is done by - ``argon2-cffi``. + *argon2-cffi*. - :param hash: An encoded hash as returned from - :meth:`PasswordHasher.hash`. - :type hash: ``bytes`` or ``unicode`` + Args: + hash: An encoded hash as returned from :meth:`PasswordHasher.hash`. - :param password: The password to verify. - :type password: ``bytes`` or ``unicode`` + password: The password to verify. - :raises argon2.exceptions.VerifyMismatchError: If verification fails - because *hash* is not valid for *password*. - :raises argon2.exceptions.VerificationError: If verification fails for - other reasons. - :raises argon2.exceptions.InvalidHash: If *hash* is so clearly - invalid, that it couldn't be passed to Argon2. + Raises: + argon2.exceptions.VerifyMismatchError: + If verification fails because *hash* is not valid for + *password*. - :return: ``True`` on success, raise - :exc:`~argon2.exceptions.VerificationError` otherwise. - :rtype: bool + argon2.exceptions.VerificationError: + If verification fails for other reasons. + + argon2.exceptions.InvalidHashError: + If *hash* is so clearly invalid, that it couldn't be passed to + Argon2. + + Returns: + ``True`` on success, otherwise an exception is raised. .. versionchanged:: 16.1.0 Raise :exc:`~argon2.exceptions.VerifyMismatchError` on mismatches @@ -182,18 +252,18 @@ def verify(self, hash, password): hash = _ensure_bytes(hash, "ascii") try: hash_type = self._header_to_type[hash[:9]] - except (IndexError, KeyError, LookupError): - raise InvalidHash() + except LookupError: + raise InvalidHashError from None return verify_secret( hash, _ensure_bytes(password, self.encoding), hash_type ) - def check_needs_rehash(self, hash): + def check_needs_rehash(self, hash: str | bytes) -> bool: """ Check whether *hash* was created using the instance's parameters. - Whenever your Argon2 parameters -- or ``argon2-cffi``'s defaults! -- + Whenever your Argon2 parameters -- or *argon2-cffi*'s defaults! -- change, you should rehash your passwords at the next opportunity. The common approach is to do that whenever a user logs in, since that should be the only time when you have access to the cleartext @@ -202,8 +272,16 @@ def check_needs_rehash(self, hash): Therefore it's best practice to check -- and if necessary rehash -- passwords after each successful authentication. - :rtype: bool + Args: + hash: An encoded Argon2 password hash. + + Returns: + Whether *hash* was created using the instance's parameters. .. versionadded:: 18.2.0 + .. versionchanged:: 24.1.0 Accepts bytes for *hash*. """ + if isinstance(hash, bytes): + hash = hash.decode("ascii") + return self._parameters != extract_parameters(hash) diff --git a/src/argon2/_utils.py b/src/argon2/_utils.py index c78db81..21a6362 100644 --- a/src/argon2/_utils.py +++ b/src/argon2/_utils.py @@ -1,11 +1,21 @@ -from .exceptions import InvalidHash +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +import platform +import sys + +from dataclasses import dataclass +from typing import Any + +from .exceptions import InvalidHashError, UnsupportedParametersError from .low_level import Type NoneType = type(None) -def _check_types(**kw): +def _check_types(**kw: Any) -> str | None: """ Check each ``name: (value, types)`` in *kw*. @@ -19,27 +29,27 @@ def _check_types(**kw): else: types = types.__name__ errors.append( - "'{name}' must be a {type} (got {actual})".format( - name=name, type=types, actual=type(value).__name__ - ) + f"'{name}' must be a {types} (got {type(value).__name__})" ) if errors != []: return ", ".join(errors) + "." + return None -def _encoded_str_len(l): - """ - Compute how long a byte string of length *l* becomes if encoded to hex. - """ - return (l << 2) / 3 + 2 + +def _is_wasm() -> bool: + return sys.platform == "emscripten" or platform.machine() in [ + "wasm32", + "wasm64", + ] -def _decoded_str_len(l): +def _decoded_str_len(length: int) -> int: """ Compute how long an encoded string of length *l* becomes. """ - rem = l % 4 + rem = length % 4 if rem == 3: last_group_len = 2 @@ -48,109 +58,66 @@ def _decoded_str_len(l): else: last_group_len = 0 - return l // 4 * 3 + last_group_len + return length // 4 * 3 + last_group_len +@dataclass class Parameters: """ Argon2 hash parameters. See :doc:`parameters` on how to pick them. - :ivar Type type: Hash type. - :ivar int version: Argon2 version. - :ivar int salt_len: Length of the salt in bytes. - :ivar int hash_len: Length of the hash in bytes. - :ivar int time_cost: Time cost in iterations. - :ivar int memory_cost: Memory cost in kibibytes. - :ivar int parallelism: Number of parallel threads. + Attributes: + type: Hash type. + + version: Argon2 version. + + salt_len: Length of the salt in bytes. + + hash_len: Length of the hash in bytes. + + time_cost: Time cost in iterations. + + memory_cost: Memory cost in kibibytes. + + parallelism: Number of parallel threads. .. versionadded:: 18.2.0 """ - __slots__ = [ - "type", - "version", - "salt_len", + type: Type + version: int + salt_len: int + hash_len: int + time_cost: int + memory_cost: int + parallelism: int + + __slots__ = ( "hash_len", - "time_cost", "memory_cost", "parallelism", - ] - - def __init__( - self, - type, - version, - salt_len, - hash_len, - time_cost, - memory_cost, - parallelism, - ): - self.type = type - self.version = version - self.salt_len = salt_len - self.hash_len = hash_len - self.time_cost = time_cost - self.memory_cost = memory_cost - self.parallelism = parallelism - - def __repr__(self): - return ( - "" - % ( - self.type, - self.version, - self.hash_len, - self.salt_len, - self.time_cost, - self.memory_cost, - self.parallelism, - ) - ) - - def __eq__(self, other): - if self.__class__ != other.__class__: - return NotImplemented - - return ( - self.type, - self.version, - self.salt_len, - self.hash_len, - self.time_cost, - self.memory_cost, - self.parallelism, - ) == ( - other.type, - other.version, - other.salt_len, - other.hash_len, - other.time_cost, - other.memory_cost, - other.parallelism, - ) - - def __ne__(self, other): - if self.__class__ != other.__class__: - return NotImplemented - - return not self.__eq__(other) + "salt_len", + "time_cost", + "type", + "version", + ) _NAME_TO_TYPE = {"argon2id": Type.ID, "argon2i": Type.I, "argon2d": Type.D} _REQUIRED_KEYS = sorted(("v", "m", "t", "p")) -def extract_parameters(hash): +def extract_parameters(hash: str) -> Parameters: """ Extract parameters from an encoded *hash*. - :param str params: An encoded Argon2 hash string. + Args: + hash: An encoded Argon2 hash string. - :rtype: Parameters + Returns: + The parameters used to create the hash. .. versionadded:: 18.2.0 """ @@ -161,10 +128,10 @@ def extract_parameters(hash): parts.insert(2, "v=18") if len(parts) != 6: - raise InvalidHash + raise InvalidHashError - if parts[0] != "": - raise InvalidHash + if parts[0]: + raise InvalidHashError try: type = _NAME_TO_TYPE[parts[1]] @@ -172,14 +139,14 @@ def extract_parameters(hash): kvs = { k: int(v) for k, v in ( - s.split("=") for s in [parts[2]] + parts[3].split(",") + s.split("=") for s in [parts[2], *parts[3].split(",")] ) } - except Exception: - raise InvalidHash + except Exception: # noqa: BLE001 + raise InvalidHashError from None if sorted(kvs.keys()) != _REQUIRED_KEYS: - raise InvalidHash + raise InvalidHashError return Parameters( type=type, @@ -190,3 +157,18 @@ def extract_parameters(hash): memory_cost=kvs["m"], parallelism=kvs["p"], ) + + +def validate_params_for_platform(params: Parameters) -> None: + """ + Validate *params* against current platform. + + Args: + params: Parameters to be validated + + Returns: + None + """ + if _is_wasm() and params.parallelism != 1: + msg = "In WebAssembly environments `parallelism` must be 1." + raise UnsupportedParametersError(msg) diff --git a/src/argon2/exceptions.py b/src/argon2/exceptions.py index ba20c94..a0dade5 100644 --- a/src/argon2/exceptions.py +++ b/src/argon2/exceptions.py @@ -1,3 +1,8 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + + class Argon2Error(Exception): """ Superclass of all argon2 exceptions. @@ -32,9 +37,30 @@ class HashingError(Argon2Error): """ -class InvalidHash(ValueError): +class InvalidHashError(ValueError): """ Raised if the hash is invalid before passing it to Argon2. - .. versionadded:: 18.2.0 + .. versionadded:: 23.1.0 + As a replacement for :exc:`argon2.exceptions.InvalidHash`. + """ + + +class UnsupportedParametersError(ValueError): """ + Raised if the current platform does not support the parameters. + + For example, in WebAssembly parallelism must be set to 1. + + .. versionadded:: 25.1.0 + """ + + +InvalidHash = InvalidHashError +""" +Deprecated alias for :class:`InvalidHashError`. + +.. versionadded:: 18.2.0 +.. deprecated:: 23.1.0 + Use :exc:`argon2.exceptions.InvalidHashError` instead. +""" diff --git a/src/argon2/low_level.py b/src/argon2/low_level.py index 1f40de1..0598466 100644 --- a/src/argon2/low_level.py +++ b/src/argon2/low_level.py @@ -1,16 +1,21 @@ +# SPDX-License-Identifier: MIT + """ Low-level functions if you want to build your own higher level abstractions. .. warning:: This is a "Hazardous Materials" module. You should **ONLY** use it if - you're 100% absolutely sure that you know what you’re doing because this + you're 100% absolutely sure that you know what you're doing because this module is full of land mines, dragons, and dinosaurs with laser guns. """ +from __future__ import annotations from enum import Enum +from typing import Any, Literal + +from _argon2_cffi_bindings import ffi, lib -from ._ffi import ffi, lib from .exceptions import HashingError, VerificationError, VerifyMismatchError @@ -40,62 +45,47 @@ class Type(Enum): """ D = lib.Argon2_d - r""" - Argon2\ **d** is faster and uses data-depending memory access, which makes - it less suitable for hashing secrets and more suitable for cryptocurrencies - and applications with no threats from side-channel timing attacks. - """ - I = lib.Argon2_i - r""" - Argon2\ **i** uses data-independent memory access. Argon2i is slower as - it makes more passes over the memory to protect from tradeoff attacks. - """ + I = lib.Argon2_i # noqa: E741 ID = lib.Argon2_id - r""" - Argon2\ **id** is a hybrid of Argon2i and Argon2d, using a combination of - data-depending and data-independent memory accesses, which gives some of - Argon2i's resistance to side-channel cache timing attacks and much of - Argon2d's resistance to GPU cracking attacks. - - That makes it the preferred type for password hashing and password-based - key derivation. - - .. versionadded:: 16.3.0 - """ def hash_secret( - secret, - salt, - time_cost, - memory_cost, - parallelism, - hash_len, - type, - version=ARGON2_VERSION, -): + secret: bytes, + salt: bytes, + time_cost: int, + memory_cost: int, + parallelism: int, + hash_len: int, + type: Type, + version: int = ARGON2_VERSION, +) -> bytes: """ Hash *secret* and return an **encoded** hash. An encoded hash can be directly passed into :func:`verify_secret` as it contains all parameters and the salt. - :param bytes secret: Secret to hash. - :param bytes salt: A salt_. Should be random and different for each - secret. - :param Type type: Which Argon2 variant to use. - :param int version: Which Argon2 version to use. + Args: + secret: Secret to hash. + + salt: A salt_. Should be random and different for each secret. + + type: Which Argon2 variant to use. - For an explanation of the Argon2 parameters see :class:`PasswordHasher`. + version: Which Argon2 version to use. - :rtype: bytes + For an explanation of the Argon2 parameters see + :class:`argon2.PasswordHasher`. - :raises argon2.exceptions.HashingError: If hashing fails. + Returns: + An encoded Argon2 hash. + + Raises: + argon2.exceptions.HashingError: If hashing fails. .. versionadded:: 16.0.0 .. _salt: https://en.wikipedia.org/wiki/Salt_(cryptography) - .. _kibibytes: https://en.wikipedia.org/wiki/Binary_prefix#kibi """ size = ( lib.argon2_encodedlen( @@ -127,19 +117,19 @@ def hash_secret( if rv != lib.ARGON2_OK: raise HashingError(error_to_str(rv)) - return ffi.string(buf) + return ffi.string(buf) # type: ignore[no-any-return] def hash_secret_raw( - secret, - salt, - time_cost, - memory_cost, - parallelism, - hash_len, - type, - version=ARGON2_VERSION, -): + secret: bytes, + salt: bytes, + time_cost: int, + memory_cost: int, + parallelism: int, + hash_len: int, + type: Type, + version: int = ARGON2_VERSION, +) -> bytes: """ Hash *password* and return a **raw** hash. @@ -170,24 +160,30 @@ def hash_secret_raw( return bytes(ffi.buffer(buf, hash_len)) -def verify_secret(hash, secret, type): +def verify_secret(hash: bytes, secret: bytes, type: Type) -> Literal[True]: """ Verify whether *secret* is correct for *hash* of *type*. - :param bytes hash: An encoded Argon2 hash as returned by - :func:`hash_secret`. - :param bytes secret: The secret to verify whether it matches the one - in *hash*. - :param Type type: Type for *hash*. + Args: + hash: + An encoded Argon2 hash as returned by :func:`hash_secret`. + + secret: + The secret to verify whether it matches the one in *hash*. + + type: Type for *hash*. + + Raises: + argon2.exceptions.VerifyMismatchError: + If verification fails because *hash* is not valid for *secret* of + *type*. - :raises argon2.exceptions.VerifyMismatchError: If verification fails - because *hash* is not valid for *secret* of *type*. - :raises argon2.exceptions.VerificationError: If verification fails for - other reasons. + argon2.exceptions.VerificationError: + If verification fails for other reasons. - :return: ``True`` on success, raise - :exc:`~argon2.exceptions.VerificationError` otherwise. - :rtype: bool + Returns: + ``True`` on success, raise :exc:`~argon2.exceptions.VerificationError` + otherwise. .. versionadded:: 16.0.0 .. versionchanged:: 16.1.0 @@ -200,52 +196,58 @@ def verify_secret(hash, secret, type): len(secret), type.value, ) + if rv == lib.ARGON2_OK: return True - elif rv == lib.ARGON2_VERIFY_MISMATCH: + + if rv == lib.ARGON2_VERIFY_MISMATCH: raise VerifyMismatchError(error_to_str(rv)) - else: - raise VerificationError(error_to_str(rv)) + raise VerificationError(error_to_str(rv)) -def core(context, type): + +def core(context: Any, type: int) -> int: """ Direct binding to the ``argon2_ctx`` function. .. warning:: This is a strictly advanced function working on raw C data structures. - Both Argon2's and ``argon2-cffi``'s higher-level bindings do a lot of + Both Argon2's and *argon2-cffi*'s higher-level bindings do a lot of sanity checks and housekeeping work that *you* are now responsible for (e.g. clearing buffers). The structure of the *context* object can, has, and will change with *any* release! - Use at your own peril; ``argon2-cffi`` does *not* use this binding + Use at your own peril; *argon2-cffi* does *not* use this binding itself. - :param context: A CFFI Argon2 context object (i.e. an ``struct - Argon2_Context``/``argon2_context``). - :param int type: Which Argon2 variant to use. You can use the ``value`` - field of :class:`Type`'s fields. + Args: + context: + A CFFI Argon2 context object (i.e. an ``struct Argon2_Context`` / + ``argon2_context``). + + type: + Which Argon2 variant to use. You can use the ``value`` field of + :class:`Type`'s fields. - :rtype: int - :return: An Argon2 error code. Can be transformed into a string using + Returns: + An Argon2 error code. Can be transformed into a string using :func:`error_to_str`. .. versionadded:: 16.0.0 """ - return lib.argon2_ctx(context, type) + return lib.argon2_ctx(context, type) # type: ignore[no-any-return] -def error_to_str(error): +def error_to_str(error: int) -> str: """ Convert an Argon2 error code into a native string. - :param int error: An Argon2 error code as returned by :func:`core`. + Args: + error: An Argon2 error code as returned by :func:`core`. - :rtype: str + Returns: + A human-readable string describing the error. .. versionadded:: 16.0.0 """ - msg = ffi.string(lib.argon2_error_message(error)) - msg = msg.decode("ascii") - return msg + return ffi.string(lib.argon2_error_message(error)).decode("ascii") # type: ignore[no-any-return] diff --git a/src/argon2/profiles.py b/src/argon2/profiles.py new file mode 100644 index 0000000..e6fd69b --- /dev/null +++ b/src/argon2/profiles.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: MIT + +""" +This module offers access to standardized parameters that you can load using +:meth:`argon2.PasswordHasher.from_parameters()`. See the `source code +`_ for +concrete values and :doc:`parameters` for more information. + +.. versionadded:: 21.2.0 +""" + +from __future__ import annotations + +import dataclasses + +from ._utils import Parameters, _is_wasm +from .low_level import Type + + +def get_default_parameters() -> Parameters: + """ + Create default parameters for current platform. + + Returns: + Default, compatible, parameters for current platform. + + .. versionadded:: 25.1.0 + """ + params = RFC_9106_LOW_MEMORY + + if _is_wasm(): + params = dataclasses.replace(params, parallelism=1) + + return params + + +# FIRST RECOMMENDED option per RFC 9106. +RFC_9106_HIGH_MEMORY = Parameters( + type=Type.ID, + version=19, + salt_len=16, + hash_len=32, + time_cost=1, + memory_cost=2097152, # 2 GiB + parallelism=4, +) + +# SECOND RECOMMENDED option per RFC 9106. +RFC_9106_LOW_MEMORY = Parameters( + type=Type.ID, + version=19, + salt_len=16, + hash_len=32, + time_cost=3, + memory_cost=65536, # 64 MiB + parallelism=4, +) + +# The pre-RFC defaults in argon2-cffi 18.2.0 - 21.1.0. +PRE_21_2 = Parameters( + type=Type.ID, + version=19, + salt_len=16, + hash_len=16, + time_cost=2, + memory_cost=102400, # 100 MiB + parallelism=8, +) + +# Only for testing! +CHEAPEST = Parameters( + type=Type.ID, + version=19, + salt_len=8, + hash_len=4, + time_cost=1, + memory_cost=8, + parallelism=1, +) diff --git a/src/argon2/py.typed b/src/argon2/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_legacy.py b/tests/test_legacy.py index 56ed5ff..af3a947 100644 --- a/tests/test_legacy.py +++ b/tests/test_legacy.py @@ -1,3 +1,5 @@ +# SPDX-License-Identifier: MIT + import pytest from hypothesis import given @@ -10,7 +12,6 @@ hash_password_raw, verify_password, ) -from argon2._utils import _encoded_str_len from argon2.exceptions import HashingError, VerificationError from .test_low_level import ( @@ -31,28 +32,41 @@ def test_hash_defaults(self): """ Calling without arguments works. """ - hash_password(b"secret") + with pytest.deprecated_call( + match="argon2.hash_password is deprecated" + ) as dc: + hash_password(b"secret") + + assert dc.pop().filename.endswith("test_legacy.py") def test_raw_defaults(self): """ Calling without arguments works. """ - hash_password_raw(b"secret") + with pytest.deprecated_call( + match="argon2.hash_password_raw is deprecated" + ) as dc: + hash_password_raw(b"secret") + + assert dc.pop().filename.endswith("test_legacy.py") @i_and_d_encoded def test_hash_password(self, type, hash): """ Creates the same encoded hash as the Argon2 CLI client. """ - rv = hash_password( - TEST_PASSWORD, - TEST_SALT, - TEST_TIME, - TEST_MEMORY, - TEST_PARALLELISM, - TEST_HASH_LEN, - type, - ) + with pytest.deprecated_call( + match="argon2.hash_password is deprecated" + ): + rv = hash_password( + TEST_PASSWORD, + TEST_SALT, + TEST_TIME, + TEST_MEMORY, + TEST_PARALLELISM, + TEST_HASH_LEN, + type, + ) assert hash == rv assert isinstance(rv, bytes) @@ -62,15 +76,18 @@ def test_hash_password_raw(self, type, hash): """ Creates the same raw hash as the Argon2 CLI client. """ - rv = hash_password_raw( - TEST_PASSWORD, - TEST_SALT, - TEST_TIME, - TEST_MEMORY, - TEST_PARALLELISM, - TEST_HASH_LEN, - type, - ) + with pytest.deprecated_call( + match="argon2.hash_password_raw is deprecated" + ): + rv = hash_password_raw( + TEST_PASSWORD, + TEST_SALT, + TEST_TIME, + TEST_MEMORY, + TEST_PARALLELISM, + TEST_HASH_LEN, + type, + ) assert hash == rv assert isinstance(rv, bytes) @@ -79,34 +96,47 @@ def test_hash_nul_bytes(self): """ Hashing passwords with NUL bytes works as expected. """ - rv = hash_password_raw(b"abc\x00", TEST_SALT) + with pytest.deprecated_call( + match="argon2.hash_password_raw is deprecated" + ): + rv = hash_password_raw(b"abc\x00", TEST_SALT) - assert rv != hash_password_raw(b"abc", TEST_SALT) + with pytest.deprecated_call( + match="argon2.hash_password_raw is deprecated" + ): + assert rv != hash_password_raw(b"abc", TEST_SALT) def test_random_salt(self): """ Omitting a salt, creates a random one. """ - rv = hash_password(b"secret") + with pytest.deprecated_call( + match="argon2.hash_password is deprecated" + ): + rv = hash_password(b"secret") salt = rv.split(b",")[-1].split(b"$")[1] + assert ( # -1 for not NUL byte - int(_encoded_str_len(DEFAULT_RANDOM_SALT_LENGTH)) - 1 - == len(salt) + int((DEFAULT_RANDOM_SALT_LENGTH << 2) / 3 + 2) - 1 == len(salt) ) def test_hash_wrong_arg_type(self): """ Passing an argument of wrong type raises TypeError. """ - with pytest.raises(TypeError): + with pytest.deprecated_call( + match="argon2.hash_password is deprecated" + ), pytest.raises(TypeError): hash_password("oh no, unicode!") def test_illegal_argon2_parameter(self): """ Raises HashingError if hashing fails. """ - with pytest.raises(HashingError): + with pytest.deprecated_call( + match="argon2.hash_password is deprecated" + ), pytest.raises(HashingError): hash_password(TEST_PASSWORD, memory_cost=1) @given(st.binary(max_size=128)) @@ -114,14 +144,17 @@ def test_hash_fast(self, password): """ Hash various passwords as cheaply as possible. """ - hash_password( - password, - salt=b"12345678", - time_cost=1, - memory_cost=8, - parallelism=1, - hash_len=8, - ) + with pytest.deprecated_call( + match="argon2.hash_password is deprecated" + ): + hash_password( + password, + salt=b"12345678", + time_cost=1, + memory_cost=8, + parallelism=1, + hash_len=8, + ) class TestVerify: @@ -130,18 +163,27 @@ def test_success(self, type, hash): """ Given a valid hash and password and correct type, we succeed. """ - assert True is verify_password(hash, TEST_PASSWORD, type) + with pytest.deprecated_call( + match="argon2.verify_password is deprecated" + ) as dc: + assert True is verify_password(hash, TEST_PASSWORD, type) + + assert dc.pop().filename.endswith("test_legacy.py") def test_fail_wrong_argon2_type(self): """ Given a valid hash and password and wrong type, we fail. """ - with pytest.raises(VerificationError): + with pytest.deprecated_call( + match="argon2.verify_password is deprecated" + ), pytest.raises(VerificationError): verify_password(TEST_HASH_I, TEST_PASSWORD, Type.D) def test_wrong_arg_type(self): """ Passing an argument of wrong type raises TypeError. """ - with pytest.raises(TypeError): + with pytest.deprecated_call( + match="argon2.verify_password is deprecated" + ), pytest.raises(TypeError): verify_password(TEST_HASH_I, TEST_PASSWORD.decode("ascii")) diff --git a/tests/test_low_level.py b/tests/test_low_level.py index 2f685fc..3c0b550 100644 --- a/tests/test_low_level.py +++ b/tests/test_low_level.py @@ -1,3 +1,5 @@ +# SPDX-License-Identifier: MIT + import binascii import os @@ -93,11 +95,11 @@ TEST_HASH_LEN = 32 i_and_d_encoded = pytest.mark.parametrize( - "type,hash", + ("type", "hash"), [(Type.I, TEST_HASH_I), (Type.D, TEST_HASH_D), (Type.ID, TEST_HASH_ID)], ) i_and_d_raw = pytest.mark.parametrize( - "type,hash", + ("type", "hash"), [(Type.I, TEST_RAW_I), (Type.D, TEST_RAW_D), (Type.ID, TEST_RAW_ID)], ) @@ -183,13 +185,15 @@ def test_illegal_argon2_parameter(self, func): Type.I, ) - @both_hash_funcs - @given(st.binary(max_size=128)) + @given( + st.sampled_from((hash_secret, hash_secret_raw)), + st.binary(max_size=128), + ) def test_hash_fast(self, func, secret): """ Hash various secrets as cheaply as possible. """ - hash_secret( + func( secret, salt=b"12345678", time_cost=1, @@ -292,40 +296,37 @@ def test_core(): ctx = ffi.new( "argon2_context *", - dict( - out=cout, - outlen=hash_len, - version=ARGON2_VERSION, - pwd=cpwd, - pwdlen=len(pwd), - salt=csalt, - saltlen=len(salt), - secret=ffi.NULL, - secretlen=0, - ad=ffi.NULL, - adlen=0, - t_cost=1, - m_cost=8, - lanes=1, - threads=1, - allocate_cbk=ffi.NULL, - free_cbk=ffi.NULL, - flags=lib.ARGON2_DEFAULT_FLAGS, - ), + { + "out": cout, + "outlen": hash_len, + "version": ARGON2_VERSION, + "pwd": cpwd, + "pwdlen": len(pwd), + "salt": csalt, + "saltlen": len(salt), + "secret": ffi.NULL, + "secretlen": 0, + "ad": ffi.NULL, + "adlen": 0, + "t_cost": 1, + "m_cost": 8, + "lanes": 1, + "threads": 1, + "allocate_cbk": ffi.NULL, + "free_cbk": ffi.NULL, + "flags": lib.ARGON2_DEFAULT_FLAGS, + }, ) rv = core(ctx, Type.D.value) assert 0 == rv - assert ( - hash_secret_raw( - pwd, - salt=salt, - time_cost=1, - memory_cost=8, - parallelism=1, - hash_len=hash_len, - type=Type.D, - ) - == bytes(ffi.buffer(ctx.out, ctx.outlen)) - ) + assert hash_secret_raw( + pwd, + salt=salt, + time_cost=1, + memory_cost=8, + parallelism=1, + hash_len=hash_len, + type=Type.D, + ) == bytes(ffi.buffer(ctx.out, ctx.outlen)) diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 0000000..60db130 --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,50 @@ +# SPDX-License-Identifier: MIT + + +from importlib import metadata + +import pytest + +import argon2 + + +class TestLegacyMetadataHack: + def test_version(self): + """ + argon2.__version__ returns the correct version. + """ + with pytest.deprecated_call(): + assert metadata.version("argon2-cffi") == argon2.__version__ + + def test_description(self): + """ + argon2.__description__ returns the correct description. + """ + with pytest.deprecated_call(): + assert "Argon2 for Python" == argon2.__description__ + + def test_uri(self): + """ + argon2.__uri__ returns the correct project URL. + """ + with pytest.deprecated_call(): + assert "https://argon2-cffi.readthedocs.io/" == argon2.__uri__ + + with pytest.deprecated_call(): + assert "https://argon2-cffi.readthedocs.io/" == argon2.__url__ + + def test_email(self): + """ + argon2.__email__ returns Hynek's email address. + """ + with pytest.deprecated_call(): + assert "hs@ox.cx" == argon2.__email__ + + def test_does_not_exist(self): + """ + Asking for unsupported dunders raises an AttributeError. + """ + with pytest.raises( + AttributeError, match="module argon2 has no attribute __yolo__" + ): + argon2.__yolo__ # noqa: B018 diff --git a/tests/test_password_hasher.py b/tests/test_password_hasher.py index ca14953..90adc1a 100644 --- a/tests/test_password_hasher.py +++ b/tests/test_password_hasher.py @@ -1,8 +1,22 @@ +# SPDX-License-Identifier: MIT + +import secrets +import sys +import threading + +from concurrent.futures import ThreadPoolExecutor +from unittest import mock + import pytest -from argon2 import PasswordHasher, Type, extract_parameters +from argon2 import PasswordHasher, Type, extract_parameters, profiles from argon2._password_hasher import _ensure_bytes -from argon2.exceptions import InvalidHash +from argon2._utils import Parameters +from argon2.exceptions import ( + InvalidHash, + InvalidHashError, + UnsupportedParametersError, +) class TestEnsureBytes: @@ -17,9 +31,9 @@ def test_is_bytes(self): assert isinstance(rv, bytes) assert s == rv - def test_is_unicode(self): + def test_is_str(self): """ - Unicode is encoded using the specified encoding. + Unicode str is encoded using the specified encoding. """ s = "föö" @@ -29,16 +43,16 @@ def test_is_unicode(self): assert s.encode("latin1") == rv -bytes_and_unicode_password = pytest.mark.parametrize( +bytes_and_str_password = pytest.mark.parametrize( "password", ["pässword".encode("latin1"), "pässword"] ) class TestPasswordHasher: - @bytes_and_unicode_password + @bytes_and_str_password def test_hash(self, password): """ - Hashing works with unicode and bytes. Uses correct parameters. + Hashing works with str and bytes. Uses correct parameters. """ ph = PasswordHasher(1, 8, 1, 16, 16, "latin1") @@ -49,10 +63,22 @@ def test_hash(self, password): assert isinstance(h, str) assert h[: len(prefix)] == prefix - @bytes_and_unicode_password + def test_custom_salt(self, password=b"password"): + """ + A custom salt can be specified. + """ + ph = PasswordHasher.from_parameters(profiles.CHEAPEST) + + h = ph.hash(password, salt=b"1234567890123456") + + assert h == ( + "$argon2id$v=19$m=8,t=1,p=1$MTIzNDU2Nzg5MDEyMzQ1Ng$maTa5w" + ) + + @bytes_and_str_password def test_verify_agility(self, password): """ - Verification works with unicode and bytes and variant is correctly + Verification works with str and bytes and variant is correctly detected. """ ph = PasswordHasher(1, 8, 1, 16, 16, "latin1") @@ -63,7 +89,7 @@ def test_verify_agility(self, password): assert ph.verify(hash, password) - @bytes_and_unicode_password + @bytes_and_str_password def test_hash_verify(self, password): """ Hashes are valid and can be verified. @@ -81,29 +107,46 @@ def test_check(self): assert "'time_cost' must be a int (got str)." == e.value.args[0] + def test_verify_invalid_hash_error(self): + """ + If the hash can't be parsed, InvalidHashError is raised. + """ + with pytest.raises(InvalidHashError): + PasswordHasher().verify("tiger", "does not matter") + def test_verify_invalid_hash(self): """ - If the hash can't be parsed, InvalidHash is raised. + InvalidHashError and the deprecrated InvalidHash are the same. """ with pytest.raises(InvalidHash): PasswordHasher().verify("tiger", "does not matter") - def test_check_needs_rehash_no(self): + @pytest.mark.parametrize("use_bytes", [True, False]) + def test_check_needs_rehash_no(self, use_bytes): """ Return False if the hash has the correct parameters. """ ph = PasswordHasher(1, 8, 1, 16, 16) - assert not ph.check_needs_rehash(ph.hash("foo")) + hash = ph.hash("foo") + if use_bytes: + hash = hash.encode() + + assert not ph.check_needs_rehash(hash) - def test_check_needs_rehash_yes(self): + @pytest.mark.parametrize("use_bytes", [True, False]) + def test_check_needs_rehash_yes(self, use_bytes): """ Return True if any of the parameters changes. """ ph = PasswordHasher(1, 8, 1, 16, 16) ph_old = PasswordHasher(1, 8, 1, 8, 8) - assert ph.check_needs_rehash(ph_old.hash("foo")) + hash = ph_old.hash("foo") + if use_bytes: + hash = hash.encode() + + assert ph.check_needs_rehash(hash) def test_type_is_configurable(self): """ @@ -120,3 +163,74 @@ def test_type_is_configurable(self): assert Type.I is ph.type is ph._parameters.type assert Type.I is extract_parameters(ph.hash("foo")).type assert ph.check_needs_rehash(default_hash) + + @mock.patch("sys.platform", "emscripten") + @pytest.mark.parametrize("machine", ["wasm32", "wasm64"]) + def test_params_on_wasm(self, machine): + """ + Parameter validation catches invalid parameters on WebAssembly. + """ + with mock.patch("platform.machine", return_value=machine): + with pytest.raises( + UnsupportedParametersError, + match="In WebAssembly environments `parallelism` must be 1.", + ): + PasswordHasher(parallelism=2) + + # last param is parallelism so it should fail + params = Parameters(Type.I, 2, 8, 8, 3, 256, 8) + with pytest.raises( + UnsupportedParametersError, + match="In WebAssembly environments `parallelism` must be 1.", + ): + ph = PasswordHasher.from_parameters(params) + + # explicitly correct parameters + ph = PasswordHasher(parallelism=1) + + hash = ph.hash("hello") + + assert ph.verify(hash, "hello") is True + + # explicit, but still default parameters + default_params = profiles.get_default_parameters() + ph = PasswordHasher.from_parameters(default_params) + + hash = ph.hash("hello") + + assert ph.verify(hash, "hello") is True + + +def test_multithreaded_hashing(): + """ + Hash passwords in a thread pool and check for thread safety + """ + hasher = PasswordHasher(parallelism=2) + + num_passwords = 100 + + passwords = [secrets.token_urlsafe(15) for _ in range(num_passwords)] + + def closure(b, passwords): + b.wait() + for password in passwords: + assert hasher.verify(hasher.hash(password), password) + + max_workers = 4 + + chunks = [passwords[i::max_workers] for i in range(max_workers)] + orig_interval = sys.getswitchinterval() + + with ThreadPoolExecutor(max_workers=max_workers) as tpe: + barrier = threading.Barrier(max_workers) + futures = [] + try: + sys.setswitchinterval(0.00001) + for chunk in chunks: + futures.append(tpe.submit(closure, barrier, chunk)) # noqa: PERF401 + finally: + sys.setswitchinterval(orig_interval) + if len(futures) < max_workers: + barrier.abort() + for f in futures: + f.result() diff --git a/tests/test_utils.py b/tests/test_utils.py index 47af269..9ad541c 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,4 +1,7 @@ +# SPDX-License-Identifier: MIT + from base64 import b64encode +from dataclasses import replace import pytest @@ -7,7 +10,7 @@ from argon2 import Parameters, Type, extract_parameters from argon2._utils import NoneType, _check_types, _decoded_str_len -from argon2.exceptions import InvalidHash +from argon2.exceptions import InvalidHashError class TestCheckTypes: @@ -103,24 +106,24 @@ def test_invalid_hash(self, hash): """ Invalid hashes of various types raise an InvalidHash error. """ - with pytest.raises(InvalidHash): + with pytest.raises(InvalidHashError): extract_parameters(hash) class TestParameters: def test_eq(self): """ - Parameters are iff every attribute is equal. + Parameters are equal iff every attribute is equal. """ - assert VALID_PARAMETERS == VALID_PARAMETERS - assert not VALID_PARAMETERS != VALID_PARAMETERS + assert VALID_PARAMETERS == VALID_PARAMETERS # noqa: PLR0124 + assert VALID_PARAMETERS != replace(VALID_PARAMETERS, salt_len=9) def test_eq_wrong_type(self): """ Parameters are only compared if they have the same type. """ assert VALID_PARAMETERS != "foo" - assert not VALID_PARAMETERS == object() + assert VALID_PARAMETERS != object() def test_repr(self): """ @@ -136,9 +139,7 @@ def test_repr(self): time_cost=2, parallelism=4, ) - ) in [ - ", version=19, hash_len=32, " - "salt_len=8, time_cost=2, memory_cost=65536, parallelism=4)>", - "", - ] + ) == ( + "Parameters(type=, version=19, salt_len=8, " + "hash_len=32, time_cost=2, memory_cost=65536, parallelism=4)" + ) diff --git a/tests/typing/api.py b/tests/typing/api.py new file mode 100644 index 0000000..6aadffd --- /dev/null +++ b/tests/typing/api.py @@ -0,0 +1,19 @@ +import argon2 + + +argon2.PasswordHasher.from_parameters(argon2.profiles.RFC_9106_HIGH_MEMORY) +ph = argon2.PasswordHasher() + +ph.hash("pw") +ph.hash("pw", salt=b"salt") +ph.hash(b"pw") +ph.hash(b"pw", salt=b"salt") +ph.verify("hash", "pw") +ph.verify(b"hash", "pw") +ph.verify(b"hash", b"pw") +ph.verify("hash", b"pw") + +if ph.check_needs_rehash("hash") is True: + ... + +params: argon2.Parameters = argon2.profiles.get_default_parameters() diff --git a/tox.ini b/tox.ini index 2983715..975a61f 100644 --- a/tox.ini +++ b/tox.ini @@ -1,93 +1,112 @@ -[flake8] -exclude = src/argon2/_ffi.py -ignore = - # Ambiguous variable names - # Ignored, since there is an enum value "I" for the algorithm type Argon2I - E741 - # Not an actual PEP8 violation - W503 - # Black vs flake8 conflict - E203 - - -[gh-actions] -python = - 3.5: py35 - 3.6: py36 - 3.7: py37, docs - 3.8: py38, lint - 3.9: py39, manifest - 3.10: py310 - pypy3: pypy3 - - [tox] -envlist = lint,py35,py36,py37,py38,py39,py310,pypy3,system-argon2,docs,manifest,pypi-description,coverage-report -isolated_build = true +min_version = 4 +env_list = + pre-commit, + mypy-pkg, + py3{8,9,10,11,12,13,14}-{tests,mypy} + py312-bindings-main, + pypy3-tests, + system-argon2, + docs-doctests, + coverage-report -[testenv:lint] -description = Run all pre-commit hooks. -basepython = python3.8 -skip_install = true -deps = pre-commit -passenv = HOMEPATH # needed on Windows -commands = pre-commit run --all-files --show-diff +[testenv] +description = Run tests / check types and do NOT measure coverage. +package = wheel +wheel_build_env = .pkg +dependency_groups = + tests: tests + mypy: typing +pass_env = + FORCE_COLOR + NO_COLOR +commands = + tests: pytest {posargs} + tests: python -Im argon2 -n 1 -t 1 -m 8 -p 1 + mypy: mypy tests/typing -[testenv] +[testenv:py3{8,13}-tests] description = Run tests and measure coverage. -extras = tests +deps = + coverage[toml] commands = - coverage run --parallel -m pytest {posargs} - coverage run --parallel -m argon2 -n 1 -t 1 -m 8 -p 1 + coverage run -m pytest {posargs} + coverage run -m argon2 -n 1 -t 1 -m 8 -p 1 + coverage run -m argon2 --profile CHEAPEST + + +[testenv:coverage-report] +description = Report coverage over all test runs. +skip_install = true +depends = py3{8,13}-tests +deps = coverage[toml] +parallel_show_output = true +commands = + coverage combine + coverage report [testenv:system-argon2] description = Run tests against bindings that use a system installation of Argon2. -basepython = python3.8 -setenv = ARGON2_CFFI_USE_SYSTEM=1 -extras = tests -install_command = pip install {opts} --no-binary=argon2-cffi {packages} -commands = - python -m pytest {posargs} - python -m argon2 -n 1 -t 1 -m 8 -p 1 +set_env = ARGON2_CFFI_USE_SYSTEM=1 +install_command = pip install {opts} --no-binary=argon2-cffi-bindings {packages} -[testenv:docs] -description = Build docs and run doctests. -# Keep basepython in sync with gh-actions and .readthedocs.yml. -basepython = python3.7 -extras = docs -commands = - python -m doctest README.rst - sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html - sphinx-build -W -b doctest -d {envtmpdir}/doctrees docs docs/_build/html +[testenv:py312-bindings-main] +description = Run tests against the current main branch of argon2-cffi-bindings +dependency_groups = +deps = +commands_pre = pip install -I hypothesis pytest git+https://github.com/hynek/argon2-cffi-bindings +install_command = pip install {opts} --no-deps {packages} -[testenv:manifest] -description = Ensure MANIFEST.in is up to date. -deps = check-manifest +[testenv:pre-commit] +description = Run all pre-commit hooks. skip_install = true -commands = check-manifest +deps = pre-commit-uv +commands = pre-commit run --all-files -[testenv:pypi-description] -description = Ensure README.rst renders on PyPI. -skip_install = true -deps = - twine - pip >= 18.0.0 +[testenv:pyright] +deps = pyright +dependency_groups = typing +commands = pyright tests/typing src + + +[testenv:mypy-pkg] +description = Check own code. +deps = mypy +commands = mypy src + + +[testenv:docs-{build,doctests,linkcheck}] +# Keep base_python in sync with .readthedocs.yaml. +base_python = py313 +dependency_groups = docs commands = - pip wheel -w {envtmpdir}/build --no-deps . - twine check {envtmpdir}/build/* + build: sphinx-build -n -T -W -b html -d {envtmpdir}/doctrees docs {posargs:docs/_build/}html + doctests: python -m doctest README.md + doctests: sphinx-build -n -T -W -b doctest -d {envtmpdir}/doctrees docs {posargs:docs/_build/}html + linkcheck: sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/html -[testenv:coverage-report] -description = Report coverage over all test runs. -basepython = python3.8 -deps = coverage[toml]>=5.0.2 -skip_install = true +[testenv:docs-watch] +package = editable +base_python = {[testenv:docs-build]base_python} +dependency_groups = {[testenv:docs-build]dependency_groups} +deps = watchfiles commands = - coverage combine - coverage report + watchfiles \ + --ignore-paths docs/_build/ \ + 'sphinx-build -W -n --jobs auto -b html -d {envtmpdir}/doctrees docs docs/_build/html' \ + src \ + docs \ + README.md \ + CHANGELOG.md + +[testenv:docs-linkcheck] +base_python = {[testenv:docs]base_python} +dependency_groups = {[testenv:docs]dependency_groups} +commands = sphinx-build -W -b linkcheck -d {envtmpdir}/doctrees docs docs/_build/html diff --git a/zizmor.yml b/zizmor.yml new file mode 100644 index 0000000..1bab80b --- /dev/null +++ b/zizmor.yml @@ -0,0 +1,10 @@ +--- +rules: + unpinned-uses: + config: + policies: + # We trust GitHub, the PyPA, and ourselves. + "actions/*": ref-pin + "github/*": ref-pin + "pypa/*": ref-pin + "hynek/*": ref-pin