Skip to content

Commit

Permalink
Merge pull request #719 from SUNET/ylle-ruff-pie
Browse files Browse the repository at this point in the history
Add PIE rules to ruff and fix issues
  • Loading branch information
johanlundberg authored Nov 29, 2024
2 parents 4dfafcc + e8d9c1f commit 6d52310
Show file tree
Hide file tree
Showing 24 changed files with 33 additions and 97 deletions.
2 changes: 1 addition & 1 deletion ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ line-length = 120
target-version = "py311"

[lint]
select = ["E", "F", "W", "I", "ASYNC", "UP", "FLY", "PERF", "FURB", "ERA", "ANN"]
select = ["E", "F", "W", "I", "ASYNC", "UP", "FLY", "PERF", "FURB", "ERA", "ANN", "PIE"]

# ANN101 and ANN102 are depracated
ignore = ["E501", "ANN1"]
Expand Down
2 changes: 1 addition & 1 deletion src/eduid/common/config/parsers/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def interpolate_list(config_dict: dict[str, Any], sub_list: list) -> list:
:return: Configuration list
"""
for i in range(0, len(sub_list)):
for i in range(len(sub_list)):
item = sub_list[i]
# Substitute string items
if isinstance(item, str) and "$" in item:
Expand Down
2 changes: 0 additions & 2 deletions src/eduid/common/models/bearer_token.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ class AuthorizationError(Exception):
class RequestedAccessDenied(Exception):
"""Break out of get_data_owner when requested access (in the token) is not allowed"""

pass


logger = logging.getLogger(__name__)

Expand Down
1 change: 0 additions & 1 deletion src/eduid/graphdb/groupdb/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ def db_setup(self) -> None:
):
raise e
# Constraints already set up
pass
logger.info(f"{self} setup done.")

@property
Expand Down
2 changes: 1 addition & 1 deletion src/eduid/maccapi/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


def make_presentable_password(password: str) -> str:
return " ".join([password[i * 4 : i * 4 + 4] for i in range(0, math.ceil(len(password) / 4))])
return " ".join([password[i * 4 : i * 4 + 4] for i in range(math.ceil(len(password) / 4))])


def load_jwks(config: MAccApiConfig) -> jwk.JWKSet:
Expand Down
2 changes: 0 additions & 2 deletions src/eduid/queue/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,3 @@ class PayloadNotRegistered(EduIDDBError):
"""
Exception when a payload is not registered with a QueueDB.
"""

pass
6 changes: 0 additions & 6 deletions src/eduid/userdb/element.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,25 +68,19 @@ class ElementError(EduIDUserDBError):
Base exception class for PrimaryElement errors.
"""

pass


class PrimaryElementError(ElementError):
"""
Base exception class for PrimaryElement errors.
"""

pass


class PrimaryElementViolation(PrimaryElementError):
"""
Raised when some operation would result in more or less than one 'primary'
element in an PrimaryElementList.
"""

pass


TElementSubclass = TypeVar("TElementSubclass", bound="Element")
ElementKey = NewType("ElementKey", str)
Expand Down
2 changes: 0 additions & 2 deletions src/eduid/userdb/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@ class EventList(ElementList[ListElement], Generic[ListElement], ABC):
maintaining some governing principles, such as ensuring there no duplicates in the list.
"""

pass


def event_from_dict(data: dict[str, Any]) -> ToUEvent:
"""
Expand Down
32 changes: 0 additions & 32 deletions src/eduid/userdb/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,12 @@ class ConnectionError(EduIDDBError):
Error connecting to the database.
"""

pass


class MongoConnectionError(ConnectionError):
"""
Error connecting to MongoDB.
"""

pass


class DocumentDoesNotExist(EduIDDBError):
pass
Expand All @@ -44,8 +40,6 @@ class UserDoesNotExist(DocumentDoesNotExist):
Requested user could not be found in the database.
"""

pass


