Skip to content

Commit

Permalink
Merge pull request #4639 from jmcrawford45/pyupgrade-38-plus
Browse files Browse the repository at this point in the history
Run pyupgrade --py38-plus to remove pre-3.8 idioms
  • Loading branch information
jmcrawford45 authored Oct 19, 2023
2 parents 7378095 + 42040b2 commit 9a9a4f6
Show file tree
Hide file tree
Showing 109 changed files with 391 additions and 405 deletions.
4 changes: 1 addition & 3 deletions lemur/__about__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import, division, print_function

__all__ = [
"__title__",
"__summary__",
Expand All @@ -21,4 +19,4 @@
__email__ = "[email protected]"

__license__ = "Apache License, Version 2.0"
__copyright__ = "Copyright 2018 {0}".format(__author__)
__copyright__ = f"Copyright 2018 {__author__}"
2 changes: 1 addition & 1 deletion lemur/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,5 +184,5 @@ def sanitize_path(*, path: str) -> str:

# Record our response time metric
metrics.send("response_time", "TIMER", elapsed, metric_tags=tags)
metrics.send("status_code_{}".format(response.status_code), "counter", 1)
metrics.send(f"status_code_{response.status_code}", "counter", 1)
return response
2 changes: 1 addition & 1 deletion lemur/api_keys/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def create(uid, name, ttl):
)
click.echo("[+] Successfully created a new api key. Generating a JWT...")
jwt = create_token(uid, key.id, key.ttl)
click.echo("[+] Your JWT is: {jwt}".format(jwt=jwt))
click.echo(f"[+] Your JWT is: {jwt}")


@cli.command("revoke")
Expand Down
14 changes: 7 additions & 7 deletions lemur/api_keys/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class ApiKeyList(AuthenticatedResource):
""" Defines the 'api_keys' endpoint """

def __init__(self):
super(ApiKeyList, self).__init__()
super().__init__()

