Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ def invalidate(self):
blockchain_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=1)
grievance_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=1)
resolution_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=1)
token_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=1)
visit_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=2)
audit_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=2)
evidence_audit_last_hash_cache = ThreadSafeCache(ttl=3600, max_size=1)
Expand Down
4 changes: 4 additions & 0 deletions backend/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,10 @@ class ResolutionProofToken(Base):
valid_from = Column(DateTime, nullable=True)
valid_until = Column(DateTime, nullable=True)

# Blockchain integrity fields
integrity_hash = Column(String, nullable=True)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1: Missing database migration for the new integrity_hash and previous_integrity_hash columns (and the index on previous_integrity_hash). init_db.py handles migrations for resolution_proof_tokens but only covers nonce, valid_from, and valid_until. On existing deployments the ORM will try to read/write columns that don't exist, causing runtime errors. Add the corresponding add_column / create_index statements to the migration block in init_db.py.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/models.py, line 327:

<comment>Missing database migration for the new `integrity_hash` and `previous_integrity_hash` columns (and the index on `previous_integrity_hash`). `init_db.py` handles migrations for `resolution_proof_tokens` but only covers `nonce`, `valid_from`, and `valid_until`. On existing deployments the ORM will try to read/write columns that don't exist, causing runtime errors. Add the corresponding `add_column` / `create_index` statements to the migration block in `init_db.py`.</comment>

<file context>
@@ -323,6 +323,10 @@ class ResolutionProofToken(Base):
     valid_until = Column(DateTime, nullable=True)
 
+    # Blockchain integrity fields
+    integrity_hash = Column(String, nullable=True)
+    previous_integrity_hash = Column(String, nullable=True, index=True)
+
</file context>

previous_integrity_hash = Column(String, nullable=True, index=True)
Comment on lines +326 to +328
Comment on lines +326 to +328
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C2 'resolution_proof_tokens|integrity_hash|previous_integrity_hash|create_index|add_column' .

Repository: RohanExploit/VishwaGuru

Length of output: 45382


🏁 Script executed:

find . -type d -name alembic -o -name migrations -o -name migrate | head -20

Repository: RohanExploit/VishwaGuru

Length of output: 49


🏁 Script executed:

ls -la backend/init_db.py && wc -l backend/init_db.py

Repository: RohanExploit/VishwaGuru

Length of output: 159


🏁 Script executed:

sed -n '260,280p' backend/init_db.py

Repository: RohanExploit/VishwaGuru

Length of output: 1262


Add migration for integrity_hash and previous_integrity_hash columns on resolution_proof_tokens table.

The model defines these columns and generate_proof_token immediately writes to them (lines 222–223 in resolution_proof_service.py), but init_db.py does not create them. Unlike other blockchain-chained models (Resolution​Evidence, EscalationAudit, EvidenceAuditLog, ClosureConfirmation), the resolution_proof_tokens migration block only handles nonce, valid_from, and valid_until. Add the missing column and index creation to lines 262–273 of init_db.py before deploying.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/models.py` around lines 326 - 328, The migration for the
resolution_proof_tokens table is missing the integrity_hash and
previous_integrity_hash columns (the model defines them and generate_proof_token
writes to them), so update the resolution_proof_tokens migration block to add a
nullable string column integrity_hash and a nullable string column
previous_integrity_hash and create an index on previous_integrity_hash; ensure
the column names and index match the model fields (integrity_hash,
previous_integrity_hash) so writes from generate_proof_token succeed and the DB
schema stays consistent with the ResolutionProofToken model.


# Relationship
grievance = relationship("Grievance", back_populates="resolution_tokens")

Expand Down
22 changes: 21 additions & 1 deletion backend/resolution_proof_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
EvidenceAuditLog, VerificationStatus, GrievanceStatus
)
from backend.config import get_config, get_auth_config
from backend.cache import resolution_last_hash_cache, evidence_audit_last_hash_cache
from backend.cache import resolution_last_hash_cache, evidence_audit_last_hash_cache, token_last_hash_cache

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -189,6 +189,22 @@ def generate_proof_token(

signature = ResolutionProofService._sign_payload(payload)

# Generate Integrity Hash
prev_hash = token_last_hash_cache.get("last_hash")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1: Reading previous_integrity_hash from a local cache without DB-level serialization can fork the integrity chain under concurrent requests. This breaks linear blockchain-style integrity guarantees for ResolutionProofToken.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/resolution_proof_service.py, line 193:

<comment>Reading `previous_integrity_hash` from a local cache without DB-level serialization can fork the integrity chain under concurrent requests. This breaks linear blockchain-style integrity guarantees for `ResolutionProofToken`.</comment>

<file context>
@@ -189,6 +189,22 @@ def generate_proof_token(
         signature = ResolutionProofService._sign_payload(payload)
 
+        # Generate Integrity Hash
+        prev_hash = token_last_hash_cache.get("last_hash")
+        if prev_hash is None:
+            # Cache miss: Fetch only the last hash from DB
</file context>

if prev_hash is None:
# Cache miss: Fetch only the last hash from DB
last_record = db.query(ResolutionProofToken.integrity_hash).order_by(ResolutionProofToken.id.desc()).first()
prev_hash = last_record[0] if last_record and last_record[0] else ""
token_last_hash_cache.set(data=prev_hash, key="last_hash")

Comment on lines +192 to +199
hash_content = f"{token_uuid}|{grievance_id}|{authority_email}|{now.isoformat()}|{prev_hash}"
secret_key = get_auth_config().secret_key
integrity_hash = hmac.new(
secret_key.encode('utf-8'),
hash_content.encode('utf-8'),
hashlib.sha256
).hexdigest()

# Create token record
token = ResolutionProofToken(
token_id=token_uuid,
Expand All @@ -203,12 +219,16 @@ def generate_proof_token(
nonce=nonce,
token_signature=signature,
is_used=False,
integrity_hash=integrity_hash,
previous_integrity_hash=prev_hash,
)
Comment on lines 192 to 224

db.add(token)
db.commit()
db.refresh(token)

token_last_hash_cache.set(data=integrity_hash, key="last_hash")

logger.info(
f"Generated RPT {token_uuid} for grievance {grievance_id} "
f"by {authority_email}, expires {valid_until.isoformat()}"
Expand Down
Loading