Skip to content

⚡ Bolt: Implement blockchain integrity for Escalation Audit#649

Merged
RohanExploit merged 1 commit into
mainfrom
bolt-escalation-audit-blockchain-15592076955393926344
Apr 8, 2026
Merged

⚡ Bolt: Implement blockchain integrity for Escalation Audit#649
RohanExploit merged 1 commit into
mainfrom
bolt-escalation-audit-blockchain-15592076955393926344

Conversation

@RohanExploit
Copy link
Copy Markdown
Owner

@RohanExploit RohanExploit commented Apr 8, 2026

⚡ Bolt: Implement blockchain integrity for Escalation Audit

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.


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

    • Added integrity_hash and previous_integrity_hash to EscalationAudit.
    • Implemented HMAC-SHA256 chaining in EscalationEngine with audit_last_hash_cache for O(1) writes.
    • Added GET /api/audit/{audit_id}/blockchain-verify for O(1) integrity checks.
    • Updated init_db.py to add columns and an index for fast lookups.
  • Migration

    • Run init_db.py to apply DB changes before deploying.
    • Ensure secret_key is configured; changing it will invalidate existing hashes.

Written for commit 4d1d51c. Summary will update on new commits.

Summary by CodeRabbit

  • New Features
    • Escalation audits now include cryptographic integrity verification to detect unauthorized modifications
    • New API endpoint added (GET /audit/{audit_id}/blockchain-verify) to validate audit record authenticity

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.
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 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 @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

Copilot AI review requested due to automatic review settings April 8, 2026 14:19
@netlify
Copy link
Copy Markdown

netlify Bot commented Apr 8, 2026

Deploy Preview for fixmybharat canceled.

Name Link
🔨 Latest commit 4d1d51c
🔍 Latest deploy log https://app.netlify.com/projects/fixmybharat/deploys/69d663ece831b600086be52d

@RohanExploit RohanExploit temporarily deployed to bolt-escalation-audit-blockchain-15592076955393926344 - vishwaguru-backend PR #649 April 8, 2026 14:19 — with Render Destroyed
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Apr 8, 2026

🙏 Thank you for your contribution, @RohanExploit!

PR Details:

Quality Checklist:
Please ensure your PR meets the following criteria:

  • Code follows the project's style guidelines
  • Self-review of code completed
  • Code is commented where necessary
  • Documentation updated (if applicable)
  • No new warnings generated
  • Tests added/updated (if applicable)
  • All tests passing locally
  • No breaking changes to existing functionality

Review Process:

  1. Automated checks will run on your code
  2. A maintainer will review your changes
  3. Address any requested changes promptly
  4. Once approved, your PR will be merged! 🎉

Note: The maintainers will monitor code quality and ensure the overall project flow isn't broken.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread backend/escalation_engine.py
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 8, 2026

📝 Walkthrough

Walkthrough

This pull request introduces blockchain-style integrity verification for escalation audits. It adds a dedicated cache for audit hashes, extends the EscalationAudit model with integrity hash columns, implements HMAC-SHA256 chaining during escalation creation, and exposes a new endpoint to verify the integrity chain.

Changes

Cohort / File(s) Summary
Blockchain Integrity Infrastructure
backend/cache.py, backend/models.py, backend/init_db.py
Added a thread-safe cache instance for audit hashes, extended EscalationAudit model with integrity_hash and previous_integrity_hash columns (with indexing), and created migration logic to conditionally add these columns and indexes to the escalation_audits table.
Integrity Hash Computation
backend/escalation_engine.py
Enhanced _escalate_grievance to compute HMAC-SHA256 integrity hashes chaining each audit to its predecessor, retrieve prior hashes from cache (with DB fallback on miss), store computed hashes in the audit record, and update cache after commit.
Integrity Hash Verification
backend/routers/grievances.py
Added GET /audit/{audit_id}/blockchain-verify endpoint to fetch audit details, recompute integrity hashes using chained values, and verify against stored hashes via HMAC-SHA256 comparison, returning validation status and hash details.

Sequence Diagram

sequenceDiagram
    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
Loading
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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 Hashing through the audit trail so long,
Each escalation linked, ever strong,
HMAC chains in rabbity delight,
Blockchain magic shimmering bright!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: implementing blockchain integrity for escalation audit records.
Description check ✅ Passed The description covers all required template sections with comprehensive details about what, why, and impact.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt-escalation-audit-blockchain-15592076955393926344

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_hash and previous_integrity_hash to EscalationAudit, 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.

Comment thread backend/escalation_engine.py
Comment thread backend/escalation_engine.py
Comment thread backend/routers/grievances.py
Comment thread backend/escalation_engine.py
Comment thread backend/cache.py
Comment thread backend/escalation_engine.py
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 25593c4 and 4d1d51c.

📒 Files selected for processing (5)
  • backend/cache.py
  • backend/escalation_engine.py
  • backend/init_db.py
  • backend/models.py
  • backend/routers/grievances.py

Comment thread backend/escalation_engine.py
Comment thread backend/escalation_engine.py
Comment thread backend/init_db.py
Comment thread backend/routers/grievances.py
@RohanExploit RohanExploit merged commit 3dc8230 into main Apr 8, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants