Skip to content

Commit

Permalink
apply ruff format
Browse files Browse the repository at this point in the history
  • Loading branch information
maksyutov.vlad committed Sep 13, 2024
1 parent 8c34109 commit 3307b6e
Show file tree
Hide file tree
Showing 46 changed files with 149 additions and 30 deletions.
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
warnings.filterwarnings("ignore", category=DeprecationWarning, module="passlib[.].*")



# read env var for tags, needed since "python setup.py build_sphinx"
# doesn't support sphinx-build's "-t" option.
for _tag in os.environ.get("SPHINX_BUILD_TAGS", "").split():
Expand Down
6 changes: 6 additions & 0 deletions passlib/apache.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class _CommonFile(object):
#: list of tokens for recreating original file contents when saving. if present,
#: will be sequence of (_SKIPPED, b"whitespace/comments") and (_RECORD, <record key>) tuples.
_source = None

@classmethod
def from_string(cls, data, **kwds):
"""create new object from raw string.
Expand Down Expand Up @@ -93,6 +94,7 @@ def from_path(cls, path: PathLike, **kwds):
self = cls(**kwds)
self.load(path)
return self

# XXX: add a new() classmethod, ala TOTP.new()?

def __init__(
Expand Down Expand Up @@ -151,6 +153,7 @@ def path(self, value):
def mtime(self):
"""modify time when last loaded (if bound to a local file)"""
return self._mtime

def load_if_changed(self):
"""Reload from ``self.path`` only if file has changed since last load"""
if not self._path:
Expand Down Expand Up @@ -249,6 +252,7 @@ def _set_record(self, key, value):
if not existing:
self._source.append((_RECORD, key))
return existing

def _autosave(self):
"""subclass helper to call save() after any changes"""
if self.autosave and self._path:
Expand Down Expand Up @@ -311,6 +315,7 @@ def _iter_lines(self):
def _render_record(self, key, value): # pragma: no cover - abstract method
"""given key/value pair, encode as line of file"""
raise NotImplementedError("should be implemented in subclass")

def _encode_user(self, user):
"""user-specific wrapper for _encode_field()"""
return self._encode_field(user, "user")
Expand Down Expand Up @@ -913,6 +918,7 @@ class HtdigestFile(_CommonFile):
# optionally specify default realm that will be used if none
# is provided to a method call. otherwise realm is always required.
default_realm = None

def __init__(self, path=None, default_realm=None, **kwds):
self.default_realm = default_realm
super().__init__(path, **kwds)
Expand Down
6 changes: 6 additions & 0 deletions passlib/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ class _CryptConfig(object):
# dict mapping category -> list of custom handler instances for that category,
# in order of schemes(). populated on demand by _get_record_list()
_record_lists = None

def __init__(self, source):
self._init_scheme_list(source.get((None, None, "schemes")))
self._init_options(source)
Expand Down Expand Up @@ -369,6 +370,7 @@ def get_scheme_options_with_flag(self, scheme, category):
has_cat_options = True

return kwds, has_cat_options

def _init_default_schemes(self):
"""initialize maps containing default scheme for each category.
Expand Down Expand Up @@ -447,6 +449,7 @@ def test(cat):
if alt is not None and value != alt:
return alt, True
return value, False

def _init_records(self):
# NOTE: this step handles final validation of settings,
# checking for violations against handler's internal invariants.
Expand Down Expand Up @@ -610,6 +613,7 @@ def disabled_record(self):
"no disabled hasher present "
"(perhaps add 'unix_disabled' to list of schemes?)"
)

def iter_config(self, resolve=False):
"""regenerate original config.
Expand Down Expand Up @@ -657,6 +661,7 @@ def iter_config(self, resolve=False):
for key in sorted(kwds):
yield (cat, scheme, key), kwds[key]


class CryptContext(object):
"""Helper for hashing & verifying passwords using multiple algorithms.
Expand Down Expand Up @@ -692,6 +697,7 @@ class CryptContext(object):
# copy of _config methods, stored in CryptContext instance for speed.
_get_record = None
_identify_record = None

@classmethod
def _norm_source(cls, source):
"""internal helper - accepts string, dict, or context"""
Expand Down
3 changes: 0 additions & 3 deletions passlib/crypto/_blowfish/_gen_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,6 @@ def expand(self, key_words):
)




def main():
target = os.path.join(os.path.dirname(__file__), "unrolled.py")
with open(target, "w") as fh:
Expand Down Expand Up @@ -241,4 +239,3 @@ class BlowfishEngine(_BlowfishEngine):

if __name__ == "__main__":
main()

4 changes: 3 additions & 1 deletion passlib/crypto/_blowfish/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,7 @@ def __init__(self):
_init_constants()
self.P = list(BLOWFISH_P)
self.S = [list(box) for box in BLOWFISH_S]