@validate_schema(None, api_keys_output_schema)
def get(self):
Expand Down Expand Up @@ -134,7 +134,7 @@ def post(self, data=None):
if data["user"]["id"] != g.current_user.id:
return (
dict(
message="You are not authorized to create tokens for: {0}".format(
message="You are not authorized to create tokens for: {}".format(
data["user"]["username"]
)
),
Expand All @@ -157,7 +157,7 @@ class ApiKeyUserList(AuthenticatedResource):
""" Defines the 'keys' endpoint on the 'users' endpoint. """

def __init__(self):
super(ApiKeyUserList, self).__init__()
super().__init__()

@validate_schema(None, api_keys_output_schema)
def get(self, user_id):
Expand Down Expand Up @@ -254,7 +254,7 @@ def post(self, user_id, data=None):
if user_id != g.current_user.id:
return (
dict(
message="You are not authorized to create tokens for: {0}".format(
message="You are not authorized to create tokens for: {}".format(
user_id
)
),
Expand All @@ -276,7 +276,7 @@ def post(self, user_id, data=None):
class ApiKeys(AuthenticatedResource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(ApiKeys, self).__init__()
super().__init__()

@validate_schema(None, api_key_output_schema)
def get(self, aid):
Expand Down Expand Up @@ -416,7 +416,7 @@ def delete(self, aid):
class UserApiKeys(AuthenticatedResource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(UserApiKeys, self).__init__()
super().__init__()

@validate_schema(None, api_key_output_schema)
def get(self, uid, aid):
Expand Down Expand Up @@ -565,7 +565,7 @@ def delete(self, uid, aid):
class ApiKeysDescribed(AuthenticatedResource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(ApiKeysDescribed, self).__init__()
super().__init__()

@validate_schema(None, api_key_described_output_schema)
def get(self, aid):
Expand Down
12 changes: 6 additions & 6 deletions lemur/auth/ldap.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def __init__(self, args):
self.ldap_principal = args["username"]
self.ldap_email_domain = current_app.config.get("LDAP_EMAIL_DOMAIN", None)
if "@" not in self.ldap_principal:
self.ldap_principal = "%s@%s" % (
self.ldap_principal = "{}@{}".format(
self.ldap_principal,
self.ldap_email_domain,
)
Expand Down Expand Up @@ -110,7 +110,7 @@ def _authorize(self):
# update their 'roles'
role = role_service.get_by_name(self.ldap_principal)
if not role:
description = "auto generated role based on owner: {0}".format(
description = "auto generated role based on owner: {}".format(
self.ldap_principal
)
role = role_service.create(
Expand All @@ -127,7 +127,7 @@ def _authorize(self):
if role:
if ldap_group_name in self.ldap_groups:
current_app.logger.debug(
"assigning role {0} to ldap user {1}".format(
"assigning role {} to ldap user {}".format(
self.ldap_principal, role
)
)
Expand Down Expand Up @@ -156,7 +156,7 @@ def _bind(self):
raise an exception on error.
"""
if "@" not in self.ldap_principal:
self.ldap_principal = "%s@%s" % (
self.ldap_principal = "{}@{}".format(
self.ldap_principal,
self.ldap_email_domain,
)
Expand Down Expand Up @@ -186,7 +186,7 @@ def _bind(self):
except ldap.SERVER_DOWN:
raise Exception("ldap server unavailable")
except ldap.LDAPError as e:
raise Exception("ldap error: {0}".format(e))
raise Exception(f"ldap error: {e}")

if self.ldap_is_active_directory:
# Lookup user DN, needed to search for group membership
Expand All @@ -198,7 +198,7 @@ def _bind(self):
)[0][1]["distinguishedName"][0]
userdn = userdn.decode("utf-8")
# Search all groups that have the userDN as a member
groupfilter = "(&(objectclass=group)(member:1.2.840.113556.1.4.1941:={0}))".format(
groupfilter = "(&(objectclass=group)(member:1.2.840.113556.1.4.1941:={}))".format(
userdn
)
lgroups = self.ldap_client.search_s(
Expand Down
18 changes: 9 additions & 9 deletions lemur/auth/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def __init__(self):
for role in sensitive_domain_roles:
needs.append(RoleNeed(role))

super(SensitiveDomainPermission, self).__init__(*needs)
super().__init__(*needs)


class CertificatePermission(Permission):
Expand All @@ -41,12 +41,12 @@ def __init__(self, owner, roles):
if str(r) != str(r).lower():
needs.append(CertificateOwnerNeed(str(r).lower()))

super(CertificatePermission, self).__init__(*needs)
super().__init__(*needs)


class ApiKeyCreatorPermission(Permission):
def __init__(self):
super(ApiKeyCreatorPermission, self).__init__(RoleNeed("admin"))
super().__init__(RoleNeed("admin"))


RoleMember = namedtuple("RoleMember", ["method", "value"])
Expand All @@ -56,16 +56,16 @@ def __init__(self):
class RoleMemberPermission(Permission):
def __init__(self, role_id):
needs = [RoleNeed("admin"), RoleMemberNeed(role_id)]
super(RoleMemberPermission, self).__init__(*needs)
super().__init__(*needs)


class AuthorityCreatorPermission(Permission):
def __init__(self):
requires_admin = current_app.config.get("ADMIN_ONLY_AUTHORITY_CREATION", False)
if requires_admin:
super(AuthorityCreatorPermission, self).__init__(RoleNeed("admin"))
super().__init__(RoleNeed("admin"))
else:
super(AuthorityCreatorPermission, self).__init__()
super().__init__()


AuthorityCreator = namedtuple("AuthorityCreator", ["method", "value"])
Expand All @@ -81,14 +81,14 @@ def __init__(self, authority_id, roles):
for r in roles:
needs.append(AuthorityOwnerNeed(str(r)))

super(AuthorityPermission, self).__init__(*needs)
super().__init__(*needs)


class StrictRolePermission(Permission):
def __init__(self):
strict_role_enforcement = current_app.config.get("LEMUR_STRICT_ROLE_ENFORCEMENT", False)
if strict_role_enforcement:
needs = [RoleNeed("admin"), RoleNeed("operator")]
super(StrictRolePermission, self).__init__(*needs)
super().__init__(*needs)
else:
super(StrictRolePermission, self).__init__()
super().__init__()
2 changes: 1 addition & 1 deletion lemur/auth/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,4 +209,4 @@ class AuthenticatedResource(Resource):
method_decorators = [login_required]

def __init__(self):
super(AuthenticatedResource, self).__init__()
super().__init__()
18 changes: 9 additions & 9 deletions lemur/auth/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,17 @@ def exchange_for_access_token(
}

# the secret and cliendId will be given to you when you signup for the provider
token = "{0}:{1}".format(client_id, secret)
token = f"{client_id}:{secret}"

basic = base64.b64encode(bytes(token, "utf-8"))
headers = {
"Content-Type": "application/x-www-form-urlencoded"
}

if current_app.config.get("TOKEN_AUTH_HEADER_CASE_SENSITIVE"):
headers["Authorization"] = "Basic {0}".format(basic.decode("utf-8"))
headers["Authorization"] = "Basic {}".format(basic.decode("utf-8"))
else:
headers["authorization"] = "basic {0}".format(basic.decode("utf-8"))
headers["authorization"] = "basic {}".format(basic.decode("utf-8"))

# exchange authorization code for access token.
r = requests.post(
Expand Down Expand Up @@ -401,7 +401,7 @@ class Login(Resource):

def __init__(self):
self.reqparse = reqparse.RequestParser()
super(Login, self).__init__()
super().__init__()

@limiter.limit("10/5minute")
def post(self):
Expand Down Expand Up @@ -481,7 +481,7 @@ def post(self):
)
return dict(token=create_token(user))
except Exception as e:
current_app.logger.error("ldap error: {0}".format(e))
current_app.logger.error(f"ldap error: {e}")
ldap_message = "ldap error: %s" % e
metrics.send(
"login", "counter", 1, metric_tags={"status": FAILURE_METRIC_STATUS}
Expand All @@ -508,7 +508,7 @@ class Ping(Resource):

def __init__(self):
self.reqparse = reqparse.RequestParser()
super(Ping, self).__init__()
super().__init__()

def get(self):
return "Redirecting..."
Expand Down Expand Up @@ -568,7 +568,7 @@ def post(self):
class OAuth2(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(OAuth2, self).__init__()
super().__init__()

def get(self):
return "Redirecting..."
Expand Down Expand Up @@ -631,7 +631,7 @@ def post(self):
class Google(Resource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(Google, self).__init__()
super().__init__()

def post(self):
access_token_url = "https://accounts.google.com/o/oauth2/token"
Expand Down Expand Up @@ -659,7 +659,7 @@ def post(self):
token = r.json()

# Step 2. Retrieve information about the current user
headers = {"Authorization": "Bearer {0}".format(token["access_token"])}
headers = {"Authorization": "Bearer {}".format(token["access_token"])}

r = requests.get(user_info_url, headers=headers)
profile = r.json()
Expand Down
2 changes: 1 addition & 1 deletion lemur/authorities/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def default_validity_days(self):
return current_app.config.get("DEFAULT_VALIDITY_DAYS", 365) # 1 year default

def __repr__(self):
return "Authority(name={name})".format(name=self.name)
return f"Authority(name={self.name})"

@property
def is_cn_optional(self):
Expand Down
10 changes: 5 additions & 5 deletions lemur/authorities/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def create_authority_roles(roles, owner, plugin_title, creator):
role = role_service.create(
r["name"],
password=r["password"],
description="Auto generated role for {0}".format(plugin_title),
description=f"Auto generated role for {plugin_title}",
username=r["username"],
)

Expand All @@ -114,7 +114,7 @@ def create_authority_roles(roles, owner, plugin_title, creator):
owner_role = role_service.get_by_name(owner)
if not owner_role:
owner_role = role_service.create(
owner, description="Auto generated role based on owner: {0}".format(owner)
owner, description=f"Auto generated role based on owner: {owner}"
)

role_objs.append(owner_role)
Expand Down Expand Up @@ -215,8 +215,8 @@ def get_authority_role(ca_name, creator=None):
"""
if creator:
if creator.is_admin:
return role_service.get_by_name("{0}_admin".format(ca_name))
return role_service.get_by_name("{0}_operator".format(ca_name))
return role_service.get_by_name(f"{ca_name}_admin")
return role_service.get_by_name(f"{ca_name}_operator")


def render(args):
Expand All @@ -234,7 +234,7 @@ def render(args):
if "active" in filt:
query = query.filter(Authority.active == truthiness(terms[1]))
elif "cn" in filt:
term = "%{0}%".format(terms[1])
term = f"%{terms[1]}%"
sub_query = (
database.session_query(Certificate.root_authority_id)
.filter(Certificate.cn.ilike(term))
Expand Down
6 changes: 3 additions & 3 deletions lemur/authorities/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class AuthoritiesList(AuthenticatedResource):

def __init__(self):
self.reqparse = reqparse.RequestParser()
super(AuthoritiesList, self).__init__()
super().__init__()

@validate_schema(None, authorities_output_schema)
def get(self):
Expand Down Expand Up @@ -243,7 +243,7 @@ def post(self, data=None):
class Authorities(AuthenticatedResource):
def __init__(self):
self.reqparse = reqparse.RequestParser()
super(Authorities, self).__init__()
super().__init__()

@validate_schema(None, authority_output_schema)
def get(self, authority_id):
Expand Down Expand Up @@ -425,7 +425,7 @@ def put(self, authority_id, data=None):

class CertificateAuthority(AuthenticatedResource):
def __init__(self):
super(CertificateAuthority, self).__init__()
super().__init__()

@validate_schema(None, authority_output_schema)
def get(self, certificate_id):
Expand Down
2 changes: 1 addition & 1 deletion lemur/authorizations/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def plugin(self):
return plugins.get(self.plugin_name)

def __repr__(self):
return "Authorization(id={id})".format(id=self.id)
return f"Authorization(id={self.id})"

def __init__(self, account_number, domains, dns_provider_type, options=None):
self.account_number = account_number
Expand Down
Loading

0 comments on commit 9a9a4f6

Please sign in to comment.