Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Types #112

Merged
merged 2 commits into from
Dec 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@ What explicitly *may* change over time are the default hashing parameters and th

- 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

Expand Down
28 changes: 28 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[mypy]
# show error messages from unrelated files
follow_imports = normal

# suppress errors about unsatisfied imports
ignore_missing_imports = True

# be strict
check_untyped_defs = True
disallow_any_generics = True
disallow_incomplete_defs = True
disallow_untyped_calls = True
disallow_untyped_defs = True
no_implicit_optional = True
strict_optional = True
warn_no_return = True
warn_redundant_casts = True
warn_unreachable = True
warn_unused_ignores = True

# sometimes redefinition is just fine
allow_redefinition = True

[mypy-tests.*]
ignore_errors = True

[mypy-conftest]
ignore_errors = True
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ name = "argon2-cffi"
authors = [{name = "Hynek Schlawack", email = "[email protected]"}]
dynamic = ["version", "description"]
requires-python = ">=3.6"
dependencies = ["argon2-cffi-bindings", "dataclasses; python_version < '3.7'"]
dependencies = [
"argon2-cffi-bindings",
"dataclasses; python_version < '3.7'",
"typing-extensions; python_version < '3.8'", # c.f. _typing.py module
]
license = { file = "LICENSE" }
readme = "README.rst"
keywords = ["password", "hash", "hashing", "security"]
Expand Down
4 changes: 3 additions & 1 deletion src/argon2/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import sys
import timeit

from typing import List

from . import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
Expand All @@ -14,7 +16,7 @@
)


def main(argv):
def main(argv: List[str]) -> None:
parser = argparse.ArgumentParser(description="Benchmark Argon2.")
parser.add_argument(
"-n", type=int, default=100, help="Number of iterations to measure."
Expand Down
40 changes: 22 additions & 18 deletions src/argon2/_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,30 @@
Legacy mid-level functions.
"""


import os

from typing import Optional

from ._password_hasher import (
DEFAULT_HASH_LENGTH,
DEFAULT_MEMORY_COST,
DEFAULT_PARALLELISM,
DEFAULT_RANDOM_SALT_LENGTH,
DEFAULT_TIME_COST,
)
from ._typing import Literal
from .low_level import Type, hash_secret, hash_secret_raw, verify_secret


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: Optional[bytes] = 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.

Expand All @@ -40,14 +42,14 @@ 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: Optional[bytes] = 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.

Expand All @@ -61,7 +63,9 @@ 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.

Expand Down
42 changes: 25 additions & 17 deletions src/argon2/_password_hasher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

import os

from typing import Union

from ._typing import Literal
from ._utils import Parameters, _check_types, extract_parameters
from .exceptions import InvalidHash
from .low_level import Type, hash_secret, verify_secret
Expand All @@ -15,7 +18,7 @@
DEFAULT_PARALLELISM = RFC_9106_LOW_MEMORY.parallelism


def _ensure_bytes(s, encoding):
def _ensure_bytes(s: Union[bytes, str], encoding: str) -> bytes:
"""
Ensure *s* is a bytes string. Encode using *encoding* if it isn't.
"""
Expand Down Expand Up @@ -67,15 +70,18 @@ class PasswordHasher:
"""
__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),
Expand Down Expand Up @@ -114,30 +120,30 @@ def from_parameters(cls, params: Parameters) -> "PasswordHasher":
return ph

@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: Union[str, bytes]) -> str:
"""
Hash *password* and return an encoded hash.

Expand All @@ -164,7 +170,9 @@ def hash(self, password):
b"$argon2id": Type.ID,
}

def verify(self, hash, password):
def verify(
self, hash: Union[str, bytes], password: Union[str, bytes]
) -> Literal[True]:
"""
Verify that *password* matches *hash*.

Expand Down Expand Up @@ -207,7 +215,7 @@ def verify(self, hash, password):
hash, _ensure_bytes(password, self.encoding), hash_type
)

def check_needs_rehash(self, hash):
def check_needs_rehash(self, hash: str) -> bool:
"""
Check whether *hash* was created using the instance's parameters.

Expand Down
13 changes: 13 additions & 0 deletions src/argon2/_typing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# SPDX-License-Identifier: MIT

import sys


# try/except ImportError does NOT work.
# c.f. https://github.com/python/mypy/issues/8520
if sys.version_info >= (3, 8):
from typing import Literal
else:
from typing_extensions import Literal

__all__ = ["Literal"]
14 changes: 5 additions & 9 deletions src/argon2/_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: MIT

from dataclasses import dataclass
from typing import Any, Optional

from .exceptions import InvalidHash
from .low_level import Type
Expand All @@ -9,7 +10,7 @@
NoneType = type(None)


def _check_types(**kw):
def _check_types(**kw: Any) -> Optional[str]:
"""
Check each ``name: (value, types)`` in *kw*.

Expand All @@ -31,15 +32,10 @@ def _check_types(**kw):
if errors != []:
return ", ".join(errors) + "."


def _encoded_str_len(l):
"""
Compute how long a byte string of length *l* becomes if encoded to hex.
"""
return (l << 2) / 3 + 2
return None


def _decoded_str_len(l):
def _decoded_str_len(l: int) -> int:
"""
Compute how long an encoded string of length *l* becomes.
"""
Expand Down Expand Up @@ -96,7 +92,7 @@ class Parameters:
_REQUIRED_KEYS = sorted(("v", "m", "t", "p"))


def extract_parameters(hash):
def extract_parameters(hash: str) -> Parameters:
"""
Extract parameters from an encoded *hash*.

Expand Down
45 changes: 23 additions & 22 deletions src/argon2/low_level.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
module is full of land mines, dragons, and dinosaurs with laser guns.
"""


from enum import Enum
from typing import Any

from _argon2_cffi_bindings import ffi, lib

from ._typing import Literal
from .exceptions import HashingError, VerificationError, VerifyMismatchError


Expand Down Expand Up @@ -68,15 +69,15 @@ class Type(Enum):


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.

Expand Down Expand Up @@ -134,15 +135,15 @@ def hash_secret(


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.

Expand Down Expand Up @@ -173,7 +174,7 @@ 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*.

Expand Down Expand Up @@ -211,7 +212,7 @@ def verify_secret(hash, secret, type):
raise VerificationError(error_to_str(rv))


def core(context, type):
def core(context: Any, type: int) -> int:
"""
Direct binding to the ``argon2_ctx`` function.

Expand Down Expand Up @@ -239,7 +240,7 @@ def core(context, type):
return lib.argon2_ctx(context, type)


def error_to_str(error):
def error_to_str(error: int) -> str:
"""
Convert an Argon2 error code into a native string.

Expand Down
Loading