1818
1919try :
2020 from cryptography .fernet import Fernet
21+
2122 CRYPTO_AVAILABLE = True
2223except ImportError :
2324 CRYPTO_AVAILABLE = False
@@ -136,17 +137,18 @@ def __init__(
136137 self ._file_chmod_done = False # Track if chmod has been done
137138
138139 # Encryption setup for L3 audit logs
139- self ._encryption_key = encryption_key
140+ self ._encryption_key : Optional [ bytes ] = encryption_key
140141 self ._fernet : Optional [Any ] = None
141142 if audit_level == 'L3' :
142143 if not CRYPTO_AVAILABLE :
143144 raise ValueError (
144145 'L3 audit level requires cryptography library. Install with: pip install cryptography'
145146 )
146- if encryption_key is None :
147+ if self . _encryption_key is None :
147148 # Generate a new encryption key if not provided
148149 self ._encryption_key = self ._load_or_save_encryption_key ()
149150 try :
151+ assert self ._encryption_key is not None
150152 self ._fernet = Fernet (self ._encryption_key )
151153 except Exception as exc :
152154 raise ValueError (f'Failed to initialize L3 encryption: { exc } ' ) from exc
@@ -231,7 +233,9 @@ def _load_or_save_encryption_key(self) -> bytes:
231233 if len (key ) == 44 : # Fernet key length
232234 return key
233235 except OSError as exc :
234- raise ValueError (f'Failed to load encryption key from { key_path } : { exc } ' ) from exc
236+ raise ValueError (
237+ f'Failed to load encryption key from { key_path } : { exc } '
238+ ) from exc
235239
236240 key = Fernet .generate_key ()
237241 try :
@@ -240,7 +244,9 @@ def _load_or_save_encryption_key(self) -> bytes:
240244 key_path .write_bytes (key )
241245 key_path .chmod (0o600 )
242246 except OSError as exc :
243- raise ValueError (f'Failed to save encryption key to { key_path } : { exc } ' ) from exc
247+ raise ValueError (
248+ f'Failed to save encryption key to { key_path } : { exc } '
249+ ) from exc
244250 return key
245251
246252 def get_chain_key (self ) -> bytes :
@@ -384,8 +390,12 @@ def record(self, event_type: str, run_id: str, **payload: Any) -> AuditEvent:
384390 raise ValueError ('L3 encryption not initialized' )
385391 try :
386392 payload_json = json .dumps (event .payload , sort_keys = True )
387- encrypted_bytes = self ._fernet .encrypt (payload_json .encode ('utf-8' ))
388- payload_to_write = {'encrypted' : encrypted_bytes .decode ('utf-8' )}
393+ encrypted_bytes = self ._fernet .encrypt (
394+ payload_json .encode ('utf-8' )
395+ )
396+ payload_to_write = {
397+ 'encrypted' : encrypted_bytes .decode ('utf-8' )
398+ }
389399 except Exception as exc :
390400 raise ValueError (f'L3 encryption failed: { exc } ' ) from exc
391401
@@ -409,7 +419,9 @@ def record(self, event_type: str, run_id: str, **payload: Any) -> AuditEvent:
409419 entry_data = json .loads (canonical )
410420 entry_data ['hash' ] = current_hash
411421 entry_data ['chain_hmac' ] = chain_hmac
412- handle .write (json .dumps (entry_data , sort_keys = True ).rstrip ('\n ' ) + '\n ' )
422+ handle .write (
423+ json .dumps (entry_data , sort_keys = True ).rstrip ('\n ' ) + '\n '
424+ )
413425 handle .flush ()
414426 os .fsync (handle .fileno ())
415427 # Only chmod once at file creation
@@ -543,7 +555,8 @@ def decrypt_audit_log(
543555 if encryption_key is None :
544556 run_id = audit_path .stem
545557 safe_id = (
546- '' .join (ch for ch in run_id if ch .isalnum () or ch in {'-' , '_' }) or 'run'
558+ '' .join (ch for ch in run_id if ch .isalnum () or ch in {'-' , '_' })
559+ or 'run'
547560 )
548561 key_dir = Path .home () / '.teaagent' / 'audit-encryption'
549562 key_path = key_dir / f'{ safe_id } .enc'
@@ -556,13 +569,17 @@ def decrypt_audit_log(
556569 if len (encryption_key ) != 44 : # Fernet key length
557570 raise ValueError (f'Invalid encryption key length at { key_path } ' )
558571 except OSError as exc :
559- raise ValueError (f'Failed to load encryption key from { key_path } : { exc } ' ) from exc
572+ raise ValueError (
573+ f'Failed to load encryption key from { key_path } : { exc } '
574+ ) from exc
560575
561576 # Initialize Fernet with the key
562577 try :
563578 fernet = Fernet (encryption_key )
564579 except Exception as exc :
565- raise ValueError (f'Failed to initialize Fernet with provided key: { exc } ' ) from exc
580+ raise ValueError (
581+ f'Failed to initialize Fernet with provided key: { exc } '
582+ ) from exc
566583
567584 # Read and decrypt the audit log
568585 try :
@@ -624,7 +641,9 @@ def decrypt_audit_log(
624641 decrypted_json = decrypted_bytes .decode ('utf-8' )
625642 event ['payload' ] = json .loads (decrypted_json )
626643 except Exception as exc :
627- raise ValueError (f'Failed to decrypt event { event .get ("event_id" )} : { exc } ' ) from exc
644+ raise ValueError (
645+ f'Failed to decrypt event { event .get ("event_id" )} : { exc } '
646+ ) from exc
628647
629648 decrypted_events .append (event )
630649
@@ -636,7 +655,9 @@ def decrypt_audit_log(
636655 }
637656
638657 except OSError as exc :
639- raise ValueError (f'Failed to read audit log from { audit_path } : { exc } ' ) from exc
658+ raise ValueError (
659+ f'Failed to read audit log from { audit_path } : { exc } '
660+ ) from exc
640661 except json .JSONDecodeError as exc :
641662 raise ValueError (f'Failed to parse audit log JSON: { exc } ' ) from exc
642663
0 commit comments