class MultipleDocumentsReturned(EduIDDBError):
pass
Expand All @@ -56,64 +50,48 @@ class MultipleUsersReturned(MultipleDocumentsReturned):
More than one user in the database matched the given search criteria.
"""

pass


class EduIDUserDBError(EduIDDBError):
"""
eduID userdb Exception class.
"""

pass


class UserHasUnknownData(EduIDUserDBError):
"""
One or more elements of the user could not be interpreted.
"""

pass


class UserDBValueError(EduIDUserDBError):
"""
Error regarding APIAuthUser instances.
"""

pass


class UserMissingData(EduIDUserDBError):
"""
There is missing data for a User
"""

pass


class DocumentOutOfSync(EduIDDBError):
"""
The document has been modified since it was read from the db.
"""

pass


class LockedIdentityViolation(EduIDUserDBError):
"""
The user is trying to verify an identity that differs from the current locked identity.
"""

pass


class UserOutOfSync(DocumentOutOfSync):
"""
The user has been modified since it was read from the db.
"""

pass


class UserIsRevoked(EduIDUserDBError):
"""
Expand All @@ -123,8 +101,6 @@ class UserIsRevoked(EduIDUserDBError):
they are never ever re-used (Kantara requirement).
"""

pass


class UserHasNotCompletedSignup(EduIDUserDBError):
"""
Expand All @@ -133,28 +109,20 @@ class UserHasNotCompletedSignup(EduIDUserDBError):
Signup has created lots of users in the database with only eppn, mail and mailAliases.
"""

pass


class ActionDBError(EduIDUserDBError):
"""
There was an actions-database related error
"""

pass


class BadEvent(EduIDUserDBError):
"""
General error in Event processing.
"""

pass


class EventHasUnknownData(BadEvent):
"""
One or more elements of the event could not be interpreted.
"""

pass
1 change: 0 additions & 1 deletion src/eduid/userdb/proofing/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,3 @@

class ProofingUser(User):
replace_locked: IdentityType | None = None
pass
2 changes: 1 addition & 1 deletion src/eduid/userdb/scimapi/invitedb.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class ScimApiInvite(ScimApiResourceBase):
nin: str | None = field(default=None)
preferred_language: str | None = field(default=None)
completed: datetime | None = field(default=None)
profiles: dict[str, ScimApiProfile] = field(default_factory=lambda: {})
profiles: dict[str, ScimApiProfile] = field(default_factory=dict)

def to_dict(self) -> TUserDbDocument:
res = asdict(self)
Expand Down
18 changes: 8 additions & 10 deletions src/eduid/webapp/bankid/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,16 +251,14 @@ def generate_auth_response(

resp = " ".join(
saml_response_tpl.format(
**{
"asserted_identity": asserted_identity,
"date_of_birth": date_of_birth.strftime("%Y-%m-%d"),
"session_id": request_id,
"timestamp": timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
"tomorrow": tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ"),
"yesterday": yesterday.strftime("%Y-%m-%dT%H:%M:%SZ"),
"sp_url": sp_baseurl,
"extra_attributes": extra_attributes_str,
}
asserted_identity=asserted_identity,
date_of_birth=date_of_birth.strftime("%Y-%m-%d"),
session_id=request_id,
timestamp=timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
tomorrow=tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ"),
yesterday=yesterday.strftime("%Y-%m-%dT%H:%M:%SZ"),
sp_url=sp_baseurl,
extra_attributes=extra_attributes_str,
).split()
)

Expand Down
1 change: 0 additions & 1 deletion src/eduid/webapp/common/api/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,5 +97,4 @@ def init_sentry(app: Flask) -> Flask:
sentry.init_app(app)
except ImportError:
app.logger.warning("SENTRY_DSN found but Raven not installed.")
pass
return app
2 changes: 0 additions & 2 deletions src/eduid/webapp/common/api/schemas/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,6 @@ def get_csrf_token(self, out_data: dict[str, Any], **kwargs: Any) -> dict[str, A
class EmptyRequest(EduidSchema, CSRFRequestMixin):
"""This is a common request schema that will just check the CSRF token"""

pass


class EmptyResponse(FluxStandardAction):
"""This is a common response schema for returning an empty response with a fresh CSRF token"""
Expand Down
1 change: 0 additions & 1 deletion src/eduid/webapp/common/api/tests/test_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ def post_param_view() -> Response:
@UnmarshalWith(NonValidatingSchema)
def post_json_view(test_data: str) -> None:
"""never validates"""
pass


@test_views.route("/test-cookie")
Expand Down
16 changes: 7 additions & 9 deletions src/eduid/webapp/common/authn/tests/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,13 @@ def auth_response(session_id: str, eppn: str, accr: EduidAuthnContextClass | Non
</samlp:Response>""" # noqa: E501

return saml_response_tpl.format(
**{
"uid": eppn,
"session_id": session_id,
"timestamp": timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
"tomorrow": tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ"),
"yesterday": yesterday.strftime("%Y-%m-%dT%H:%M:%SZ"),
"sp_url": sp_baseurl,
"accr": accr.value,
}
uid=eppn,
session_id=session_id,
timestamp=timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
tomorrow=tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ"),
yesterday=yesterday.strftime("%Y-%m-%dT%H:%M:%SZ"),
sp_url=sp_baseurl,
accr=accr.value,
)


