From b69076ac1a0f506bb57f2631f37b08d54bdf696b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adolfo=20G=C3=B3mez=20Garc=C3=ADa?= Date: Mon, 17 Apr 2023 02:47:31 +0200 Subject: [PATCH] Linted all models --- server/src/uds/models/os_manager.py | 8 +-- server/src/uds/models/permissions.py | 16 ++---- server/src/uds/models/provider.py | 10 ++-- server/src/uds/models/scheduler.py | 8 +-- server/src/uds/models/service.py | 22 ++++---- server/src/uds/models/service_pool.py | 2 +- server/src/uds/models/service_pool_group.py | 9 +-- .../uds/models/service_pool_publication.py | 18 ++---- server/src/uds/models/stats_counters.py | 2 +- server/src/uds/models/stats_counters_accum.py | 4 +- server/src/uds/models/stats_events.py | 19 ++----- server/src/uds/models/storage.py | 6 +- server/src/uds/models/tag.py | 8 +-- server/src/uds/models/ticket_store.py | 53 +++++++++++------- server/src/uds/models/transport.py | 11 ++-- server/src/uds/models/tunnel_token.py | 6 +- server/src/uds/models/unique_id.py | 6 +- server/src/uds/models/user.py | 12 ++-- server/src/uds/models/user_service.py | 55 ++++++++++++------- .../src/uds/models/user_service_property.py | 6 +- 20 files changed, 135 insertions(+), 146 deletions(-) diff --git a/server/src/uds/models/os_manager.py b/server/src/uds/models/os_manager.py index 22bd21bc2..265019558 100644 --- a/server/src/uds/models/os_manager.py +++ b/server/src/uds/models/os_manager.py @@ -55,7 +55,7 @@ class OSManager(ManagedObjectModel, TaggingMixin): # objects: 'models.manager.Manager[OSManager]' deployedServices: 'models.manager.RelatedManager[ServicePool]' - class Meta(ManagedObjectModel.Meta): + class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order """ @@ -80,7 +80,7 @@ class OSManager(ManagedObjectModel, TaggingMixin): :note: We only need to get info from this, not access specific data (class specific info) """ # We only need to get info from this, not access specific data (class specific info) - from uds.core import osmanagers + from uds.core import osmanagers # pylint: disable=import-outside-toplevel return osmanagers.factory().lookup(self.data_type) or osmanagers.OSManager @@ -101,10 +101,10 @@ class OSManager(ManagedObjectModel, TaggingMixin): return True def __str__(self) -> str: - return "{0} of type {1} (id:{2})".format(self.name, self.data_type, self.id) + return f'{self.name} of type {self.data_type} (id:{self.id})' @staticmethod - def beforeDelete(sender, **kwargs) -> None: + def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument """ Used to invoke the Service class "Destroy" before deleting it from database. diff --git a/server/src/uds/models/permissions.py b/server/src/uds/models/permissions.py index a41804aef..c688083f0 100644 --- a/server/src/uds/models/permissions.py +++ b/server/src/uds/models/permissions.py @@ -85,7 +85,6 @@ class PermissionType(enum.IntEnum): return self.value >= permission.value - class Permissions(UUIDModel): """ An OS Manager represents a manager for responding requests for agents inside services. @@ -118,9 +117,7 @@ class Permissions(UUIDModel): object_type = models.SmallIntegerField(default=-1, db_index=True) object_id = models.IntegerField(default=None, db_index=True, null=True, blank=True) - permission = models.SmallIntegerField( - default=PermissionType.NONE, db_index=True - ) + permission = models.SmallIntegerField(default=PermissionType.NONE, db_index=True) # "fake" declarations for type checking # objects: 'models.manager.Manager[Permissions]' @@ -235,11 +232,8 @@ class Permissions(UUIDModel): return PermissionType(self.permission).as_str() def __str__(self) -> str: - return 'Permission {}, user {} group {} object_type {} object_id {} permission {}'.format( - self.uuid, - self.user, - self.group, - self.object_type, - self.object_id, - PermissionType(self.permission).as_str(), + return ( + f'Permission {self.uuid}, user {self.user} group {self.group} ' + f'object_type {self.object_type} object_id {self.object_id} ' + f'permission {PermissionType(self.permission).as_str()}' ) diff --git a/server/src/uds/models/provider.py b/server/src/uds/models/provider.py index f96106d4b..bd20c8358 100644 --- a/server/src/uds/models/provider.py +++ b/server/src/uds/models/provider.py @@ -59,7 +59,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore # objects: 'models.manager.Manager[Provider]' services: 'models.manager.RelatedManager[Service]' - class Meta(ManagedObjectModel.Meta): + class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order """ @@ -76,7 +76,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore Returns: The python type for this record object """ - from uds.core import services # pylint: disable=redefined-outer-name + from uds.core import services # pylint: disable=import-outside-toplevel return services.factory().lookup(self.data_type) or services.ServiceProvider @@ -94,10 +94,10 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore return self.maintenance_mode def __str__(self) -> str: - return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id) + return f'Provider {self.name} of type {self.data_type} (id:{self.id})' @staticmethod - def beforeDelete(sender, **kwargs) -> None: + def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument """ Used to invoke the Provider class "Destroy" before deleting it from database. @@ -106,7 +106,7 @@ class Provider(ManagedObjectModel, TaggingMixin): # type: ignore :note: If destroy raises an exception, the deletion is not taken. """ - from uds.core.util.permissions import clean + from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel toDelete = kwargs['instance'] logger.debug('Before delete service provider %s', toDelete) diff --git a/server/src/uds/models/scheduler.py b/server/src/uds/models/scheduler.py index 86d33a886..555c1dcb9 100644 --- a/server/src/uds/models/scheduler.py +++ b/server/src/uds/models/scheduler.py @@ -76,7 +76,7 @@ class Scheduler(models.Model): # objects: 'models.manager.Manager[Scheduler]' id: int # Primary key (Autogenerated by model, just for type checking) - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -87,7 +87,7 @@ class Scheduler(models.Model): """ Returns an environment valid for the record this object represents """ - return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore + return Environment.getEnvForTableElement(self._meta.verbose_name, self.id) # type: ignore # pylint: disable=no-member def getInstance(self) -> typing.Optional[jobs.Job]: """ @@ -111,9 +111,7 @@ class Scheduler(models.Model): toDelete.getEnvironment().clearRelatedData() def __str__(self) -> str: - return 'Scheduled task {}, every {}, last execution at {}, state = {}'.format( - self.name, self.frecuency, self.last_execution, self.state - ) + return f'Scheduled task {self.name}, every {self.frecuency}, last execution at {self.last_execution}, state = {self.state}' # Connects a pre deletion signal to Scheduler diff --git a/server/src/uds/models/service.py b/server/src/uds/models/service.py index 725bd777d..54bb5fbe3 100644 --- a/server/src/uds/models/service.py +++ b/server/src/uds/models/service.py @@ -46,8 +46,8 @@ from .provider import Provider # Not imported at runtime, just for type checking if typing.TYPE_CHECKING: - from uds.core import services from uds.models.service_pool import ServicePool + from uds.core import services logger = logging.getLogger(__name__) @@ -63,10 +63,10 @@ class ServiceTokenAlias(models.Model): ) alias = models.CharField(max_length=64, unique=True) - def __str__(self): - return self.alias - + def __str__(self) -> str: + return str(self.alias) # pylint complains about CharField +# pylint: disable=no-member class Service(ManagedObjectModel, TaggingMixin): # type: ignore """ A Service represents an specidied type of service offered to final users, @@ -93,7 +93,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore deployedServices: 'models.manager.RelatedManager[ServicePool]' aliases: 'models.manager.RelatedManager[ServiceTokenAlias]' - class Meta(ManagedObjectModel.Meta): + class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -149,9 +149,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore self.deserialize(obj, values) else: raise Exception( - 'Service type of {} is not recogniced by provider {}'.format( - self.data_type, prov - ) + f'Service type of {self.data_type} is not recogniced by provider {prov.name}' ) self._cachedInstance = obj @@ -169,6 +167,8 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore :note: We only need to get info from this, not access specific data (class specific info) """ + from uds.core import services # pylint: disable=import-outside-toplevel,redefined-outer-name + prov: typing.Type['services.ServiceProvider'] = self.provider.getType() return prov.getServiceByType(self.data_type) or services.Service @@ -194,10 +194,10 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore return self.max_services_count_type == 1 def __str__(self) -> str: - return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id) + return f'{self.name} of type {self.data_type} (id:{self.id})' @staticmethod - def beforeDelete(sender, **kwargs) -> None: + def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument """ Used to invoke the Service class "Destroy" before deleting it from database. @@ -206,7 +206,7 @@ class Service(ManagedObjectModel, TaggingMixin): # type: ignore :note: If destroy raises an exception, the deletion is not taken. """ - from uds.core.util.permissions import clean + from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel toDelete = kwargs['instance'] diff --git a/server/src/uds/models/service_pool.py b/server/src/uds/models/service_pool.py index d425af46f..c244bdca5 100644 --- a/server/src/uds/models/service_pool.py +++ b/server/src/uds/models/service_pool.py @@ -159,7 +159,7 @@ class ServicePool(UUIDModel, TaggingMixin): # type: ignore calendaraction_set: 'models.manager.RelatedManager[CalendarAction]' changelog: 'models.manager.RelatedManager[ServicePoolPublicationChangelog]' - class Meta(UUIDModel.Meta): + class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare the name of the table at database """ diff --git a/server/src/uds/models/service_pool_group.py b/server/src/uds/models/service_pool_group.py index e681ff8e0..fea7877b1 100644 --- a/server/src/uds/models/service_pool_group.py +++ b/server/src/uds/models/service_pool_group.py @@ -44,13 +44,12 @@ from .image import Image logger = logging.getLogger(__name__) - +# pylint: disable=no-member class ServicePoolGroup(UUIDModel): """ A deployed service is the Service produced element that is assigned finally to an user (i.e. a Virtual Machine, etc..) """ - # pylint: disable=model-missing-unicode name = models.CharField(max_length=128, default='', db_index=True, unique=True) comments = models.CharField(max_length=256, default='') priority = models.IntegerField(default=0, db_index=True) @@ -65,7 +64,7 @@ class ServicePoolGroup(UUIDModel): # "fake" declarations for type checking # objects: 'models.manager.Manager[ServicePoolGroup]' - class Meta(UUIDModel.Meta): + class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare the name of the table at database """ @@ -74,9 +73,7 @@ class ServicePoolGroup(UUIDModel): app_label = 'uds' def __str__(self) -> str: - return 'Service Pool group {}({}): {}'.format( - self.name, self.comments, self.image.name if self.image else '' - ) + return f'Service Pool group {self.name}({self.comments}): {self.image.name if self.image else ""}' @property def as_dict(self) -> typing.MutableMapping[str, typing.Any]: diff --git a/server/src/uds/models/service_pool_publication.py b/server/src/uds/models/service_pool_publication.py index bf8893249..eeee246d0 100644 --- a/server/src/uds/models/service_pool_publication.py +++ b/server/src/uds/models/service_pool_publication.py @@ -65,7 +65,7 @@ class ServicePoolPublicationChangelog(models.Model): # "fake" declarations for type checking # objects: 'models.manager.Manager[ServicePoolPublicationChangelog]' - class Meta(UUIDModel.Meta): + class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -74,9 +74,7 @@ class ServicePoolPublicationChangelog(models.Model): app_label = 'uds' def __str__(self) -> str: - return 'Revision log for publication {}, rev {}: {}'.format( - self.publication.name, self.revision, self.log - ) + return f'Changelog for publication {self.publication.name}, rev {self.revision}: {self.log}' class ServicePoolPublication(UUIDModel): @@ -105,7 +103,7 @@ class ServicePoolPublication(UUIDModel): # objects: 'models.manager.Manager["ServicePoolPublication"]' userServices: 'models.manager.RelatedManager[UserService]' - class Meta(UUIDModel.Meta): + class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -146,9 +144,7 @@ class ServicePoolPublication(UUIDModel): if serviceInstance.publicationType is None: raise Exception( - 'Class {} do not have defined publicationType but needs to be published!!!'.format( - serviceInstance.__class__ - ) + f'Class {serviceInstance.__class__.__name__} do not have defined publicationType but needs to be published!!!' ) publication = serviceInstance.publicationType( @@ -208,7 +204,7 @@ class ServicePoolPublication(UUIDModel): publicationManager().cancel(self) @staticmethod - def beforeDelete(sender, **kwargs) -> None: + def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument """ Used to invoke the Service class "Destroy" before deleting it from database. @@ -230,9 +226,7 @@ class ServicePoolPublication(UUIDModel): logger.debug('Deleted publication %s', toDelete) def __str__(self) -> str: - return 'Publication {}, rev {}, state {}'.format( - self.deployed_service.name, self.revision, State.toString(self.state) - ) + return f'Publication {self.deployed_service.name}, rev {self.revision}, state {State.toString(self.state)}' # Connects a pre deletion signal to Authenticator diff --git a/server/src/uds/models/stats_counters.py b/server/src/uds/models/stats_counters.py index 3e15c24b3..3499b86c7 100644 --- a/server/src/uds/models/stats_counters.py +++ b/server/src/uds/models/stats_counters.py @@ -53,7 +53,7 @@ class StatsCounters(models.Model): # "fake" declarations for type checking objects: 'models.manager.Manager[StatsCounters]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare db table """ diff --git a/server/src/uds/models/stats_counters_accum.py b/server/src/uds/models/stats_counters_accum.py index fe78d30d4..9f73b4d66 100644 --- a/server/src/uds/models/stats_counters_accum.py +++ b/server/src/uds/models/stats_counters_accum.py @@ -82,7 +82,7 @@ class StatsCountersAccum(models.Model): # "fake" declarations for type checking objects: 'models.manager.Manager[StatsCountersAccum]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare db table """ @@ -215,7 +215,7 @@ class StatsCountersAccum(models.Model): sum=models.Sum('v_sum'), ) - """Stores accumulated data in StatsCountersAccum""" + # Stores accumulated data in StatsCountersAccum # Acummulate data, only register if there is data accumulated: typing.List[StatsCountersAccum] = [ StatsCountersAccum( diff --git a/server/src/uds/models/stats_events.py b/server/src/uds/models/stats_events.py index 9cf067c1b..15f645b1e 100644 --- a/server/src/uds/models/stats_events.py +++ b/server/src/uds/models/stats_events.py @@ -33,13 +33,9 @@ Author: Adolfo Gómez, dkmaster at dkmon dot com import datetime import logging import typing -import types from django.db import models -from .util import NEVER_UNIX -from .util import getSqlDatetimeAsUnix - logger = logging.getLogger(__name__) @@ -62,7 +58,7 @@ class StatsEvents(models.Model): # "fake" declarations for type checking # objects: 'models.manager.Manager[StatsEvents]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare db table """ @@ -160,7 +156,7 @@ class StatsEvents(models.Model): # Return record as csv line using separator (default: ',') def toCsv(self, sep: str = ',') -> str: - from uds.core.util.stats.events import EVENT_NAMES, TYPES_NAMES + from uds.core.util.stats.events import EVENT_NAMES, TYPES_NAMES # pylint: disable=import-outside-toplevel return sep.join( [ @@ -176,12 +172,7 @@ class StatsEvents(models.Model): ) def __str__(self): - return 'Log of {}({}): {} - {} - {}, {}, {}'.format( - self.owner_type, - self.owner_id, - self.event_type, - self.stamp, - self.fld1, - self.fld2, - self.fld3, + return ( + f'Log of {self.owner_type}({self.owner_id}): {self.event_type} - {self.stamp}, ' + f'{self.fld1}, {self.fld2}, {self.fld3}' ) diff --git a/server/src/uds/models/storage.py b/server/src/uds/models/storage.py index 59c74b63d..e2e5e57e3 100644 --- a/server/src/uds/models/storage.py +++ b/server/src/uds/models/storage.py @@ -53,7 +53,7 @@ class Storage(models.Model): # "fake" declarations for type checking # objects: 'models.manager.Manager[Storage]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare the name of the table at database """ @@ -61,6 +61,4 @@ class Storage(models.Model): app_label = 'uds' def __str__(self) -> str: - return '{} {} > str= {}, {}'.format( - self.owner, self.key, self.data, '/'.join([self.attr1 or '']) - ) + return f'{self.owner} {self.key} > str= {self.data}, {self.attr1 or ""}' diff --git a/server/src/uds/models/tag.py b/server/src/uds/models/tag.py index ce1f15cd3..6460df5f4 100644 --- a/server/src/uds/models/tag.py +++ b/server/src/uds/models/tag.py @@ -81,7 +81,7 @@ class Tag(UUIDModel): servicepool_set: 'models.manager.RelatedManager[ServicePool]' transport_set: 'models.manager.RelatedManager[Transport]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare db table """ @@ -91,14 +91,14 @@ class Tag(UUIDModel): @property def vtag(self) -> str: - return self.tag.capitalize() + return str(self.tag).capitalize() def __str__(self) -> str: - return 'Tag: {} {}'.format(self.uuid, self.tag) + return f'Tag: {self.uuid} {self.tag}' class TaggingMixin(models.Model): tags = models.ManyToManyField(Tag) - class Meta: + class Meta: # pylint: disable=too-few-public-methods abstract = True diff --git a/server/src/uds/models/ticket_store.py b/server/src/uds/models/ticket_store.py index fd2e81476..acbde4743 100644 --- a/server/src/uds/models/ticket_store.py +++ b/server/src/uds/models/ticket_store.py @@ -76,7 +76,7 @@ class TicketStore(UUIDModel): class InvalidTicket(Exception): pass - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare the name of the table at database """ @@ -114,13 +114,16 @@ class TicketStore(UUIDModel): data = cryptoManager().AESCrypt(data, owner.encode()) owner = SECURED # So data is REALLY encrypted - return TicketStore.objects.create( - stamp=getSqlDatetime(), - data=data, - validator=validator, - validity=validity, - owner=owner, - ).uuid or '' + return ( + TicketStore.objects.create( + stamp=getSqlDatetime(), + data=data, + validator=validator, + validity=validity, + owner=owner, + ).uuid + or '' + ) @staticmethod def get( @@ -151,11 +154,15 @@ class TicketStore(UUIDModel): data, typing.cast(str, owner).encode() ) - data = pickle.loads(data) # nosec: Tickets are generated by us, so we know they are safe + data = pickle.loads( + data + ) # nosec: Tickets are generated by us, so we know they are safe # If has validator, execute it if t.validator: - validator: ValidatorType = pickle.loads(t.validator) # nosec: Tickets are generated by us, so we know they are safe + validator: ValidatorType = pickle.loads( + t.validator + ) # nosec: Tickets are generated by us, so we know they are safe if validator(data) is False: raise TicketStore.InvalidTicket('Validation failed') @@ -166,7 +173,7 @@ class TicketStore(UUIDModel): return data except TicketStore.DoesNotExist: - raise TicketStore.InvalidTicket('Does not exists') + raise TicketStore.InvalidTicket('Does not exists') from None @staticmethod def update( @@ -188,7 +195,9 @@ class TicketStore(UUIDModel): data, typing.cast(str, owner).encode() ) - dct = pickle.loads(data) + dct = pickle.loads( + data + ) # nosec: Tickets are ONLY generated by us, so we know they are safe # invoke check function if checkFnc(dct) is False: @@ -222,7 +231,7 @@ class TicketStore(UUIDModel): t.validity = validity t.save(update_fields=['validity', 'stamp']) except TicketStore.DoesNotExist: - raise TicketStore.InvalidTicket('Does not exists') + raise TicketStore.InvalidTicket('Does not exists') from None # Especific methods for tunnel @staticmethod @@ -302,12 +311,14 @@ class TicketStore(UUIDModel): TicketStore.objects.filter(stamp__lt=cleanSince).delete() def __str__(self) -> str: - data = pickle.loads(self.data) if self.owner != SECURED else '{Secure Ticket}' # nosec: Tickets are generated by us, so we know they are safe - - return 'Ticket id: {}, Owner: {}, Stamp: {}, Validity: {}, Data: {}'.format( - self.uuid, - self.owner, - self.stamp, - self.validity, - data, + # Tickets are generated by us, so we know they are safe + data = ( + pickle.loads(self.data) # nosec + if self.owner != SECURED + else '{Secure Ticket}' + ) + + return ( + f'Ticket id: {self.uuid}, Owner: {self.owner}, Stamp: {self.stamp}, ' + f'Validity: {self.validity}, Data: {data}' ) diff --git a/server/src/uds/models/transport.py b/server/src/uds/models/transport.py index dad9f9012..3cc095cd7 100644 --- a/server/src/uds/models/transport.py +++ b/server/src/uds/models/transport.py @@ -62,7 +62,6 @@ class Transport(ManagedObjectModel, TaggingMixin): ALLOW = 'a' DENY = 'd' - # pylint: disable=model-missing-unicode priority = models.IntegerField(default=0, db_index=True) net_filtering = models.CharField(max_length=1, default=NO_FILTERING, db_index=True) # We store allowed oss as a comma-separated list @@ -76,7 +75,7 @@ class Transport(ManagedObjectModel, TaggingMixin): deployedServices: 'models.manager.RelatedManager[ServicePool]' networks: 'models.manager.RelatedManager[Network]' - class Meta(ManagedObjectModel.Meta): + class Meta(ManagedObjectModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order """ @@ -140,13 +139,13 @@ class Transport(ManagedObjectModel, TaggingMixin): Returns: bool: True if this transport is valid for the specified OS, False otherwise """ - return not self.allowed_oss or os.name in self.allowed_oss.split(',') + return not self.allowed_oss or os.name in str(self.allowed_oss).split(',') def __str__(self) -> str: - return '{} of type {} (id:{})'.format(self.name, self.data_type, self.id) + return f'{self.name} of type {self.data_type} (id:{self.id})' @staticmethod - def beforeDelete(sender, **kwargs) -> None: + def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument """ Used to invoke the Service class "Destroy" before deleting it from database. @@ -155,7 +154,7 @@ class Transport(ManagedObjectModel, TaggingMixin): :note: If destroy raises an exception, the deletion is not taken. """ - from uds.core.util.permissions import clean + from uds.core.util.permissions import clean # pylint: disable=import-outside-toplevel toDelete = kwargs['instance'] diff --git a/server/src/uds/models/tunnel_token.py b/server/src/uds/models/tunnel_token.py index 1d37ad99e..bfb14e02e 100644 --- a/server/src/uds/models/tunnel_token.py +++ b/server/src/uds/models/tunnel_token.py @@ -52,7 +52,7 @@ class TunnelToken(models.Model): # "fake" declarations for type checking # objects: 'models.manager.Manager[TunnelToken]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods app_label = 'uds' constraints = [ models.UniqueConstraint(fields=['ip', 'hostname'], name='tt_ip_hostname') @@ -73,6 +73,4 @@ class TunnelToken(models.Model): return False def __str__(self): - return ''.format( - self.token, self.stamp, self.username, self.ip, self.hostname - ) + return f'' diff --git a/server/src/uds/models/unique_id.py b/server/src/uds/models/unique_id.py index bd8068f3c..954bf8706 100644 --- a/server/src/uds/models/unique_id.py +++ b/server/src/uds/models/unique_id.py @@ -52,7 +52,7 @@ class UniqueId(models.Model): # "fake" declarations for type checking # objects: 'models.manager.Manager[UniqueId]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -64,6 +64,4 @@ class UniqueId(models.Model): ] def __str__(self) -> str: - return u"{0} {1}.{2}, assigned is {3}".format( - self.owner, self.basename, self.seq, self.assigned - ) + return f'{self.owner} {self.basename}.{self.seq}, assigned is {self.assigned}' diff --git a/server/src/uds/models/user.py b/server/src/uds/models/user.py index 7ab1d274d..8bdecb04e 100644 --- a/server/src/uds/models/user.py +++ b/server/src/uds/models/user.py @@ -51,6 +51,7 @@ if typing.TYPE_CHECKING: logger = logging.getLogger(__name__) +# pylint: disable=no-member class User(UUIDModel): """ This class represents a single user, associated with one authenticator @@ -83,7 +84,7 @@ class User(UUIDModel): userServices: 'models.manager.RelatedManager[UserService]' permissions: 'models.manager.RelatedManager[Permissions]' - class Meta(UUIDModel.Meta): + class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -204,10 +205,8 @@ class User(UUIDModel): return store[str(self.uuid) + '_' + key] def __str__(self): - return 'User {} (id:{}) from auth {}'.format( - self.name, self.id, self.manager.name - ) - + return f'{self.pretty_name} (id:{self.id})' + def cleanRelated(self) -> None: """ Cleans up all related external data, such as mfa data, etc @@ -217,9 +216,8 @@ class User(UUIDModel): if self.manager.mfa: self.manager.mfa.getInstance().resetData(mfas.MFA.getUserId(self)) - @staticmethod - def beforeDelete(sender, **kwargs) -> None: + def beforeDelete(sender, **kwargs) -> None: # pylint: disable=unused-argument """ Used to invoke the Service class "Destroy" before deleting it from database. diff --git a/server/src/uds/models/user_service.py b/server/src/uds/models/user_service.py index 1858feda1..826879acf 100644 --- a/server/src/uds/models/user_service.py +++ b/server/src/uds/models/user_service.py @@ -59,7 +59,9 @@ if typing.TYPE_CHECKING: logger = logging.getLogger(__name__) -class UserService(UUIDModel): # pylint: disable=too-many-public-methods + +# pylint: disable=too-many-instance-attributes,too-many-public-methods +class UserService(UUIDModel): """ This is the base model for assigned user service and cached user services. This are the real assigned services to users. ServicePool is the container (the group) of this elements. @@ -74,12 +76,12 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods # so we need to store the publication id here (or the revision, but we need to store something) # storing the id simplifies the queries publication: 'models.ForeignKey[ServicePoolPublication | None]' = models.ForeignKey( - ServicePoolPublication, - on_delete=models.CASCADE, - null=True, - blank=True, - related_name='userServices', - ) + ServicePoolPublication, + on_delete=models.CASCADE, + null=True, + blank=True, + related_name='userServices', + ) unique_id = models.CharField( max_length=128, default='', db_index=True @@ -110,7 +112,9 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods ) # Cache level must be 1 for L1 or 2 for L2, 0 if it is not cached service src_hostname = models.CharField(max_length=MAX_DNS_NAME_LENGTH, default='') - src_ip = models.CharField(max_length=MAX_IPV6_LENGTH, default='') # Source IP of the user connecting to the service. Max length is 45 chars (ipv6) + src_ip = models.CharField( + max_length=MAX_IPV6_LENGTH, default='' + ) # Source IP of the user connecting to the service. Max length is 45 chars (ipv6) # "fake" declarations for type checking # objects: 'models.manager.Manager["UserService"]' @@ -118,7 +122,7 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods sessions: 'models.manager.RelatedManager[UserServiceSession]' accounting: 'AccountUsage' - class Meta(UUIDModel.Meta): + class Meta(UUIDModel.Meta): # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -316,8 +320,12 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods self.src_ip = ip[:MAX_IPV6_LENGTH] self.src_hostname = hostname[:MAX_DNS_NAME_LENGTH] - if(len(ip) > MAX_IPV6_LENGTH or len(hostname) > MAX_DNS_NAME_LENGTH): - logger.info('Truncated connection source data to %s/%s', self.src_ip, self.src_hostname) + if len(ip) > MAX_IPV6_LENGTH or len(hostname) > MAX_DNS_NAME_LENGTH: + logger.info( + 'Truncated connection source data to %s/%s', + self.src_ip, + self.src_hostname, + ) self.save(update_fields=['src_ip', 'src_hostname']) @@ -330,7 +338,10 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods :note: If the transport did not notified this data, this may be "empty" """ - return (self.src_ip or '0.0.0.0', self.src_hostname or 'unknown') # nosec: no binding address + return ( + self.src_ip or '0.0.0.0', # nosec: not a binding address + self.src_hostname or 'unknown', + ) def getOsManager(self) -> typing.Optional['OSManager']: return self.deployed_service.osmanager @@ -436,7 +447,8 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods :note: If the state is Fase (set to not in use), a check for removal of this deployed service is launched. """ - from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel + # pylint: disable=import-outside-toplevel + from uds.core.managers import userServiceManager self.in_use = inUse self.in_use_date = getSqlDatetime() @@ -513,9 +525,10 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods """ Returns if this service is ready (not preparing or marked for removal) """ - # Call to isReady of the instance - from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel + # pylint: disable=import-outside-toplevel + from uds.core.managers import userServiceManager + # Call to isReady of the instance return userServiceManager().isReady(self) def isInMaintenance(self) -> bool: @@ -537,7 +550,8 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods """ Asks the UserServiceManager to cancel the current operation of this user deployed service. """ - from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel + # pylint: disable=import-outside-toplevel + from uds.core.managers import userServiceManager userServiceManager().cancel(self) @@ -563,7 +577,8 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods Args: cacheLevel: New cache level to put object in """ - from uds.core.managers import userServiceManager # pylint: disable=import-outside-toplevel + # pylint: disable=import-outside-toplevel + from uds.core.managers import userServiceManager userServiceManager().moveToLevel(self, cacheLevel) @@ -617,9 +632,9 @@ class UserService(UUIDModel): # pylint: disable=too-many-public-methods Returns True if this user service does not needs an publication, or if this deployed service publication is the current one """ return ( - (self.deployed_service.service and self.deployed_service.service.getType().publicationType is None) - or self.publication == self.deployed_service.activePublication() - ) + self.deployed_service.service + and self.deployed_service.service.getType().publicationType is None + ) or self.publication == self.deployed_service.activePublication() # Utility for logging def log(self, message: str, level: int = log.INFO) -> None: diff --git a/server/src/uds/models/user_service_property.py b/server/src/uds/models/user_service_property.py index 2783c6b59..a83cf4b99 100644 --- a/server/src/uds/models/user_service_property.py +++ b/server/src/uds/models/user_service_property.py @@ -55,7 +55,7 @@ class UserServiceProperty(models.Model): # pylint: disable=too-many-public-meth # "fake" declarations for type checking # objects: 'models.manager.Manager[UserServiceProperty]' - class Meta: + class Meta: # pylint: disable=too-few-public-methods """ Meta class to declare default order and unique multiple field index """ @@ -69,6 +69,4 @@ class UserServiceProperty(models.Model): # pylint: disable=too-many-public-meth ] def __str__(self) -> str: - return "Property of {}. {}={}".format( - self.user_service.pk, self.name, self.value - ) + return f'Property of {self.user_service.pk}. {self.name}={self.value}'