Skip to content

Commit 015b747

Browse files
remyluslosiusclaude
andcommitted
fix(code-quality): Resolve 47 CodeQL code scanning alerts
Fixed all ERROR, WARNING, and NOTE severity issues across 15 files: ERROR Severity (3 issues): - Fixed check_permission() calls with wrong arguments (8 instances) - host_security_discovery.py: Changed from 2-arg to 3-arg signature - host_network_discovery.py: Split "hosts:read" into ("hosts", "read") - Fixed non-iterable enum iteration in plugin_registry_service.py - Added explicit list() conversion for PluginStatus enum WARNING Severity (5 issues): - Removed 4 unnecessary pass statements in ssh_settings.py - Fixed unreachable code in rule_specific_scanner.py - Enabled remediation success rate calculation logic - Changed "if False:" to proper condition check NOTE Severity (39 issues): - Fixed 20 bare except statements (changed to "except Exception:") - scap_content.py: 7 instances - scans.py: 7 instances - remove_legacy_credentials.py: 3 instances - remediation.py, scap_import.py, capabilities.py: 3 instances - Removed 5 duplicate "import json" statements - scans.py: 3 duplicates removed - rule_scanning.py: 2 duplicates removed - Removed 2 unused import statements - error_handling.py, compliance_rules_api.py: unused json imports - Removed 2 unused variables - system_info_sanitization.py: _error_sanitization_service - system_settings_unified.py: _scheduler Security Impact: - Bare except: blocks now properly allow system exits (KeyboardInterrupt) - RBAC permission checks use correct 3-argument signature - Dead code eliminated, reducing attack surface Testing: - All files pass Python syntax validation - Docker build completes successfully - All services healthy (backend, frontend, databases, workers) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 67baf2d commit 015b747

15 files changed

Lines changed: 28 additions & 46 deletions

backend/app/api/v1/endpoints/compliance_rules_api.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
from pathlib import Path
1111
from collections import defaultdict
1212
import logging
13-
import json
1413