@staticmethod
def key_to_words(data, size=18):
"""convert data to tuple of <size> 4-byte integers, repeating or
Expand All @@ -1105,6 +1106,7 @@ def key_to_words(data, size=18):

# unpack
return struct.unpack(">%dI" % (size,), data)

def encipher(self, l, r):
"""loop version of blowfish encipher routine"""
P, S = self.P, self.S
Expand Down Expand Up @@ -1153,6 +1155,7 @@ def expand(self, key_words):
while i < 256:
box[i], box[i + 1] = l, r = encipher(l, r)
i += 2

def eks_salted_expand(self, key_words, salt_words):
"""perform EKS' salted version of Blowfish keyschedule setup"""
# NOTE: this is the same as expand(), except for the addition
Expand Down Expand Up @@ -1207,4 +1210,3 @@ def repeat_encipher(self, l, r, count):
l, r = encipher(l, r)
n += 1
return l, r

3 changes: 0 additions & 3 deletions passlib/crypto/des.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
]



# masks/upper limits for various integer sizes
INT_24_MASK = 0xFFFFFF
INT_56_MASK = 0xFFFFFFFFFFFFFF
Expand All @@ -67,7 +66,6 @@
_KS_MASK = 0xFCFCFCFCFFFFFFFF



# placeholders filled in by _load_tables()
PCXROT = IE3264 = SPE = CF6464 = None

Expand Down Expand Up @@ -1998,7 +1996,6 @@ def _unpack56(value):
return _uint64_struct.unpack(b"\x00" + value)[0]



##def expand_7bit(value):
## "expand 7-bit integer => 7-bits + 1 odd-parity bit"
## # parity calc adapted from 32-bit even parity alg found at
Expand Down
1 change: 1 addition & 0 deletions passlib/crypto/digest.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ def const(source=b""):
% (self.name, const, hash.name),
exc.PasslibRuntimeWarning,
)

def __repr__(self):
return "<lookup_hash(%r): digest_size=%r block_size=%r)" % (
self.name,
Expand Down
5 changes: 5 additions & 0 deletions passlib/crypto/scrypt/_builtin.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,12 @@ class ScryptEngine(object):
bmix_half_len = 0
bmix_struct = None
integerify = None

@classmethod
def execute(cls, secret, salt, n, r, p, keylen):
"""create engine & run scrypt() hash calculation"""
return cls(n, r, p).run(secret, salt, keylen)

def __init__(self, n, r, p):
# store config
self.n = n
Expand Down Expand Up @@ -73,6 +75,7 @@ def integerify(X):
return ig1(X) | (ig2(X) << 32)

self.integerify = integerify

def run(self, secret, salt, keylen):
"""
run scrypt kdf for specified secret, salt, and keylen
Expand Down Expand Up @@ -102,6 +105,7 @@ def run(self, secret, salt, keylen):

# stretch final byte array into output via pbkdf2
return pbkdf2_hmac("sha256", secret, output, rounds=1, keylen=keylen)

def smix(self, input):
"""run SCrypt smix function on a single input block
Expand Down Expand Up @@ -166,6 +170,7 @@ def vgen():

# repack tmp
return bmix_struct.pack(*buffer)

def bmix(self, source, target):
"""
block mixing function used by smix()
Expand Down
1 change: 0 additions & 1 deletion passlib/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,6 @@ def ChecksumSizeError(handler, raw=False):
return MalformedHashError(handler, reason)



#: global flag, set temporarily by UTs to allow debug_only_repr() to display sensitive values.
ENABLE_DEBUG_ONLY_REPR = False

Expand Down
7 changes: 7 additions & 0 deletions passlib/ext/django/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ def resolve_django_hasher(self, django_name, cached=True):
# lookup corresponding django hasher
return self.passlib_to_django(passlib_hasher, cached=cached)


class DjangoContextAdapter(DjangoTranslator):
"""
Object which tries to adapt a Passlib CryptContext object,
Expand Down Expand Up @@ -434,6 +435,7 @@ class DjangoContextAdapter(DjangoTranslator):

#: patch status
patched = False

def __init__(self, context=None, get_user_category=None, **kwds):
# init log
self.log = logging.getLogger(__name__ + ".DjangoContextAdapter")
Expand Down Expand Up @@ -804,6 +806,7 @@ def _load_settings(self):
self.context.load(config)
self.reset_hashers()


_GEN_SALT_SIGNAL = "--!!!generate-new-salt!!!--"


Expand Down Expand Up @@ -857,6 +860,7 @@ def __init__(self, passlib_handler):
if self._has_rounds:
self.rounds = passlib_handler.default_rounds
self.iterations = ProxyProperty("rounds")

def __repr__(self):
return "<PasslibHasherWrapper handler=%r>" % self.passlib_handler

Expand All @@ -882,6 +886,7 @@ def _translate_kwds(self):
@memoized_property
def algorithm(self):
return PASSLIB_WRAPPER_PREFIX + self.passlib_handler.name

def salt(self):
# NOTE: passlib's handler.hash() should generate new salt each time,
# so this just returns a special constant which tells
Expand Down Expand Up @@ -1054,6 +1059,7 @@ def _import_path(self, path):
def _is_same_value(left, right):
"""check if two values are the same (stripping method wrappers, etc)"""
return get_method_function(left) == get_method_function(right)

def _get_path(self, key, default=_UNSET):
obj, attr = self._import_path(key)
return getattr(obj, attr, default)
Expand Down Expand Up @@ -1081,6 +1087,7 @@ def check_all(self, strict=False):
raise RuntimeError(msg)
else:
warn(msg, PasslibRuntimeWarning)

def _set_path(self, path, value):
obj, attr = self._import_path(path)
if value is _UNSET:
Expand Down
3 changes: 3 additions & 0 deletions passlib/handlers/argon2.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,7 @@ def to_string(self):
bascii_to_str(b64s_encode(self.salt)),
bascii_to_str(b64s_encode(self.checksum)),
)

