Skip to content

Commit

Permalink
Revised logging integration changes based on code review
Browse files Browse the repository at this point in the history
  • Loading branch information
li-ruihao committed Feb 14, 2025
1 parent 72097f0 commit c0e884f
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 10 deletions.
6 changes: 3 additions & 3 deletions application/Profile/DBProfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def __init__(self, app):
self.activation_email_body_template = f.read()
except OSError as e:
logger.exception('Failed to open "%s"', ACTIVATION_EMAIL_TEMPLATE)
raise e
raise

class User(db.Model):
__table_args__ = {"schema": "ictrl"}
Expand Down Expand Up @@ -217,7 +217,7 @@ def query(self):
"username": session.username
}

logger.info("Query user sessions successful, all user sessions:\n%s", json.dumps(_profile))
logger.info("User sessions queried successfully.")

return _profile

Expand Down Expand Up @@ -436,6 +436,6 @@ def send_activation_email(self, username):
expire_min=int(ACTIVATION_TTL_SECOND / 60))
send_email(user.email, 'Activate Your iCtrl Account', body)

logger.info("Successfully sent out activation email to email=%s", user.email)
logger.info("Successfully sent out activation email to user ID=%s", user.id)

return True
8 changes: 4 additions & 4 deletions application/Profile/LocalProfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,13 @@ def add_session(self, host, username, conn=None) -> tuple[bool, str]:

def delete_session(self, session_id) -> tuple[bool, str]:
if session_id not in self._profile['sessions']:
logger.error('Cannot delete session %s, session does not exist', session_id)
logger.warning('Cannot delete session %s, session does not exist', session_id)
return False, f'failed: session {session_id} does not exist'

try:
os.remove(os.path.join(PRIVATE_KEY_PATH, session_id))
except FileNotFoundError:
logger.exception('No valid SSH key found for deletion')
logger.warning('No valid SSH key found for deletion')

self._profile['sessions'].pop(session_id)
self.save_profile()
Expand All @@ -121,7 +121,7 @@ def delete_session(self, session_id) -> tuple[bool, str]:

def change_host(self, session_id, new_host) -> tuple[bool, str]:
if session_id not in self._profile['sessions']:
logger.error("Cannot change host, session %s does not exist", session_id)
logger.warning("Cannot change host, session %s does not exist", session_id)
return False, f'failed: session {session_id} does not exist'

self._profile["sessions"][session_id]['host'] = new_host
Expand Down Expand Up @@ -206,7 +206,7 @@ def get_session_vnc_credentials(self, session_id) -> tuple[bool, object]:
logger.error("Cannot retrieve session %s, session does not exist", session_id)
return False, f'failed: session {session_id} does not exist'

logger.info("Retrieving vnc credentials for session %s", session_id)
logger.debug("Retrieving VNC credentials for session %s", session_id)
if 'vnc_credentials' in self._profile['sessions'][session_id]:
json_str = base64.b64decode(self._profile['sessions'][session_id]['vnc_credentials'])
return True, json.loads(json_str.decode('ascii'))
Expand Down
5 changes: 3 additions & 2 deletions application/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
def makedir_if_not_exists(path):
if not os.path.exists(path):
os.mkdir(path)
logger.info('Created directory, path = %s', path)
logger.info('Created directory at path = %s', path)


# setup profile path
Expand All @@ -38,7 +38,8 @@ def makedir_if_not_exists(path):
elif platform.system() == "Darwin" or 'Linux':
PROFILE_PATH = os.path.join(os.path.expanduser("~"), ".ictrl")
else:
logger.error("Operating System: %s not supported", platform.system())
logger.error("Unsupported operating system detected - OS: %s, Version: %s, Machine: %s",
platform.system(), platform.version(), platform.machine())
raise SystemError(f"Operating System: {platform.system()} not supported")

makedir_if_not_exists(PROFILE_PATH)
Expand Down
34 changes: 33 additions & 1 deletion application/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def send_email(to_email, subject, body):

server_ssl.sendmail(sender_email, to_email, msg.as_string())

logger.info('Successfully sent email from %s to %s', sender_email, to_email)
logger.info('Successfully sent email from %s to %s', mask_email(sender_email), mask_email(to_email))

server_ssl.close()

Expand Down Expand Up @@ -125,3 +125,35 @@ def local_auth(headers, abort_func):
abort_func(403, "You are not authorized to access this API.")

return auth_passed


def mask_email(email: str) -> str:
"""
Masks an email address for secure logging by keeping first character and domain.
Example:
mask_email("user@example.com")
'u***@example.com'
mask_email("a.b.c@sub.example.com")
'a***@sub.example.com'
mask_email("invalid.email")
'***@***'
Args:
email: The email address to mask
Returns:
Masked email address with only first character and domain visible
"""
try:
if '@' not in email:
return '***@***'

local, domain = email.split('@', 1)
if not local:
return '***@' + domain

masked = local[0] + '*' * (len(local) - 1)
return f'{masked}@{domain}'
except Exception:
return '***@***' # Fallback for any parsing errors

0 comments on commit c0e884f

Please sign in to comment.