1514
try:
1615
from ....services.mongo_integration_service import (

backend/app/api/v1/endpoints/scap_import.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,5 +310,5 @@ def estimate_import_duration(file_path: Path) -> float:
310310
file_size_mb = file_path.stat().st_size / (1024 * 1024)
311311
# Rough estimate: 1MB per minute for processing
312312
return max(1.0, file_size_mb * 1.0)
313-
except:
313+
except Exception:
314314
return 5.0 # Default estimate

backend/app/middleware/error_handling.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
"""
55

66
import traceback
7-
import json
87
import uuid
98
from typing import Dict, Any, Optional, List
109
from datetime import datetime, timedelta

backend/app/routes/capabilities.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@ def _check_aegis_availability() -> bool:
305305
# For now, check if AEGIS configuration exists
306306
aegis_url = os.environ.get("AEGIS_URL")
307307
return aegis_url is not None
308-
except:
308+
except Exception:
309309
return False
310310

311311

backend/app/routes/host_network_discovery.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ async def discover_host_network_topology(
7878
NetworkDiscoveryResponse containing discovered network information
7979
"""
8080
# Check permissions
81-
check_permission(current_user, "hosts:read")
81+
check_permission(current_user["role"], "hosts", "read")
8282

8383
try:
8484
# Convert string UUID to UUID object
@@ -139,7 +139,7 @@ async def bulk_discover_network_topology(
139139
BulkNetworkDiscoveryResponse with results for all hosts
140140
"""
141141
# Check permissions
142-
check_permission(current_user, "hosts:read")
142+
check_permission(current_user["role"], "hosts", "read")
143143

144144
if not request.host_ids:
145145
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No host IDs provided")
@@ -225,7 +225,7 @@ async def assess_host_network_security(
225225
NetworkSecurityAssessment with security evaluation
226226
"""
227227
# Check permissions
228-
check_permission(current_user, "hosts:read")
228+
check_permission(current_user["role"], "hosts", "read")
229229

230230
try:
231231
# Convert string UUID to UUID object
@@ -277,7 +277,7 @@ async def generate_network_topology_map(
277277
NetworkTopologyMap with network topology visualization data
278278
"""
279279
# Check permissions
280-
check_permission(current_user, "hosts:read")
280+
check_permission(current_user["role"], "hosts", "read")
281281

282282
if not request.host_ids:
283283
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No host IDs provided")
@@ -314,7 +314,7 @@ async def get_network_discovery_capabilities(current_user=Depends(get_current_us
314314
Dictionary of supported network discovery features
315315
"""
316316
# Check permissions
317-
check_permission(current_user, "hosts:read")
317+
check_permission(current_user["role"], "hosts", "read")
318318

319319
capabilities = {
320320
"network_interfaces": {

backend/app/routes/host_security_discovery.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ async def discover_host_security_infrastructure(
5959
SecurityDiscoveryResponse containing discovered security information
6060
"""
6161
# Check permissions
62-
check_permission(current_user, "hosts:read")
62+
check_permission(current_user["role"], "hosts", "read")
6363

6464
try:
6565
# Convert string UUID to UUID object
@@ -120,7 +120,7 @@ async def bulk_discover_security_infrastructure(
120120
BulkSecurityDiscoveryResponse with results for all hosts
121121
"""
122122
# Check permissions
123-
check_permission(current_user, "hosts:read")
123+
check_permission(current_user["role"], "hosts", "read")
124124

125125
if not request.host_ids:
126126
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No host IDs provided")
@@ -203,7 +203,7 @@ async def get_host_security_summary(
203203
Security summary based on existing host data
204204
"""
205205
# Check permissions
206-
check_permission(current_user, "hosts:read")
206+
check_permission(current_user["role"], "hosts", "read")
207207

208208
try:
209209
# Convert string UUID to UUID object

backend/app/routes/rule_scanning.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,8 +349,6 @@ async def create_remediation_plan(
349349
).fetchone()
350350

351351
if scan_result and scan_result.rule_details:
352-
import json
353-
354352
rule_details = json.loads(scan_result.rule_details)
355353
failed_rules = [
356354
{
@@ -449,8 +447,6 @@ def _store_rule_scan_results(db: Session, scan_results: dict):
449447
def _store_remediation_plan(db: Session, plan, created_by: int):
450448
"""Store remediation plan in database"""
451449
try:
452-
import json
453-
454450
db.execute(
455451
text(
456452
"""

backend/app/routes/scans.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ async def validate_scan_configuration(
193193
profile_ids = [p.get("id") for p in profiles if p.get("id")]
194194
if validation_request.profile_id not in profile_ids:
195195
raise HTTPException(status_code=400, detail="Profile not found in SCAP content")
196-
except:
196+
except Exception:
197197
raise HTTPException(status_code=400, detail="Invalid SCAP content profiles")
198198

199199
# Resolve credentials
@@ -366,7 +366,7 @@ async def quick_scan(
366366
status_code=400,
367367
detail="No profiles available in SCAP content",
368368
)
369-
except:
369+
except Exception:
370370
raise HTTPException(status_code=400, detail="Invalid SCAP content profiles")
371371

372372
# Generate scan name
@@ -468,7 +468,7 @@ async def quick_scan(
468468
if len(parts) == 2:
469469
avg_minutes = (int(parts[0]) + int(parts[1])) / 2
470470
estimated_time = datetime.utcnow().timestamp() + (avg_minutes * 60)
471-
except:
471+
except Exception:
472472
logger.debug("Ignoring exception during cleanup")
473473

474474
return QuickScanResponse(
@@ -1038,18 +1038,14 @@ async def create_scan(
10381038
profiles = []
10391039
if content_result.profiles:
10401040
try:
1041-
import json
1042-
10431041
profiles = json.loads(content_result.profiles)
10441042
profile_ids = [p.get("id") for p in profiles if p.get("id")]
10451043
if scan_request.profile_id not in profile_ids:
10461044
raise HTTPException(status_code=400, detail="Profile not found in SCAP content")
1047-
except:
1045+
except Exception:
10481046
raise HTTPException(status_code=400, detail="Invalid SCAP content profiles")
10491047

10501048
# Create scan record with UUID primary key
1051-
import json
1052-
10531049
scan_id = str(uuid.uuid4())
10541050
db.execute(
10551051
text(
@@ -1122,7 +1118,7 @@ async def create_scan(
11221118
"error_code": classified_error.error_code,
11231119
},
11241120
)
1125-
except:
1121+
except Exception:
11261122
# Fallback to generic error if classification fails
11271123
raise HTTPException(status_code=500, detail=f"Failed to create scan: {str(e)}")
11281124

@@ -1159,10 +1155,8 @@ async def get_scan(
11591155
scan_options = {}
11601156
if result.scan_options:
11611157
try:
1162-
import json
1163-
11641158
scan_options = json.loads(result.scan_options)
1165-
except:
1159+
except Exception:
11661160
logger.debug("Ignoring exception during cleanup")
11671161

11681162
scan_data = {
@@ -1775,7 +1769,7 @@ async def create_verification_scan(
17751769
profile_ids = [p.get("id") for p in profiles if p.get("id")]
17761770
if verification_request.profile_id not in profile_ids:
17771771
raise HTTPException(status_code=400, detail="Profile not found in SCAP content")
1778-
except:
1772+
except Exception:
17791773
raise HTTPException(status_code=400, detail="Invalid SCAP content profiles")
17801774

17811775
# Generate scan name

backend/app/routes/scap_content.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ async def list_scap_content(
6868
import json
6969

7070
profiles = json.loads(row.profiles)
71-
except:
71+
except Exception:
7272
profiles = []
7373

7474
content_list.append(
@@ -292,7 +292,7 @@ async def upload_scap_content(
292292
# Clean up temp file
293293
try:
294294
os.unlink(temp_path)
295-
except:
295+
except Exception:
296296
logger.debug("Ignoring exception during cleanup")
297297

298298
except SCAPContentError as e:
@@ -334,7 +334,7 @@ async def get_scap_content(
334334
import json
335335

336336
profiles = json.loads(result.profiles)
337-
except:
337+
except Exception:
338338
profiles = []
339339

340340
return {
@@ -383,7 +383,7 @@ async def get_scap_profiles(
383383
import json
384384

385385
profiles = json.loads(result.profiles)
386-
except:
386+
except Exception:
387387
# Re-extract profiles from file if cached version is invalid
388388
if os.path.exists(result.file_path):
389389
profiles = scap_scanner.extract_profiles(result.file_path)
@@ -461,7 +461,7 @@ async def delete_scap_content(
461461
if parent_dir.name != "scap": # Don't remove main scap dir
462462
try:
463463
parent_dir.rmdir() # Only removes if empty
464-
except:
464+
except Exception:
465465
pass
466466
except Exception as e:
467467
logger.warning(
@@ -800,11 +800,11 @@ async def test_connectivity():
800800
async with aiohttp.ClientSession() as session:
801801
async with session.get("https://www.google.com", timeout=5) as response:
802802
return response.status == 200
803-
except:
803+
except Exception:
804804
return False
805805

806806
has_internet = await test_connectivity()
807-
except:
807+
except Exception:
808808
has_internet = False
809809

810810
environment_type = "connected" if has_internet else "air-gapped"

backend/app/routes/ssh_settings.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,6 @@ async def set_ssh_policy(
170170
#
171171
# logger.warning(f"Traceback: {traceback.format_exc()}")
172172
# # Continue with operation - don't fail SSH updates due to audit issues
173-
pass
174173

175174
# Return updated configuration
176175
return await get_ssh_policy(db=db, current_user=current_user)
@@ -252,7 +251,6 @@ async def add_known_host(
252251
# logger.warning(
253252
# f"Enhanced audit logging failed for SSH known host addition: {audit_error}"
254253
# )
255-
pass
256254

257255
# Return the added host
258256
hosts = service.get_known_hosts(host_request.hostname)
@@ -321,7 +319,6 @@ async def remove_known_host(
321319
# logger.warning(
322320
# f"Enhanced audit logging failed for SSH known host removal: {audit_error}"
323321
# )
324-
pass
325322

326323
return {"message": f"Known host {hostname} removed successfully"}
327324

@@ -381,7 +378,6 @@ async def test_ssh_connectivity(
381378
# logger.warning(
382379
# f"Enhanced audit logging failed for SSH connectivity test: {audit_error}"
383380
# )
384-
pass
385381

386382
return {
387383
"host_id": host_id,

0 commit comments

Comments
 (0)