Expand Down
18 changes: 8 additions & 10 deletions src/eduid/webapp/eidas/tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,16 +284,14 @@ def generate_auth_response(

resp = " ".join(
saml_response_tpl.format(
**{
"asserted_identity": asserted_identity,
"date_of_birth": date_of_birth.strftime("%Y-%m-%d"),
"session_id": request_id,
"timestamp": timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
"tomorrow": tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ"),
"yesterday": yesterday.strftime("%Y-%m-%dT%H:%M:%SZ"),
"sp_url": sp_baseurl,
"extra_attributes": extra_attributes_str,
}
asserted_identity=asserted_identity,
date_of_birth=date_of_birth.strftime("%Y-%m-%d"),
session_id=request_id,
timestamp=timestamp.strftime("%Y-%m-%dT%H:%M:%SZ"),
tomorrow=tomorrow.strftime("%Y-%m-%dT%H:%M:%SZ"),
yesterday=yesterday.strftime("%Y-%m-%dT%H:%M:%SZ"),
sp_url=sp_baseurl,
extra_attributes=extra_attributes_str,
).split()
)

Expand Down
1 change: 0 additions & 1 deletion src/eduid/webapp/idp/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ def require_ticket_decorator(*args: Any, **kwargs: Any) -> Response | WerkzeugRe
except Exception:
logger.exception("Couldn't parse the this_device supplied")
logger.debug(f"Extra debug: Known device: {this_device}")
pass

kwargs["ticket"] = ticket
return f(*args, **kwargs)
Expand Down
1 change: 0 additions & 1 deletion src/eduid/webapp/idp/sso_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ def release(self) -> None:
"""
Fake releasing a lock.
"""
pass


@deprecated("This class seems unused")
Expand Down
6 changes: 2 additions & 4 deletions src/eduid/webapp/letter_proofing/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,8 @@ def get_address(user: User, proofing_state: LetterProofingState) -> FullPostalAd
# return bogus data without Navet interaction for integration test
current_app.logger.info("Using magic cookie to get address")
return FullPostalAddress(
**{
"Name": {"GivenNameMarking": "20", "GivenName": "Magic Cookie", "Surname": "Testsson"},
"OfficialAddress": {"Address2": "MAGIC COOKIE", "PostalCode": "12345", "City": "LANDET"},
}
Name={"GivenNameMarking": "20", "GivenName": "Magic Cookie", "Surname": "Testsson"},
OfficialAddress={"Address2": "MAGIC COOKIE", "PostalCode": "12345", "City": "LANDET"},
)
# Lookup official address via Navet
address = current_app.msg_relay.get_postal_address(proofing_state.nin.number)
Expand Down
6 changes: 2 additions & 4 deletions src/eduid/webapp/lookup_mobile_proofing/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,8 @@ def match_mobile_to_user(
if check_magic_cookie(current_app.conf):
current_app.logger.info("Using the BACKDOOR to verify a NIN through the lookup mobile app")
user_postal_address = FullPostalAddress(
**{
"Name": {"GivenName": "Magic Cookie", "GivenNameMarking": "20", "Surname": "Magic Cookie"},
"OfficialAddress": {"Address2": "Dummy address", "City": "LANDET", "PostalCode": "12345"},
}
Name={"GivenName": "Magic Cookie", "GivenNameMarking": "20", "Surname": "Magic Cookie"},
OfficialAddress={"Address2": "Dummy address", "City": "LANDET", "PostalCode": "12345"},
)
proofing_log_entry = TeleAdressProofing(
eppn=user.eppn,
Expand Down
2 changes: 1 addition & 1 deletion src/eduid/webapp/reset_password/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def generate_suggested_password(password_length: int) -> str:
The suggested password is hashed and saved in session to avoid form hijacking
"""
password = generate_password(length=password_length)
password = " ".join([password[i * 4 : i * 4 + 4] for i in range(0, math.ceil(len(password) / 4))])
password = " ".join([password[i * 4 : i * 4 + 4] for i in range(math.ceil(len(password) / 4))])

return password

Expand Down
2 changes: 1 addition & 1 deletion src/eduid/webapp/security/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def generate_suggested_password() -> str:
password_length = current_app.conf.password_length

password = generate_password(length=password_length)
password = " ".join([password[i * 4 : i * 4 + 4] for i in range(0, int(len(password) / 4))])
password = " ".join([password[i * 4 : i * 4 + 4] for i in range(int(len(password) / 4))])

return password

Expand Down
2 changes: 0 additions & 2 deletions src/eduid/workers/amapi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
class AccessDenied(Exception):
"""Break out of get_data_owner when requested access (in the token) is not allowed"""

pass


# middleware needs to return a response
# some background: https://github.com/tiangolo/fastapi/issues/458
Expand Down

0 comments on commit 6d52310

Please sign in to comment.