"""Logic managing the security level setting of the Trustpoint."""from__future__importannotationsfromtypingimportTYPE_CHECKINGfrommanagement.modelsimportSecurityConfigfrommanagement.securityimportLEVEL_FEATURE_MAPfromtrustpoint.loggerimportLoggerMixinifTYPE_CHECKING:frommanagement.security.featuresimportSecurityFeature
[docs]classSecurityManager(LoggerMixin):"""Manages the security level setting of the Trustpoint."""
[docs]defis_feature_allowed(self,feature:SecurityFeature,target_level:None|str=None)->bool:"""Checks if the specified feature is allowed under the given security level. If 'target_level' is None, the current security level is used. """sec_level=self.get_security_level()iftarget_levelisNoneelsetarget_levelifsec_level==SecurityConfig.SecurityModeChoices.DEV:returnTrue# Convert or cast sec_level to actual SecurityModeChoices if needed:# If sec_level is just a string like '1', get the enumerated type:level_choice=SecurityConfig.SecurityModeChoices(sec_level)# If the level is defined in the dictionary, check membershipallowed_features=LEVEL_FEATURE_MAP.get(level_choice,set())returnfeatureinallowed_features
[docs]defget_security_level(self)->str:"""Returns the string representation of the security_mode, e.g. '0', '1', etc."""returnself.get_security_config_model().security_mode
@classmethod
[docs]defget_features_to_disable(cls,sec_level:str)->list[SecurityFeature]:"""Returns a list of features that must be disabled at the given security level."""dev_features=LEVEL_FEATURE_MAP[SecurityConfig.SecurityModeChoices.DEV]level_choice=SecurityConfig.SecurityModeChoices(sec_level)valid_features=LEVEL_FEATURE_MAP.get(level_choice,set())# The difference is the set of features that are NOT allowed at this level.must_disable=dev_features-valid_featuresreturnlist(must_disable)
[docs]defreset_settings(self,new_sec_mode:str)->None:"""Disables any feature that is not allowed by the new security mode."""features_to_disable=self.get_features_to_disable(new_sec_mode)forfeatureinfeatures_to_disable:self.logger.info('Disabling Feature: %s',feature)feature.disable()
[docs]defget_security_config_model(self)->SecurityConfig:"""Returns the model holding the security settings."""returnSecurityConfig.objects.first()
[docs]defenable_feature(self,feature:SecurityFeature,*args:dict)->None:"""Enables a feature if it is allowed at the current security level."""ifself.is_feature_allowed(feature):feature.enable(*args)