def __init__(
self, type=None, type_d=False, version=None, memory_cost=None, data=None, **kwds
):
Expand Down Expand Up @@ -682,6 +683,7 @@ class _NoBackend(_Argon2Common):
mixin used before any backend has been loaded.
contains stubs that force loading of one of the available backends.
"""

@classmethod
def hash(cls, secret):
cls._stub_requires_backend()
Expand All @@ -697,6 +699,7 @@ def verify(cls, secret, hash):
def genhash(cls, secret, config):
cls._stub_requires_backend()
return cls.genhash(secret, config)

def _calc_checksum(self, secret):
# NOTE: since argon2_cffi takes care of rendering hash,
# _calc_checksum() is only used by the argon2pure backend.
Expand Down
2 changes: 1 addition & 1 deletion passlib/handlers/bcrypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,7 @@ class _NoBackend(_BcryptCommon):
mixin used before any backend has been loaded.
contains stubs that force loading of one of the available backends.
"""

def _calc_checksum(self, secret):
self._stub_requires_backend()
# NOTE: have to use super() here so that we don't recursively
Expand Down Expand Up @@ -849,7 +850,6 @@ class bcrypt(_NoBackend, _BcryptCommon):
}



_UDOLLAR = "$"


Expand Down
2 changes: 2 additions & 0 deletions passlib/handlers/cisco.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class cisco_pix(uh.HasUserContext, uh.StaticHandler):

#: control flag signalling "cisco_asa" mode, set by cisco_asa class
_is_asa = False

def _calc_checksum(self, secret):
"""
This function implements the "encrypted" hash format used by Cisco
Expand Down Expand Up @@ -315,6 +316,7 @@ class cisco_type7(uh.GenericHandler):
# chars in size, not sure what appropriate behavior is for that edge case.
min_salt_value = 0
max_salt_value = 52

@classmethod
def using(cls, salt=None, **kwds):
subcls = super().using(**kwds)
Expand Down
8 changes: 7 additions & 1 deletion passlib/handlers/des_crypt.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,14 @@ def from_string(cls, hash):
def to_string(self):
hash = "%s%s" % (self.salt, self.checksum)
return hash

def _calc_checksum(self, secret):
# check for truncation (during .hash() calls only)
if self.use_defaults:
self._check_truncate_policy(secret)

return self._calc_checksum_backend(secret)

backends = ("os_crypt", "builtin")

# ---------------------------------------------------------------
Expand Down Expand Up @@ -251,6 +253,7 @@ class bsdi_crypt(uh.HasManyBackends, uh.HasRounds, uh.HasSalt, uh.GenericHandler
:meth:`hash` will now issue a warning if an even number of rounds is used
(see :ref:`bsdi-crypt-security-issues` regarding weak DES keys).
"""

# --GenericHandler--
name = "bsdi_crypt"
setting_kwds = ("salt", "rounds")
Expand Down Expand Up @@ -332,6 +335,7 @@ def _calc_needs_update(self, **kwds):
return True
# hand off to base implementation
return super()._calc_needs_update(**kwds)

backends = ("os_crypt", "builtin")

# ---------------------------------------------------------------
Expand Down Expand Up @@ -393,6 +397,7 @@ class bigcrypt(uh.HasSalt, uh.GenericHandler):
.. versionadded:: 1.6
"""

# --GenericHandler--
name = "bigcrypt"
setting_kwds = ("salt",)
Expand Down Expand Up @@ -429,6 +434,7 @@ def _norm_checksum(self, checksum, relaxed=False):
if len(checksum) % 11:
raise uh.exc.InvalidHashError(self)
return checksum

def _calc_checksum(self, secret):
if isinstance(secret, str):
secret = secret.encode("utf-8")
Expand Down Expand Up @@ -516,6 +522,7 @@ def from_string(cls, hash):
def to_string(self):
hash = "%s%s" % (self.salt, self.checksum)
return hash

def _calc_checksum(self, secret):
if isinstance(secret, str):
secret = secret.encode("utf-8")
Expand Down Expand Up @@ -545,4 +552,3 @@ def _calc_checksum(self, secret):
# done
chk = h64big.encode_int64(result1) + h64big.encode_int64(result2)
return chk.decode("ascii")

Loading

0 comments on commit 3307b6e

Please sign in to comment.