⚡ Bolt: Implement blockchain integrity for Escalation Audit#649
Conversation
Implemented a performance-optimized blockchain-style integrity chain for escalation audit logs.
💡 What:
- Added `integrity_hash` and `previous_integrity_hash` to `EscalationAudit` model.
- Implemented HMAC-SHA256 chaining in `EscalationEngine`.
- Added `audit_last_hash_cache` (ThreadSafeCache) for O(1) creation path.
- Added `/api/audit/{audit_id}/blockchain-verify` for O(1) verification.
- Updated `init_db.py` with migration logic.
🎯 Why:
Ensures the immutability and auditability of the escalation trail, preventing unauthorized tampering with government records while maintaining high performance via in-memory caching of the latest chain link.
📊 Impact:
- Enables cryptographic verification of audit records.
- O(1) chaining performance (eliminates DB lookup for previous hash).
- O(1) single-record verification.
🔬 Measurement:
Verified with `tests/test_audit_blockchain.py` confirming valid chaining and detection of tampered records.
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
✅ Deploy Preview for fixmybharat canceled.
|
🙏 Thank you for your contribution, @RohanExploit!PR Details:
Quality Checklist:
Review Process:
Note: The maintainers will monitor code quality and ensure the overall project flow isn't broken. |
There was a problem hiding this comment.
1 issue found across 5 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/escalation_engine.py">
<violation number="1" location="backend/escalation_engine.py:257">
P1: The cache read, hash computation, DB commit, and cache update are not serialized, so concurrent escalations will both read the same `prev_hash` and commit audit records with identical `previous_integrity_hash` values—breaking the chain.
Wrap the entire hash-chain section in a dedicated lock (or use a DB-level advisory lock) to ensure only one audit record is chained at a time.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
📝 WalkthroughWalkthroughThis pull request introduces blockchain-style integrity verification for escalation audits. It adds a dedicated cache for audit hashes, extends the Changes
Sequence DiagramsequenceDiagram
participant Client
participant EscalationEngine as Escalation Engine
participant Cache
participant DB as Database
participant AuthConfig as Auth Config
Client->>EscalationEngine: escalate_grievance()
EscalationEngine->>Cache: get prev audit hash
alt Cache Hit
Cache-->>EscalationEngine: prev_hash
else Cache Miss
EscalationEngine->>DB: query previous EscalationAudit
DB-->>EscalationEngine: prev_hash (or None)
end
EscalationEngine->>AuthConfig: get_auth_config().secret_key
AuthConfig-->>EscalationEngine: secret_key
EscalationEngine->>EscalationEngine: compute HMAC-SHA256<br/>(grievance_id, jurisdiction,<br/>reason, prev_hash)
EscalationEngine->>DB: create EscalationAudit<br/>(integrity_hash,<br/>previous_integrity_hash)
DB-->>EscalationEngine: audit_record
EscalationEngine->>DB: commit()
DB-->>EscalationEngine: success
EscalationEngine->>Cache: update with new hash
Cache-->>EscalationEngine: ok
EscalationEngine-->>Client: escalation_result
sequenceDiagram
participant Client
participant Router as Grievances Router
participant DB as Database
participant AuthConfig as Auth Config
Client->>Router: GET /audit/{audit_id}/blockchain-verify
Router->>DB: fetch EscalationAudit record
alt Audit Found
DB-->>Router: audit (integrity_hash,<br/>previous_integrity_hash, etc.)
Router->>AuthConfig: get_auth_config().secret_key
AuthConfig-->>Router: secret_key
Router->>Router: recompute HMAC-SHA256<br/>(fields + previous_hash)
alt Hashes Match
Router-->>Client: BlockchainVerificationResponse<br/>(is_valid: true)
else Hashes Differ
Router-->>Client: BlockchainVerificationResponse<br/>(is_valid: false)
end
else Audit Not Found
Router-->>Client: HTTPException (404)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Pull request overview
This PR adds a blockchain-style integrity chain to escalation audit logs to make tampering detectable and to support fast integrity verification.
Changes:
- Added
integrity_hashandprevious_integrity_hashtoEscalationAudit, plus migration/index creation. - Implemented HMAC-SHA256 chaining for new escalation audit records, using an in-memory cache to avoid DB lookups on the hot path.
- Added an API endpoint to verify an individual escalation audit record’s integrity hash.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| backend/routers/grievances.py | Adds /audit/{audit_id}/blockchain-verify endpoint for audit integrity verification. |
| backend/models.py | Extends EscalationAudit with integrity hash fields. |
| backend/init_db.py | Adds migration logic for new columns + index on previous_integrity_hash. |
| backend/escalation_engine.py | Computes/stores chained HMAC integrity hashes when creating escalation audit logs (with cache optimization). |
| backend/cache.py | Introduces audit_last_hash_cache for caching the latest audit chain head. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@backend/escalation_engine.py`:
- Around line 264-283: The integrity hash currently built in hash_content (using
grievance.id, previous_authority, grievance.assigned_authority, reason_str,
prev_hash) omits mutable fields like notes and timestamp, so include those exact
fields when computing integrity_hash and ensure the same canonical serialization
is used when recomputing elsewhere (e.g., backend/routers/grievances.py). Update
the EscalationAudit creation flow to add notes and the timestamp value into
hash_content (serialize timestamp consistently, e.g., ISO8601) and include notes
(normalize/escape or trim whitespace) and reason.value when present; then use
get_auth_config().secret_key with HMAC-SHA256 on that augmented canonical string
so routers can recompute and verify integrity_hash reliably.
In `@backend/init_db.py`:
- Around line 222-234: The migration call is currently disabled so the new
escalation_audits columns (integrity_hash, previous_integrity_hash) and index
won't be applied to existing DBs; open backend/main.py and uncomment/restore the
migrate_db() invocation so migrate_db() runs (before Base.metadata.create_all()
and before any escalation_engine.py operations) during startup, ensuring the
ALTER TABLE and CREATE INDEX steps defined in init_db.py are executed and
existing deployments get the new columns and index applied prior to handling
writes or audit verification.
In `@backend/routers/grievances.py`:
- Around line 456-499: The current verification only recomputes the HMAC for the
single EscalationAudit row; to attest chain continuity also verify that if
audit.previous_integrity_hash is non-empty it matches an existing
EscalationAudit.integrity_hash (i.e. run a follow-up query like
db.query(EscalationAudit.id).filter(EscalationAudit.integrity_hash ==
prev_hash).first()) and treat the audit as invalid if the predecessor row is
missing or not found (allow empty/None as the genesis case); update the returned
message and is_valid accordingly and, separately, add a DB index/uniqueness
constraint on EscalationAudit.integrity_hash to make that lookup safe and
prevent forks.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: ee95c57c-96b8-48f1-bbe8-76bacd4d0461
📒 Files selected for processing (5)
backend/cache.pybackend/escalation_engine.pybackend/init_db.pybackend/models.pybackend/routers/grievances.py
⚡ Bolt: Implement blockchain integrity for Escalation Audit
Implemented a performance-optimized blockchain-style integrity chain for escalation audit logs.
💡 What:
integrity_hashandprevious_integrity_hashtoEscalationAuditmodel.EscalationEngine.audit_last_hash_cache(ThreadSafeCache) for O(1) creation path./api/audit/{audit_id}/blockchain-verifyfor O(1) verification.init_db.pywith migration logic.🎯 Why:
Ensures the immutability and auditability of the escalation trail, preventing unauthorized tampering with government records while maintaining high performance via in-memory caching of the latest chain link.
📊 Impact:
🔬 Measurement:
Verified with
tests/test_audit_blockchain.pyconfirming valid chaining and detection of tampered records.PR created automatically by Jules for task 15592076955393926344 started by @RohanExploit
Summary by cubic
Add blockchain-style integrity to escalation audit logs using HMAC-SHA256 chaining for tamper detection. Provides O(1) write and verify, plus an API to validate a specific audit record.
New Features
integrity_hashandprevious_integrity_hashtoEscalationAudit.EscalationEnginewithaudit_last_hash_cachefor O(1) writes./api/audit/{audit_id}/blockchain-verifyfor O(1) integrity checks.init_db.pyto add columns and an index for fast lookups.Migration
init_db.pyto apply DB changes before deploying.secret_keyis configured; changing it will invalidate existing hashes.Written for commit 4d1d51c. Summary will update on new commits.
Summary by CodeRabbit
GET /audit/{audit_id}/blockchain-verify) to validate audit record authenticity