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

pre-commit: apply black formatting #174

Merged
merged 4 commits into from
Oct 31, 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
8 changes: 8 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
[flake8]
# Adjustments to comply with black autoformatting as described here:
# https://black.readthedocs.io/en/latest/guides/using_black_with_other_tools.html#flake8
#
extend-ignore = E203
max-line-length = 88

# Project specific adjustments
#
builtins =
c
6 changes: 2 additions & 4 deletions dev-jupyterhub_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@

c.NativeAuthenticator.allow_2fa = True

c.NativeAuthenticator.tos = (
'I agree to the <a href="your-url" target="_blank">TOS</a>.'
)
c.NativeAuthenticator.tos = 'I agree to the <a href="your-url" target="_blank">TOS</a>.'

# c.NativeAuthenticator.recaptcha_key = "your key"
# c.NativeAuthenticator.recaptcha_secret = "your secret"
Expand All @@ -50,5 +48,5 @@
# }

c.NativeAuthenticator.import_from_firstuse = False
c.NativeAuthenticator.firstuse_dbm_path = '/home/user/passwords.dbm'
c.NativeAuthenticator.firstuse_dbm_path = "/home/user/passwords.dbm"
c.NativeAuthenticator.delete_firstuse_db_after_import = False
65 changes: 38 additions & 27 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@
# sys.path.insert(0, os.path.abspath('.'))
# -- Project information -----------------------------------------------------

project = 'Native Authenticator'
copyright = '2021, Leticia Portella'
author = 'Leticia Portella'
project = "Native Authenticator"
copyright = "2021, Leticia Portella"
author = "Leticia Portella"

# The short X.Y version
version = ''
version = ""
# The full version, including alpha/beta/rc tags
release = ''
release = ""


# -- General configuration ---------------------------------------------------
Expand All @@ -33,20 +33,19 @@
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
]
extensions = []

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand All @@ -58,18 +57,18 @@
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"


# -- 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 = 'alabaster'
html_theme = "alabaster"

# 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
Expand All @@ -80,7 +79,7 @@
# 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']
html_static_path = ["_static"]

# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
Expand All @@ -96,7 +95,7 @@
# -- Options for HTMLHelp output ---------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'NativeAuthenticatordoc'
htmlhelp_basename = "NativeAuthenticatordoc"


# -- Options for LaTeX output ------------------------------------------------
Expand All @@ -105,15 +104,12 @@
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
Expand All @@ -123,9 +119,13 @@
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'NativeAuthenticator.tex',
'Native Authenticator Documentation',
'Leticia Portella', 'manual'),
(
master_doc,
"NativeAuthenticator.tex",
"Native Authenticator Documentation",
"Leticia Portella",
"manual",
),
]


Expand All @@ -134,8 +134,13 @@
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'nativeauthenticator', 'Native Authenticator Documentation',
[author], 1)
(
master_doc,
"nativeauthenticator",
"Native Authenticator Documentation",
[author],
1,
)
]


Expand All @@ -145,9 +150,15 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'NativeAuthenticator', 'Native Authenticator Documentation',
author, 'NativeAuthenticator', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"NativeAuthenticator",
"Native Authenticator Documentation",
author,
"NativeAuthenticator",
"One line description of project.",
"Miscellaneous",
),
]


Expand All @@ -166,4 +177,4 @@
# epub_uid = ''

# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
epub_exclude_files = ["search.html"]
2 changes: 1 addition & 1 deletion docs/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ Lastly, you need to add the following to the configuration file as well:
.. code-block:: python

import os, nativeauthenticator
c.JupyterHub.template_paths = ["{}/templates/".format(os.path.dirname(nativeauthenticator.__file__))]
c.JupyterHub.template_paths = [f"{os.path.dirname(nativeauthenticator.__file__}/templates/"]


Now you can run JupyterHub using the updated configuration file and start using JupyterHub with NativeAuthenticator:
Expand Down
17 changes: 6 additions & 11 deletions nativeauthenticator/crypto/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,11 @@

class InvalidAlgorithm(ValueError):
"""Algorithm is not supported by hashlib."""

pass


def salted_hmac(key_salt, value, secret, *, algorithm='sha1'):
def salted_hmac(key_salt, value, secret, *, algorithm="sha1"):
"""
Return the HMAC of 'value', using a key generated from key_salt and a
secret. Default algorithm is SHA1,
Expand All @@ -28,8 +29,7 @@ def salted_hmac(key_salt, value, secret, *, algorithm='sha1'):
hasher = getattr(hashlib, algorithm)
except AttributeError as e:
raise InvalidAlgorithm(
'%r is not an algorithm accepted by the hashlib module.'
% algorithm
"%r is not an algorithm accepted by the hashlib module." % algorithm
) from e
# We need to generate a derived key from our base key. We can do this by
# passing the key_salt and our base key through a pseudo-random function.
Expand All @@ -41,8 +41,7 @@ def salted_hmac(key_salt, value, secret, *, algorithm='sha1'):
return hmac.new(key, msg=force_bytes(value), digestmod=hasher)


RANDOM_STRING_CHARS = \
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
RANDOM_STRING_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"


def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS):
Expand All @@ -56,7 +55,7 @@ def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS):
* length: 12, bit length =~ 71 bits
* length: 22, bit length =~ 131 bits
"""
return ''.join(secrets.choice(allowed_chars) for i in range(length))
return "".join(secrets.choice(allowed_chars) for i in range(length))


