Skip to content

Fix #6256 : migrate to python 3.7+ #6260

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

Merged
merged 3 commits into from
Apr 11, 2022
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
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@
# -- Options for link checks ----------------------------------------------

linkcheck_ignore = [
'http://127\.0\.0\.1/*'
r'http://127\.0\.0\.1/*'
]


Expand Down
1 change: 0 additions & 1 deletion notebook/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

if __name__ == '__main__':
from notebook import notebookapp as app
app.launch_new_instance()
6 changes: 3 additions & 3 deletions notebook/_sysinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ def pkg_commit_hash(pkg_path):
if repo_commit:
return 'repository', repo_commit.strip().decode('ascii')
else:
return u'', u''
return '', ''
par_path = p.dirname(par_path)
return u'', u''

return '', ''


def pkg_info(pkg_path):
Expand Down
9 changes: 6 additions & 3 deletions notebook/auth/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,17 @@ def set_password(args):
}
})
if not args.quiet:
print("password stored in config dir: %s" % jupyter_config_dir())
print(f"password stored in config dir: {jupyter_config_dir()}")

def main(argv):
parser = argparse.ArgumentParser(argv[0])
subparsers = parser.add_subparsers()
parser_password = subparsers.add_parser('password', help='sets a password for your notebook server')
parser_password.add_argument("password", help="password to set, if not given, a password will be queried for (NOTE: this may not be safe)",
nargs="?")
parser_password.add_argument(
"password",
help="password to set, if not given, a password will be queried for (NOTE: this may not be safe)",
nargs="?"
)
parser_password.add_argument("--quiet", help="suppress messages", action="store_true")
parser_password.set_defaults(function=set_password)
args = parser.parse_args(argv[1:])
Expand Down
20 changes: 10 additions & 10 deletions notebook/auth/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,15 @@ def _redirect_safe(self, url, default=None):
# OR pass our cross-origin check
if parsed.netloc:
# if full URL, run our cross-origin check:
origin = '%s://%s' % (parsed.scheme, parsed.netloc)
origin = f'{parsed.scheme}://{parsed.netloc}'
origin = origin.lower()
if self.allow_origin:
allow = self.allow_origin == origin
elif self.allow_origin_pat:
allow = bool(self.allow_origin_pat.match(origin))
if not allow:
# not allowed, use default
self.log.warning("Not allowing login redirect to %r" % url)
self.log.warning(f"Not allowing login redirect to {url!r}")
url = default
self.redirect(url)

Expand All @@ -73,13 +73,13 @@ def hashed_password(self):

def passwd_check(self, a, b):
return passwd_check(a, b)

def post(self):
typed_password = self.get_argument('password', default=u'')
new_password = self.get_argument('new_password', default=u'')
typed_password = self.get_argument('password', default='')
new_password = self.get_argument('new_password', default='')




if self.get_login_available(self.settings):
if self.passwd_check(self.hashed_password, typed_password) and not new_password:
self.set_login_cookie(self, uuid.uuid4().hex)
Expand All @@ -89,7 +89,7 @@ def post(self):
config_dir = self.settings.get('config_dir')
config_file = os.path.join(config_dir, 'jupyter_notebook_config.json')
set_password(new_password, config_file=config_file)
self.log.info("Wrote hashed password to %s" % config_file)
self.log.info(f"Wrote hashed password to {config_file}")
else:
self.set_status(401)
self._render(message={'error': 'Invalid credentials'})
Expand All @@ -112,7 +112,7 @@ def set_login_cookie(cls, handler, user_id=None):
handler.set_secure_cookie(handler.cookie_name, user_id, **cookie_options)
return user_id

auth_header_pat = re.compile('token\s+(.+)', re.IGNORECASE)
auth_header_pat = re.compile(r'token\s+(.+)', re.IGNORECASE)

@classmethod
def get_token(cls, handler):
Expand Down Expand Up @@ -197,7 +197,7 @@ def get_user(cls, handler):
@classmethod
def get_user_token(cls, handler):
"""Identify the user based on a token in the URL or Authorization header

Returns:
- uuid if authenticated
- None if not
Expand Down Expand Up @@ -245,7 +245,7 @@ def password_from_settings(cls, settings):

If there is no configured password, an empty string will be returned.
"""
return settings.get('password', u'')
return settings.get('password', '')

@classmethod
def get_login_available(cls, settings):
Expand Down
11 changes: 5 additions & 6 deletions notebook/auth/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from contextlib import contextmanager
import getpass
import hashlib
import io
import json
import os
import random
Expand Down Expand Up @@ -71,7 +70,7 @@ def passwd(passphrase=None, algorithm='argon2'):
return ':'.join((algorithm, cast_unicode(h, 'ascii')))
else:
h = hashlib.new(algorithm)
salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
salt = f"{random.getrandbits(4 * salt_len):0{salt_len}x}"
h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))

return ':'.join((algorithm, salt, h.hexdigest()))
Expand Down Expand Up @@ -135,7 +134,7 @@ def passwd_check(hashed_passphrase, passphrase):
def persist_config(config_file=None, mode=0o600):
"""Context manager that can be used to modify a config object

On exit of the context manager, the config will be written back to disk,
On exit of the context manager, the config will be written back to disk,
by default with user-only (600) permissions.
"""

Expand All @@ -152,20 +151,20 @@ def persist_config(config_file=None, mode=0o600):

yield config

with io.open(config_file, 'w', encoding='utf8') as f:
with open(config_file, 'w', encoding='utf8') as f:
f.write(cast_unicode(json.dumps(config, indent=2)))

try:
os.chmod(config_file, mode)
except Exception as e:
tb = traceback.format_exc()
warnings.warn("Failed to set permissions on %s:\n%s" % (config_file, tb),
warnings.warn(f"Failed to set permissions on {config_file}:\n{tb}",
RuntimeWarning)


def set_password(password=None, config_file=None):
"""Ask user for password, store it in notebook json configuration file"""

hashed_password = passwd(password)

with persist_config(config_file) as config:
Expand Down
10 changes: 5 additions & 5 deletions notebook/auth/tests/test_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ def test_bad():

def test_passwd_check_unicode():
# GH issue #4524
phash = u'sha1:23862bc21dd3:7a415a95ae4580582e314072143d9c382c491e4f'
assert passwd_check(phash, u"łe¶ŧ←↓→")
phash = (u'argon2:$argon2id$v=19$m=10240,t=10,p=8$'
u'qjjDiZUofUVVnrVYxacnbA$l5pQq1bJ8zglGT2uXP6iOg')
assert passwd_check(phash, u"łe¶ŧ←↓→")
phash = 'sha1:23862bc21dd3:7a415a95ae4580582e314072143d9c382c491e4f'
assert passwd_check(phash, "łe¶ŧ←↓→")
phash = ('argon2:$argon2id$v=19$m=10240,t=10,p=8$'
'qjjDiZUofUVVnrVYxacnbA$l5pQq1bJ8zglGT2uXP6iOg')
assert passwd_check(phash, "łe¶ŧ←↓→")
Loading