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

Run pyupgrade --py38-plus to remove pre-3.8 idioms #4639

Merged
merged 5 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
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__}"
41 changes: 19 additions & 22 deletions lemur/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,9 @@
import socket
import time
import urllib.parse
from flask import g, request

from flask import g, request
from lemur import factory
from lemur.extensions import metrics

from lemur.users.views import mod as users_bp
from lemur.roles.views import mod as roles_bp
from lemur.auth.views import mod as auth_bp
from lemur.domains.views import mod as domains_bp
from lemur.destinations.views import mod as destinations_bp
from lemur.authorities.views import mod as authorities_bp
from lemur.certificates.views import mod as certificates_bp
from lemur.defaults.views import mod as defaults_bp
from lemur.plugins.views import mod as plugins_bp
from lemur.notifications.views import mod as notifications_bp
from lemur.sources.views import mod as sources_bp
from lemur.endpoints.views import mod as endpoints_bp
from lemur.logs.views import mod as logs_bp
from lemur.api_keys.views import mod as api_key_bp
from lemur.pending_certificates.views import mod as pending_certificates_bp
from lemur.dns_providers.views import mod as dns_providers_bp

from lemur.__about__ import (
__author__,
__copyright__,
Expand All @@ -44,7 +25,23 @@
__uri__,
__version__,
)

from lemur.api_keys.views import mod as api_key_bp
from lemur.auth.views import mod as auth_bp
from lemur.authorities.views import mod as authorities_bp
from lemur.certificates.views import mod as certificates_bp
from lemur.defaults.views import mod as defaults_bp
from lemur.destinations.views import mod as destinations_bp
from lemur.dns_providers.views import mod as dns_providers_bp
from lemur.domains.views import mod as domains_bp
from lemur.endpoints.views import mod as endpoints_bp
from lemur.extensions import metrics
from lemur.logs.views import mod as logs_bp
from lemur.notifications.views import mod as notifications_bp
from lemur.pending_certificates.views import mod as pending_certificates_bp
from lemur.plugins.views import mod as plugins_bp
from lemur.roles.views import mod as roles_bp
from lemur.sources.views import mod as sources_bp
from lemur.users.views import mod as users_bp

__all__ = [
"__title__",
Expand Down Expand Up @@ -184,5 +181,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
7 changes: 3 additions & 4 deletions lemur/api_keys/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Eric Coan <[email protected]>
"""
import click
from datetime import datetime

import click
from lemur.api_keys import service as api_key_service
from lemur.auth.service import create_token

from datetime import datetime


@click.group(name="api_keys", help="Handles all api key related tasks.")
def cli():
Expand Down Expand Up @@ -45,7 +44,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
25 changes: 11 additions & 14 deletions lemur/api_keys/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,7 @@

from flask import Blueprint, g
from flask_restful import reqparse, Api

from lemur.api_keys import service
from lemur.auth.service import AuthenticatedResource, create_token
from lemur.auth.permissions import ApiKeyCreatorPermission

from lemur.common.schema import validate_schema
from lemur.common.utils import paginated_parser

from lemur.api_keys.schemas import (
api_key_input_schema,
api_key_revoke_schema,
Expand All @@ -27,6 +20,10 @@
api_key_described_output_schema,
user_api_key_input_schema,
)
from lemur.auth.permissions import ApiKeyCreatorPermission
from lemur.auth.service import AuthenticatedResource, create_token
from lemur.common.schema import validate_schema
from lemur.common.utils import paginated_parser

mod = Blueprint("api_keys", __name__)
api = Api(mod)
Expand All @@ -36,7 +33,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 +131,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 +154,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 +251,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 +273,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 +413,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 +562,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
20 changes: 10 additions & 10 deletions lemur/auth/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <[email protected]>
"""
from functools import partial
from collections import namedtuple
from functools import partial

from flask import current_app
from flask_principal import Permission, RoleNeed
Expand All @@ -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__()
3 changes: 1 addition & 2 deletions lemur/auth/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
from flask_principal import Identity, identity_changed
from flask_principal import identity_loaded, RoleNeed, UserNeed
from flask_restful import Resource

from lemur.api_keys import service as api_key_service
from lemur.auth.permissions import AuthorityCreatorNeed, RoleMemberNeed
from lemur.users import service as user_service
Expand Down Expand Up @@ -209,4 +208,4 @@ class AuthenticatedResource(Resource):
method_decorators = [login_required]

def __init__(self):
super(AuthenticatedResource, self).__init__()
super().__init__()
Loading