Skip to content

Commit

Permalink
Ruff life
Browse files Browse the repository at this point in the history
  • Loading branch information
hynek committed Jun 2, 2023
1 parent 93850eb commit c1dfc95
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 46 deletions.
3 changes: 2 additions & 1 deletion src/argon2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ def __getattr__(name: str) -> str:

if name in ("__uri__", "__url__"):
return meta["Project-URL"].split(" ", 1)[-1]
elif name == "__email__":

if name == "__email__":
return meta["Author-email"].split("<", 1)[1].rstrip(">")

return meta[dunder_to_metadata[name]]
4 changes: 2 additions & 2 deletions src/argon2/_password_hasher.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from ._typing import Literal
from ._utils import Parameters, _check_types, extract_parameters
from .exceptions import InvalidHash
from .exceptions import InvalidHashError
from .low_level import Type, hash_secret, verify_secret
from .profiles import RFC_9106_LOW_MEMORY

Expand Down Expand Up @@ -209,7 +209,7 @@ def verify(
try:
hash_type = self._header_to_type[hash[:9]]
except LookupError:
raise InvalidHash()
raise InvalidHashError() from None

return verify_secret(
hash, _ensure_bytes(password, self.encoding), hash_type
Expand Down
24 changes: 12 additions & 12 deletions src/argon2/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from dataclasses import dataclass
from typing import Any

from .exceptions import InvalidHash
from .exceptions import InvalidHashError
from .low_level import Type


Expand Down Expand Up @@ -37,11 +37,11 @@ def _check_types(**kw: Any) -> str | None:
return None


def _decoded_str_len(l: int) -> int:
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
Expand All @@ -50,7 +50,7 @@ def _decoded_str_len(l: int) -> int:
else:
last_group_len = 0

return l // 4 * 3 + last_group_len
return length // 4 * 3 + last_group_len


@dataclass
Expand Down Expand Up @@ -79,15 +79,15 @@ class Parameters:
memory_cost: int
parallelism: int

__slots__ = [
__slots__ = (
"type",
"version",
"salt_len",
"hash_len",
"time_cost",
"memory_cost",
"parallelism",
]
)


_NAME_TO_TYPE = {"argon2id": Type.ID, "argon2i": Type.I, "argon2d": Type.D}
Expand All @@ -111,25 +111,25 @@ def extract_parameters(hash: str) -> Parameters:
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]]

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
raise InvalidHashError from None

if sorted(kvs.keys()) != _REQUIRED_KEYS:
raise InvalidHash
raise InvalidHashError

return Parameters(
type=type,
Expand Down
10 changes: 6 additions & 4 deletions src/argon2/low_level.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class Type(Enum):
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
I = lib.Argon2_i # noqa: E741
r"""
Argon2\ **i** uses data-independent memory access. Argon2i is slower as
it makes more passes over the memory to protect from tradeoff attacks.
Expand Down Expand Up @@ -206,12 +206,14 @@ def verify_secret(hash: bytes, secret: bytes, type: Type) -> Literal[True]:
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: Any, type: int) -> int:
Expand Down
40 changes: 20 additions & 20 deletions tests/test_low_level.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,26 +294,26 @@ 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)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_packaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,4 @@ def test_does_not_exist(self):
with pytest.raises(
AttributeError, match="module argon2 has no attribute __yolo__"
):
argon2.__yolo__
argon2.__yolo__ # noqa: B018
11 changes: 9 additions & 2 deletions tests/test_password_hasher.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from argon2 import PasswordHasher, Type, extract_parameters
from argon2._password_hasher import _ensure_bytes
from argon2.exceptions import InvalidHash
from argon2.exceptions import InvalidHash, InvalidHashError


class TestEnsureBytes:
Expand Down Expand Up @@ -83,9 +83,16 @@ 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")
Expand Down
8 changes: 4 additions & 4 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,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:
Expand Down Expand Up @@ -105,7 +105,7 @@ 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)


Expand All @@ -115,14 +115,14 @@ def test_eq(self):
Parameters are iff every attribute is equal.
"""
assert VALID_PARAMETERS == VALID_PARAMETERS
assert not VALID_PARAMETERS != VALID_PARAMETERS
assert VALID_PARAMETERS == VALID_PARAMETERS

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):
"""
Expand Down

0 comments on commit c1dfc95

Please sign in to comment.