-
Notifications
You must be signed in to change notification settings - Fork 35
⚡ Bolt: HMAC-SHA256 Blockchain for Escalation Audits #642
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,11 +4,16 @@ | |
| """ | ||
|
|
||
| import datetime | ||
| import hashlib | ||
| import hmac | ||
| import os | ||
| from typing import List, Dict, Any, Optional | ||
| from sqlalchemy.orm import Session | ||
| from sqlalchemy import and_, or_ | ||
| from backend.models import Grievance, Jurisdiction, EscalationAudit, GrievanceStatus, JurisdictionLevel, EscalationReason, SeverityLevel | ||
| from backend.database import SessionLocal | ||
| from backend.cache import audit_last_hash_cache | ||
| from backend.config import get_config | ||
| from backend.routing_service import RoutingService | ||
| from backend.sla_config_service import SLAConfigService | ||
|
|
||
|
|
@@ -41,8 +46,10 @@ def evaluate_and_escalate_grievances(self, db: Session = None) -> Dict[str, int] | |
| Returns: | ||
| Dictionary with escalation statistics | ||
| """ | ||
| should_close = False | ||
| if db is None: | ||
| db = SessionLocal() | ||
| should_close = True | ||
|
|
||
| try: | ||
| # Get grievances that need evaluation | ||
|
|
@@ -63,7 +70,7 @@ def evaluate_and_escalate_grievances(self, db: Session = None) -> Dict[str, int] | |
| } | ||
|
|
||
| finally: | ||
| if db is not SessionLocal(): | ||
| if should_close: | ||
| db.close() | ||
|
|
||
| def escalate_grievance_severity(self, grievance_id: int, new_severity: SeverityLevel, | ||
|
|
@@ -80,8 +87,10 @@ def escalate_grievance_severity(self, grievance_id: int, new_severity: SeverityL | |
| Returns: | ||
| True if escalation successful | ||
| """ | ||
| should_close = False | ||
| if db is None: | ||
| db = SessionLocal() | ||
| should_close = True | ||
|
|
||
| try: | ||
| grievance = db.query(Grievance).filter(Grievance.id == grievance_id).first() | ||
|
|
@@ -108,7 +117,7 @@ def escalate_grievance_severity(self, grievance_id: int, new_severity: SeverityL | |
| print(f"Error escalating grievance severity: {e}") | ||
| return False | ||
| finally: | ||
| if db is not SessionLocal(): | ||
| if should_close: | ||
| db.close() | ||
|
|
||
| def manual_escalate(self, grievance_id: int, reason: str = "", db: Session = None) -> bool: | ||
|
|
@@ -123,8 +132,10 @@ def manual_escalate(self, grievance_id: int, reason: str = "", db: Session = Non | |
| Returns: | ||
| True if escalation successful | ||
| """ | ||
| should_close = False | ||
| if db is None: | ||
| db = SessionLocal() | ||
| should_close = True | ||
|
|
||
| try: | ||
| grievance = db.query(Grievance).filter(Grievance.id == grievance_id).first() | ||
|
|
@@ -134,7 +145,7 @@ def manual_escalate(self, grievance_id: int, reason: str = "", db: Session = Non | |
| return self._escalate_grievance(grievance, EscalationReason.MANUAL, db, reason) | ||
|
|
||
| finally: | ||
| if db is not SessionLocal(): | ||
| if should_close: | ||
| db.close() | ||
|
|
||
| def _get_grievances_for_evaluation(self, db: Session) -> List[Grievance]: | ||
|
|
@@ -170,7 +181,13 @@ def _should_escalate(self, grievance: Grievance, db: Session) -> bool: | |
| """ | ||
| # Check if SLA is breached | ||
| now = datetime.datetime.now(datetime.timezone.utc) | ||
| if grievance.sla_deadline >= now: | ||
|
|
||
| # Handle naive datetimes from SQLite | ||
| deadline = grievance.sla_deadline | ||
| if deadline and deadline.tzinfo is None: | ||
| deadline = deadline.replace(tzinfo=datetime.timezone.utc) | ||
|
|
||
| if deadline >= now: | ||
| return False | ||
|
|
||
| # Check if escalation is possible | ||
|
|
@@ -248,18 +265,45 @@ def _escalate_grievance(self, grievance: Grievance, reason: EscalationReason, | |
| # Recalculate SLA | ||
| self._recalculate_sla(grievance, db) | ||
|
|
||
| # Optimized Blockchain logic: Cache-first retrieval to ensure O(1) creation path | ||
| prev_hash = audit_last_hash_cache.get("last_hash") | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Under concurrent escalations, two transactions can read the same Prompt for AI agents |
||
| if prev_hash is None: | ||
| # Cache miss: Fetch only the last hash from DB | ||
| last_audit = db.query(EscalationAudit.integrity_hash).order_by(EscalationAudit.id.desc()).first() | ||
| prev_hash = last_audit[0] if last_audit and last_audit[0] else "" | ||
| # Populate cache for subsequent escalations | ||
| audit_last_hash_cache.set(data=prev_hash, key="last_hash") | ||
|
Comment on lines
+268
to
+275
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make chain-head advancement atomic across requests.
Use a DB-backed chain-head row or another cross-process lock/CAS so “read head → insert audit → advance head” happens atomically. Also applies to: 304-305 🤖 Prompt for AI Agents |
||
|
|
||
|
Comment on lines
+268
to
+276
|
||
| # HMAC-SHA256 chaining: hash(grievance_id|prev_auth|new_auth|reason|prev_hash) | ||
| # Using centralized config to avoid hardcoded secret fallbacks (Security compliance) | ||
| app_config = get_config() | ||
| secret_key = app_config.secret_key.encode('utf-8') | ||
| reason_val = reason.value if hasattr(reason, 'value') else reason | ||
| hash_content = f"{grievance.id}|{previous_authority}|{grievance.assigned_authority}|{reason_val}|{prev_hash}" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: The Prompt for AI agents |
||
|
|
||
| integrity_hash = hmac.new( | ||
| secret_key, | ||
| hash_content.encode('utf-8'), | ||
| hashlib.sha256 | ||
| ).hexdigest() | ||
|
|
||
|
Comment on lines
+277
to
+289
|
||
| # Create audit log | ||
| audit_log = EscalationAudit( | ||
| grievance_id=grievance.id, | ||
| previous_authority=previous_authority, | ||
| new_authority=grievance.assigned_authority, | ||
| reason=reason, | ||
| notes=notes | ||
| notes=notes, | ||
| integrity_hash=integrity_hash, | ||
| previous_integrity_hash=prev_hash | ||
|
Comment on lines
+277
to
+298
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seal the manual justification text too.
🤖 Prompt for AI Agents |
||
| ) | ||
|
|
||
| db.add(audit_log) | ||
| db.commit() | ||
|
|
||
| # Update cache after successful commit to maintain chain integrity | ||
| audit_last_hash_cache.set(data=integrity_hash, key="last_hash") | ||
|
|
||
| return True | ||
|
|
||
| except Exception as e: | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -6,6 +6,7 @@ | |||||||||||||||||||||||
| import json | ||||||||||||||||||||||||
| import logging | ||||||||||||||||||||||||
| import hashlib | ||||||||||||||||||||||||
| import hmac | ||||||||||||||||||||||||
| from datetime import datetime, timezone | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| from backend.database import get_db | ||||||||||||||||||||||||
|
|
@@ -21,6 +22,7 @@ | |||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
| from backend.grievance_service import GrievanceService | ||||||||||||||||||||||||
| from backend.closure_service import ClosureService | ||||||||||||||||||||||||
| from backend.config import get_config | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| logger = logging.getLogger(__name__) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
@@ -192,9 +194,8 @@ def manual_escalate_grievance( | |||||||||||||||||||||||
| raise HTTPException(status_code=404, detail="Grievance not found") | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # Perform manual escalation | ||||||||||||||||||||||||
| success = grievance_service.escalation_engine.escalate_grievance_severity( | ||||||||||||||||||||||||
| success = grievance_service.escalation_engine.manual_escalate( | ||||||||||||||||||||||||
| grievance_id=grievance_id, | ||||||||||||||||||||||||
| new_severity=grievance.severity, # Keep same severity, just escalate jurisdiction | ||||||||||||||||||||||||
| reason=reason, | ||||||||||||||||||||||||
| db=db | ||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
|
|
@@ -496,3 +497,59 @@ def verify_grievance_blockchain( | |||||||||||||||||||||||
| except Exception as e: | ||||||||||||||||||||||||
| logger.error(f"Error verifying grievance blockchain for {grievance_id}: {e}", exc_info=True) | ||||||||||||||||||||||||
| raise HTTPException(status_code=500, detail="Failed to verify grievance integrity") | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| @router.get("/audit/{audit_id}/blockchain-verify", response_model=BlockchainVerificationResponse) | ||||||||||||||||||||||||
| def verify_audit_blockchain( | ||||||||||||||||||||||||
| audit_id: int, | ||||||||||||||||||||||||
| db: Session = Depends(get_db) | ||||||||||||||||||||||||
| ): | ||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||
| Verify the cryptographic integrity of an escalation audit record using HMAC-SHA256 chaining. | ||||||||||||||||||||||||
| Optimized: Uses previous_integrity_hash column for O(1) verification. | ||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||
| try: | ||||||||||||||||||||||||
| audit = db.query(EscalationAudit).filter(EscalationAudit.id == audit_id).first() | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| if not audit: | ||||||||||||||||||||||||
| raise HTTPException(status_code=404, detail="Audit record not found") | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # Determine previous hash (O(1) from stored column) | ||||||||||||||||||||||||
| prev_hash = audit.previous_integrity_hash or "" | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # HMAC-SHA256 chaining: hash(grievance_id|prev_auth|new_auth|reason|prev_hash) | ||||||||||||||||||||||||
| # Using centralized config for secret key to ensure security compliance | ||||||||||||||||||||||||
| app_config = get_config() | ||||||||||||||||||||||||
| secret_key = app_config.secret_key.encode('utf-8') | ||||||||||||||||||||||||
| reason_val = audit.reason.value if hasattr(audit.reason, 'value') else audit.reason | ||||||||||||||||||||||||
| hash_content = f"{audit.grievance_id}|{audit.previous_authority}|{audit.new_authority}|{reason_val}|{prev_hash}" | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| computed_hash = hmac.new( | ||||||||||||||||||||||||
| secret_key, | ||||||||||||||||||||||||
| hash_content.encode('utf-8'), | ||||||||||||||||||||||||
| hashlib.sha256 | ||||||||||||||||||||||||
| ).hexdigest() | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| if audit.integrity_hash is None: | ||||||||||||||||||||||||
| is_valid = False | ||||||||||||||||||||||||
| message = "No integrity hash present for this audit record; cryptographic integrity cannot be verified." | ||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||
| is_valid = hmac.compare_digest(computed_hash, audit.integrity_hash) | ||||||||||||||||||||||||
| message = ( | ||||||||||||||||||||||||
| "Integrity verified. This escalation audit record is cryptographically sealed." | ||||||||||||||||||||||||
| if is_valid | ||||||||||||||||||||||||
| else "Integrity check failed! The audit data does not match its cryptographic seal." | ||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| return BlockchainVerificationResponse( | ||||||||||||||||||||||||
| is_valid=is_valid, | ||||||||||||||||||||||||
| current_hash=audit.integrity_hash, | ||||||||||||||||||||||||
| computed_hash=computed_hash, | ||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P1: Returning Prompt for AI agents |
||||||||||||||||||||||||
| message=message | ||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
|
Comment on lines
+544
to
+549
|
||||||||||||||||||||||||
| return BlockchainVerificationResponse( | |
| is_valid=is_valid, | |
| current_hash=audit.integrity_hash, | |
| computed_hash=computed_hash, | |
| message=message | |
| ) | |
| return { | |
| "is_valid": is_valid, | |
| "current_hash": audit.integrity_hash, | |
| "message": message | |
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unused import:
osis imported but not referenced in this module after the changes. Please remove it to avoid lint warnings and keep imports minimal.