def test_mocked_time(self): mock_time = datetime.fromtimestamp(42) time_source.set_time(mock_time) assert time_source.mock() == False assert abs(datetime.now() - time_source.time()) < self.ALLOWED_TIME_DIFF assert time_source.mock(True) assert mock_time == time_source.time() assert time_source.mock(False) == False assert abs(datetime.now() - time_source.time()) < self.ALLOWED_TIME_DIFF
def test_offset(self): time_source.mock(True) mock_time = datetime.fromtimestamp(42) time_source.set_time(mock_time) td = timedelta(seconds=28) assert abs(mock_time - time_source.time()) < self.ALLOWED_TIME_DIFF time_source.offset_time(td) assert abs(mock_time + td - time_source.time()) < self.ALLOWED_TIME_DIFF time_source.offset_time(-td) assert abs(mock_time - time_source.time()) < self.ALLOWED_TIME_DIFF
def check_condition(main_data, notification_preferences_by_scan_order_id: Dict[str, dict])\ -> Tuple[Set, Set]: expiration_by_target_id = {} for single_res in main_data: try: key = single_res.Target.id val = single_res.ScanResults.certificate_information.received_certificate_chain_list.not_after() expiration_by_target_id[key] = val except AttributeError as e: logger.info(f"NT0002 NotificationTypeExpiration: Handled AttributeError, most likely due to failed scan. Target id: {key}") scan_order_ids_expired = set() scan_order_ids_nearing_expiration = set() for single_res in main_data: try: scan_order_id = single_res.ScanOrder.id target_id = single_res.ScanOrder.target_id expires = expiration_by_target_id[target_id] notification_settings = notification_preferences_by_scan_order_id[scan_order_id] # todo: make filtering based on notification settings. Currently notifying about 1 day expire only if expires < time_source.time(): scan_order_ids_expired.add(single_res.ScanOrder.id) continue if expires > time_source.time() + datetime.timedelta( days=NotificationsConfig.start_sending_notifications_x_days_before_expiration): continue notifications_x_days_before_expiration \ = extract_and_parse_notifications_x_days_before_expiration(notification_settings) certificate_chain = single_res.LastScan.result.certificate_information.received_certificate_chain_list not_after = certificate_chain.not_after() days_remaining = (not_after - time_source.time()).days if days_remaining in notifications_x_days_before_expiration: scan_order_ids_nearing_expiration.add(single_res.ScanOrder.id) except KeyError as e: logger.info(f"NT0003 NotificationTypeExpiration: Handled KeyError, most likely due to failed scan.") logger.info(f"NT0004 scan_order_ids_expired orders ids: {scan_order_ids_expired}") logger.info(f"NT0005 scan_order_ids_nearing_expiration ids: {scan_order_ids_nearing_expiration}") return scan_order_ids_expired, scan_order_ids_nearing_expiration
def get_scan_history( user_id: int, x_days: int = 30 ): # -> Optional[Tuple[db_models.LastScan, db_models.ScanResults]]: today = time_source.time() start = today - datetime.timedelta(days=x_days) start_timestamp = datetime_to_timestamp(start) res = db_models.db.session \ .query(db_models.ScanOrder, db_models.Target, db_models.ScanResultsHistory, db_models.ScanResultsSimplified, db_models.ServerInfo) \ .outerjoin(db_models.ScanResultsHistory, db_models.ScanResultsHistory.target_id == db_models.ScanOrder.target_id) \ .outerjoin(db_models.ScanResultsSimplified, db_models.ScanResultsHistory.scanresult_id == db_models.ScanResultsSimplified.scanresult_id) \ .outerjoin(db_models.ScanResults, db_models.ScanResultsHistory.scanresult_id == db_models.ScanResults.id) \ .outerjoin(db_models.ServerInfo, db_models.ScanResults.server_info_id == db_models.ServerInfo.id) \ .filter(db_models.ScanOrder.target_id == db_models.Target.id) \ .filter(db_models.ScanOrder.active == True) \ .filter(db_models.ScanOrder.user_id == user_id) \ .filter(db_models.ScanResultsHistory.timestamp >= start_timestamp) \ .all() return res
def api_resend_validation_email(): user_id = authentication_utils.get_user_id_from_jwt_or_exception() REQUEST_ERROR_MSG = "Request failed. Possible reasons:\n" \ "- Validation email to this email address was send less then 1 minute ago.\n"\ "- User did not register this email address, so there is nothing to validate.\n" email_to_resend_validation_email_to = json.loads(request.data).get( "email", "").strip() if len(email_to_resend_validation_email_to) == 0: return "No email argument provided. Aborting.", 400 res = db_models.db.session \ .query(db_models.TmpRandomCodes) \ .filter(db_models.TmpRandomCodes.user_id == user_id) \ .filter(db_models.TmpRandomCodes.activity == randomCodes.ActivityType.MAIL_VALIDATION.name) \ .filter(db_models.TmpRandomCodes.timestamp > datetime_to_timestamp(time_source.time() - datetime.timedelta(minutes=1))) \ .all() if res is not None: for x in res: if x.params == email_to_resend_validation_email_to: return REQUEST_ERROR_MSG, 400 res = db_models.db.session \ .query(db_models.MailConnections) \ .filter(db_models.MailConnections.user_id == user_id) \ .filter(db_models.MailConnections.email == email_to_resend_validation_email_to) \ .first() if res is None: return REQUEST_ERROR_MSG, 400 send_mail_validation(user_id, email_to_resend_validation_email_to) return f'ok', 200
def __init__(self, single_res, notification_preferences): self.single_res = single_res self.notification_preferences = notification_preferences self.scan_order = single_res.ScanOrder self.certificate_chain = single_res.LastScan.result.certificate_information.received_certificate_chain_list self.days_remaining = (self.certificate_chain.not_after() - time_source.time()).days self.event_type = EventType.ClosingExpiration if self.days_remaining >= 0 else EventType.AlreadyExpired
def create_if_not_existent(cls, target_id): try: rand_time_offset = random.randrange(0, SchedulerConfig.max_first_scan_delay) enqueue_time = time_source.time()\ - datetime.timedelta(seconds=SchedulerConfig.enqueue_min_time) \ + datetime.timedelta(seconds=rand_time_offset) # res = LastScan(id=target_id, last_enqueued=int(enqueue_time.timestamp())) res = LastScan(target_id=target_id, last_enqueued=datetime_to_timestamp(enqueue_time)) db.session.add(res) db.session.commit() except Exception as e: db.session.rollback() logger.warning(f"SC0007 Failed creating last_scan with error {e}") pass
def create_and_save_random_code(activity: ActivityType, user_id: int, expire_in_n_minutes: int, params: str = None) -> str: if params is None: params = "" res = db_models.TmpRandomCodes() res.user_id = user_id res.activity = activity.name res.expires = datetime_to_timestamp(time_source.time() + datetime.timedelta( minutes=expire_in_n_minutes)) res.code = gen_random_code() res.params = params db_models.db.session.add(res) db_models.db.session.commit() return res.code
def offset_time_back_from_now(n_secs): return time_source.time() - datetime.timedelta(seconds=n_secs)
def default_current_time(query_compare_time=None): if query_compare_time is None: query_compare_time = time_source.time() return query_compare_time
def test_set_now(self): time_source.mock(True) time_source.set_now() assert abs(datetime.now() - time_source.time()) < self.ALLOWED_TIME_DIFF
def test_current_time(self): test_time = time_source.time() assert abs(datetime.now() - test_time) < self.ALLOWED_TIME_DIFF assert abs(datetime.fromtimestamp(0) - test_time) > self.ALLOWED_TIME_DIFF