def constant_time_compare(val1, val2):
Expand All @@ -71,8 +70,4 @@ def pbkdf2(password, salt, iterations, dklen=0, digest=None):
dklen = dklen or None
password = force_bytes(password)
salt = force_bytes(salt)
return hashlib.pbkdf2_hmac(digest().name,
password,
salt,
iterations,
dklen)
return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
45 changes: 21 additions & 24 deletions nativeauthenticator/crypto/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ def __init__(self, obj, *args):
super().__init__(*args)

def __str__(self):
return '{}. You passed in {!r} ({})'.format(
super().__str__(),
self.obj,
type(self.obj))
return f"{super().__str__()}. You passed in {self.obj!r} ({type(self.obj)})"


_PROTECTED_TYPES = (
type(None),
int, float, Decimal,
int,
float,
Decimal,
datetime.datetime,
datetime.date,
datetime.time,
Expand All @@ -35,7 +34,7 @@ def is_protected_type(obj):
return isinstance(obj, _PROTECTED_TYPES)


def force_str(s, encoding='utf-8', strings_only=False, errors='strict'):
def force_str(s, encoding="utf-8", strings_only=False, errors="strict"):
"""
Similar to smart_str(), except that lazy instances are resolved to
strings, rather than kept as lazy objects.
Expand All @@ -57,7 +56,7 @@ def force_str(s, encoding='utf-8', strings_only=False, errors='strict'):
return s


def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
def force_bytes(s, encoding="utf-8", strings_only=False, errors="strict"):
"""
Similar to smart_bytes, except that lazy instances are resolved to
strings, rather than kept as lazy objects.
Expand All @@ -66,10 +65,10 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
# Handle the common case first for performance reasons.
if isinstance(s, bytes):
if encoding == 'utf-8':
if encoding == "utf-8":
return s
else:
return s.decode('utf-8', errors).encode(encoding, errors)
return s.decode("utf-8", errors).encode(encoding, errors)
if strings_only and is_protected_type(s):
return s
if isinstance(s, memoryview):
Expand All @@ -84,15 +83,14 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
(fmt % char).encode(): bytes((char,))
for ascii_range in _ascii_ranges
for char in ascii_range
for fmt in ['%02x', '%02X']
for fmt in ["%02x", "%02X"]
}
# And then everything above 128, because bytes ≥ 128 are part of multibyte
# Unicode characters.
_hexdig = '0123456789ABCDEFabcdef'
_hextobyte.update({
(a + b).encode(): bytes.fromhex(a + b)
for a in _hexdig[8:] for b in _hexdig
})
_hexdig = "0123456789ABCDEFabcdef"
_hextobyte.update(
{(a + b).encode(): bytes.fromhex(a + b) for a in _hexdig[8:] for b in _hexdig}
)


def uri_to_iri(uri):
Expand All @@ -112,7 +110,7 @@ def uri_to_iri(uri):
# second block, decode the first 2 bytes if they represent a hex code to
# decode. The rest of the block is the part after '%AB', not containing
# any '%'. Add that to the output without further processing.
bits = uri.split(b'%')
bits = uri.split(b"%")
if len(bits) == 1:
iri = uri
else:
Expand All @@ -125,9 +123,9 @@ def uri_to_iri(uri):
append(hextobyte[item[:2]])
append(item[2:])
else:
append(b'%')
append(b"%")
append(item)
iri = b''.join(parts)
iri = b"".join(parts)
return repercent_broken_unicode(iri).decode()


Expand All @@ -150,7 +148,7 @@ def escape_uri_path(path):

def punycode(domain):
"""Return the Punycode of the given domain if it's non-ASCII."""
return domain.encode('idna').decode('ascii')
return domain.encode("idna").decode("ascii")


def repercent_broken_unicode(path):
Expand All @@ -165,9 +163,8 @@ def repercent_broken_unicode(path):
except UnicodeDecodeError as e:
# CVE-2019-14235: A recursion shouldn't be used since the exception
# handling uses massive amounts of memory
repercent = quote(path[e.start:e.end],
safe=b"/#%[]=:;$&()+,!?*@'~")
path = path[:e.start] + repercent.encode() + path[e.end:]
repercent = quote(path[e.start : e.end], safe=b"/#%[]=:;$&()+,!?*@'~")
path = path[: e.start] + repercent.encode() + path[e.end :]
else:
return path

Expand All @@ -194,10 +191,10 @@ def get_system_encoding():
#10335 and #5846.
"""
try:
encoding = locale.getdefaultlocale()[1] or 'ascii'
encoding = locale.getdefaultlocale()[1] or "ascii"
codecs.lookup(encoding)
except Exception:
encoding = 'ascii'
encoding = "ascii"
return encoding


Expand Down
Loading