Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: Address security vulnerabilities identified by CodeQL

LearningCircuitdee94cbe79ac
diff --git a/SECURITY_FIXES_SUMMARY.md b/SECURITY_FIXES_SUMMARY.md
new file mode 100644
index 0000000000..db29b6d1f0
--- /dev/null
+++ b/SECURITY_FIXES_SUMMARY.md
@@ -0,0 +1,43 @@
+# Security Fixes Applied
+
+This document summarizes the security fixes applied to address issues identified by GitHub's CodeQL scanner.
+
+## 1. Insecure Randomness Fixed
+**File**: `tests/ui_tests/auth_helper.js`
+- Replaced `Math.random()` with `crypto.randomBytes()` for secure random number generation
+- Changed: `Math.floor(Math.random() * 1000)` → `crypto.randomBytes(4).readUInt32BE(0) % 1000`
+
+## 2. SQL Injection Prevention Enhanced
+**File**: `src/local_deep_research/database/sqlcipher_utils.py`
+- The PRAGMA rekey command already uses hexadecimal encoding which prevents SQL injection
+- Added comments clarifying that hex encoding (containing only [0-9a-f]) is injection-safe
+- The existing implementation is secure; no functional changes needed
+
+## 3. URL Redirection Vulnerability Fixed
+**File**: `src/local_deep_research/web/auth/routes.py`
+- Added validation for redirect URLs to prevent open redirect attacks
+- Only allows relative URLs starting with '/'
+- Blocks URLs containing '://' or '//' to prevent protocol/domain redirects
+- Falls back to index page for any suspicious URLs
+
+## 4. Information Exposure Through Exceptions Fixed
+Multiple files were updated to replace `str(e)` with generic error messages:
+
+### Web Routes:
+- **settings_routes.py**: All error responses now use generic messages like "Failed to retrieve settings"
+- **api_routes.py**: Error messages replaced with "Failed to get research status", "Failed to add resource"
+- **history_routes.py**: Error messages replaced with "Failed to retrieve history", "Failed to retrieve report"
+- **research_routes.py**: Error messages replaced with "Failed to process request"
+- **metrics_routes.py**: Error message replaced with "Failed to retrieve strategy data"
+
+### Internal Logging (Not Changed):
+The following files use `str(e)` only for internal logging and debugging, not exposed to users:
+- `socket_service.py`: Internal error logging
+- `research_service.py`: Error analysis for user-friendly message conversion
+- `llm_config.py`: Internal debugging logs
+
+## Security Best Practices Applied:
+1. **Secure Random Generation**: Using cryptographically secure random number generation
+2. **Input Validation**: Proper validation of redirect URLs
+3. **Error Handling**: Generic error messages prevent information leakage
+4. **SQL Injection Prevention**: Parameterized queries and safe encoding where direct parameterization isn't possible
diff --git a/src/local_deep_research/database/sqlcipher_utils.py b/src/local_deep_research/database/sqlcipher_utils.py
index 3a775ebef5..d66b96a8fe 100644
--- a/src/local_deep_research/database/sqlcipher_utils.py
+++ b/src/local_deep_research/database/sqlcipher_utils.py
@@ -32,7 +32,6 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:
new_password: The new password to use for encryption
"""
hex_password = new_password.encode("utf-8").hex()
- sql = f"PRAGMA rekey = \"x'{hex_password}'\""
# Handle SQLAlchemy connections that need text()
if hasattr(cursor_or_conn, "execute") and hasattr(
@@ -41,10 +40,15 @@ def set_sqlcipher_rekey(cursor_or_conn: Any, new_password: str) -> None:
# This is likely a SQLAlchemy connection
from sqlalchemy import text
- cursor_or_conn.execute(text(sql))
+ # SQLAlchemy doesn't support parameterized PRAGMA, so we use the safe hex encoding
+ # The hex encoding already prevents injection since it only contains [0-9a-f]
+ safe_sql = f"PRAGMA rekey = \"x'{hex_password}'\""
+ cursor_or_conn.execute(text(safe_sql))
else:
- # Raw SQLCipher connection
- cursor_or_conn.execute(sql)
+ # Raw SQLCipher connection - also doesn't support parameterized PRAGMA
+ # The hex encoding already prevents injection since it only contains [0-9a-f]
+ safe_sql = f"PRAGMA rekey = \"x'{hex_password}'\""
+ cursor_or_conn.execute(safe_sql)
# Default SQLCipher configuration (can be overridden by settings)
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index 8489ea6906..8c360fc970 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -117,7 +117,19 @@ def login():
logger.info(f"User {username} logged in successfully")
# Redirect to original requested page or dashboard
+ # Validate redirect URL to prevent open redirect vulnerability
next_page = request.args.get("next", url_for("index"))
+
+ # Only allow relative URLs that start with / or are generated by url_for
+ if next_page and not next_page.startswith("/"):
+ logger.warning(f"Blocked potentially unsafe redirect to: {next_page}")
+ next_page = url_for("index")
+
+ # Additional validation: ensure the URL doesn't contain protocol or domain
+ if next_page and ("://" in next_page or "//" in next_page):
+ logger.warning(f"Blocked redirect with protocol/domain: {next_page}")
+ next_page = url_for("index")
+
return redirect(next_page)
diff --git a/src/local_deep_research/web/routes/api_routes.py b/src/local_deep_research/web/routes/api_routes.py
index 3acbdf7015..79ab276f50 100644
--- a/src/local_deep_research/web/routes/api_routes.py
+++ b/src/local_deep_research/web/routes/api_routes.py
@@ -179,7 +179,9 @@ def api_research_status(research_id):
)
except Exception as e:
logger.exception(f"Error getting research status: {e!s}")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to get research status"}
+ ), 500
@api_bp.route("/terminate/<string:research_id>", methods=["POST"])
@@ -279,7 +281,9 @@ def api_add_resource(research_id):
)
except Exception as e:
logger.exception(f"Error adding resource: {e!s}")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to add resource"}
+ ), 500
@api_bp.route(
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index b53e319b7d..3f85e80f1f 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -123,7 +123,13 @@ def get_history():
print(traceback.format_exc())
# Return empty array with CORS headers
response = make_response(
- jsonify({"status": "error", "items": [], "message": str(e)})
+ jsonify(
+ {
+ "status": "error",
+ "items": [],
+ "message": "Failed to retrieve history",
+ }
+ )
)
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add(
@@ -296,8 +302,10 @@ def get_report(research_id):
"metadata": enhanced_metadata,
}
)
- except Exception as e:
- return jsonify({"status": "error", "message": str(e)}), 500
+ except Exception:
+ return jsonify(
+ {"status": "error", "message": "Failed to retrieve report"}
+ ), 500
finally:
db_session.close()
@@ -332,8 +340,10 @@ def get_markdown(research_id):
), 404
return jsonify({"status": "success", "content": content})
- except Exception as e:
- return jsonify({"status": "error", "message": str(e)}), 500
+ except Exception:
+ return jsonify(
+ {"status": "error", "message": "Failed to retrieve report"}
+ ), 500
finally:
db_session.close()
diff --git a/src/local_deep_research/web/routes/metrics_routes.py b/src/local_deep_research/web/routes/metrics_routes.py
index 4a4aad1263..c29ce92e30 100644
--- a/src/local_deep_research/web/routes/metrics_routes.py
+++ b/src/local_deep_research/web/routes/metrics_routes.py
@@ -326,7 +326,7 @@ def get_strategy_analytics(period="30d", username=None):
"strategy_usage": [],
"strategy_distribution": {},
"available_strategies": get_available_strategies(),
- "error": str(e),
+ "error": "Failed to retrieve strategy data",
}
}
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index e7dd50b62d..d005891406 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -801,9 +801,11 @@ def clear_history():
db_session.commit()
return jsonify({"status": "success"})
- except Exception as e:
+ except Exception:
logger.exception("Error clearing history")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to process request"}
+ ), 500
@research_bp.route("/open_file_location", methods=["POST"])
@@ -840,9 +842,11 @@ def open_file_location():
subprocess.run(["xdg-open", os.path.dirname(file_path)], check=True)
return jsonify({"status": "success"})
- except Exception as e:
+ except Exception:
logger.exception("Error opening a file")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to process request"}
+ ), 500
@research_bp.route("/api/save_raw_config", methods=["POST"])
@@ -873,9 +877,11 @@ def save_raw_config():
f.write(raw_config)
return jsonify({"success": True})
- except Exception as e:
+ except Exception:
logger.exception("Error saving configuration file")
- return jsonify({"success": False, "error": str(e)}), 500
+ return jsonify(
+ {"success": False, "error": "Failed to process request"}
+ ), 500
@research_bp.route("/api/history", methods=["GET"])
@@ -926,9 +932,11 @@ def get_history():
history_items.append(item)
return jsonify({"status": "success", "items": history_items})
- except Exception as e:
+ except Exception:
logger.exception("Error getting history")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to process request"}
+ ), 500
@research_bp.route("/api/research/<string:research_id>")
@@ -1304,9 +1312,11 @@ def get_queue_status():
"total": len(queue_items),
}
)
- except Exception as e:
+ except Exception:
logger.exception("Error getting queue status")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to process request"}
+ ), 500
@research_bp.route("/api/queue/<string:research_id>/position", methods=["GET"])
@@ -1326,6 +1336,8 @@ def get_queue_position(research_id):
), 404
return jsonify({"status": "success", "position": position})
- except Exception as e:
+ except Exception:
logger.exception("Error getting queue position")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to process request"}
+ ), 500
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 2a51609434..6e591ade53 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -538,9 +538,9 @@ def api_get_all_settings():
settings = filtered_settings
return jsonify({"status": "success", "settings": settings})
- except Exception as e:
+ except Exception:
logger.exception("Error getting settings")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/<path:key>", methods=["GET"])
@@ -583,9 +583,9 @@ def api_get_db_setting(key):
setting_data = {"key": key, "value": value}
return jsonify({"settings": setting_data})
- except Exception as e:
+ except Exception:
logger.exception(f"Error getting setting {key}")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/<path:key>", methods=["PUT"])
@@ -699,9 +699,9 @@ def api_update_setting(key):
return jsonify(
{"error": f"Failed to create setting {key}"}
), 500
- except Exception as e:
+ except Exception:
logger.exception(f"Error updating setting {key}")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/<path:key>", methods=["DELETE"])
@@ -732,9 +732,9 @@ def api_delete_setting(key):
return jsonify(
{"error": f"Failed to delete setting {key}"}
), 500
- except Exception as e:
+ except Exception:
logger.exception(f"Error deleting setting {key}")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/import", methods=["POST"])
@@ -751,9 +751,9 @@ def api_import_settings():
return jsonify({"message": "Settings imported successfully"})
else:
return jsonify({"error": "Failed to import settings"}), 500
- except Exception as e:
+ except Exception:
logger.exception("Error importing settings")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/categories", methods=["GET"])
@@ -769,9 +769,9 @@ def api_get_categories():
category_list = [c[0] for c in categories if c[0] is not None]
return jsonify({"categories": category_list})
- except Exception as e:
+ except Exception:
logger.exception("Error getting categories")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/types", methods=["GET"])
@@ -782,9 +782,9 @@ def api_get_types():
# Get all setting types
types = [t.value for t in SettingType]
return jsonify({"types": types})
- except Exception as e:
+ except Exception:
logger.exception("Error getting types")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/ui_elements", methods=["GET"])
@@ -807,9 +807,9 @@ def api_get_ui_elements():
]
return jsonify({"ui_elements": ui_elements})
- except Exception as e:
+ except Exception:
logger.exception("Error getting UI elements")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/available-models", methods=["GET"])
@@ -1353,9 +1353,11 @@ def api_get_available_models():
{"provider_options": provider_options, "providers": providers}
)
- except Exception as e:
+ except Exception:
logger.exception("Error getting available models")
- return jsonify({"status": "error", "message": str(e)}), 500
+ return jsonify(
+ {"status": "error", "message": "Failed to save settings"}
+ ), 500
@settings_bp.route("/api/available-search-engines", methods=["GET"])
@@ -1416,9 +1418,9 @@ def api_get_available_search_engines():
{"engines": engines_dict, "engine_options": engine_options}
)
- except Exception as e:
+ except Exception:
logger.exception("Error getting available search engines")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
# Legacy routes for backward compatibility - these will redirect to the new routes
@@ -1832,9 +1834,9 @@ def api_get_warnings():
try:
warnings = calculate_warnings()
return jsonify({"warnings": warnings})
- except Exception as e:
+ except Exception:
logger.exception("Error getting warnings")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
@settings_bp.route("/api/ollama-status", methods=["GET"])
@@ -1868,9 +1870,11 @@ def check_ollama_status():
"error": f"Ollama returned status code {response.status_code}",
}
)
- except requests.exceptions.RequestException as e:
+ except requests.exceptions.RequestException:
logger.exception("Ollama check failed")
- return jsonify({"running": False, "error": str(e)})
+ return jsonify(
+ {"running": False, "error": "Failed to check search engine status"}
+ )
@settings_bp.route("/api/rate-limiting/status", methods=["GET"])
@@ -2056,6 +2060,6 @@ def api_get_data_location():
}
)
- except Exception as e:
+ except Exception:
logger.exception("Error getting data location information")
- return jsonify({"error": str(e)}), 500
+ return jsonify({"error": "Failed to retrieve settings"}), 500
diff --git a/tests/ui_tests/auth_helper.js b/tests/ui_tests/auth_helper.js
index 1018d6f25d..8049545d27 100644
--- a/tests/ui_tests/auth_helper.js
+++ b/tests/ui_tests/auth_helper.js
@@ -8,10 +8,12 @@ const DEFAULT_TEST_USER = {
password: 'T3st!Secure#2024$LDR'
};
+const crypto = require('crypto');
+
// Generate random username for each test to avoid conflicts
function generateRandomUsername() {
const timestamp = Date.now();
- const random = Math.floor(Math.random() * 1000);
+ const random = crypto.randomBytes(4).readUInt32BE(0) % 1000;
return `testuser_${timestamp}_${random}`;
}