-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenhanced_agent_with_security.py
More file actions
1589 lines (1304 loc) · 62.5 KB
/
enhanced_agent_with_security.py
File metadata and controls
1589 lines (1304 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import hashlib
import json
import os
import requests
import time
import re
import git
import shutil
import tempfile
import subprocess
from typing import List, Dict, Optional, Tuple, Set
from datetime import datetime
from pathlib import Path
from urllib.parse import urlparse, parse_qs, unquote
# LangChain imports
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool, StructuredTool
from langchain.schema import BaseMessage
from langchain_community.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
# LlamaIndex imports
from llama_index.core import Document, VectorStoreIndex, Settings
from llama_index.core.node_parser import SimpleNodeParser
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.openai import OpenAI as LlamaOpenAI
from llama_index.llms.ollama import Ollama
from dotenv import load_dotenv
load_dotenv()
# PDF generation
try:
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.lib.colors import red, black, green
PDF_AVAILABLE = True
except ImportError:
PDF_AVAILABLE = False
print("⚠️ ReportLab not installed. PDF generation will be disabled.")
# Image processing for watermarks
try:
from PIL import Image
import io
IMAGE_PROCESSING_AVAILABLE = True
except ImportError:
IMAGE_PROCESSING_AVAILABLE = False
print("⚠️ PIL not installed. Image watermark detection will be disabled.")
class EnhancedGitHubProtectionAgent:
def __init__(self, config: Dict):
self.config = config
self.setup_models()
self.setup_tools()
self.setup_agent()
# In-memory storage
self.repositories = {}
self.violations = {}
self.security_audits = {}
self.jobs = {}
def setup_models(self):
"""Initialize AI models"""
use_local = self.config.get('USE_LOCAL_MODEL', False)
if use_local:
print("🦙 Using local model")
self.llm = ChatOpenAI(
base_url="http://localhost:11434/v1",
api_key="ollama",
model="llama3.2:3b"
)
Settings.llm = Ollama(model="llama3.2:3b", base_url="http://localhost:11434")
else:
print("🤖 Using OpenAI")
self.llm = ChatOpenAI(
model="gpt-4o-mini",
api_key=self.config['OPENAI_API_KEY']
)
Settings.llm = LlamaOpenAI(
model="gpt-4o-mini",
api_key=self.config['OPENAI_API_KEY']
)
# Setup embeddings
try:
Settings.embed_model = HuggingFaceEmbedding(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
print("✅ Using free HuggingFace embeddings")
except Exception as e:
print(f"⚠️ Embeddings setup failed: {e}")
def setup_tools(self):
"""Initialize agent tools"""
self.tools = [
StructuredTool.from_function(
func=self.analyze_repository,
name="analyze_repository",
description="Analyze a GitHub repository for key features and generate fingerprint"
),
StructuredTool.from_function(
func=self.register_repository,
name="register_repository",
description="Register a repository on the blockchain for protection"
),
StructuredTool.from_function(
func=self.search_for_violations,
name="search_for_violations",
description="Search for potential code violations across GitHub"
),
StructuredTool.from_function(
func=self.generate_license,
name="generate_license",
description="Generate appropriate license for repository"
),
StructuredTool.from_function(
func=self.security_audit,
name="security_audit",
description="Perform security audit on repository code"
),
StructuredTool.from_function(
func=self.report_violation,
name="report_violation",
description="Report a code violation to the blockchain"
),
StructuredTool.from_function(
func=self.clean_github_urls,
name="clean_github_urls",
description="Clean and standardize URLs from text input"
),
StructuredTool.from_function(
func=self.comprehensive_security_audit,
name="comprehensive_security_audit",
description="Perform comprehensive security audit on any URL (GitHub, Reddit, Twitter, images, etc.)"
)
]
def setup_agent(self):
"""Initialize the LangChain agent"""
self.memory = ConversationBufferMemory(memory_key="chat_history")
self.agent = initialize_agent(
tools=self.tools,
llm=self.llm,
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
memory=self.memory,
max_iterations=5
)
# ===== CORE REPOSITORY METHODS =====
def analyze_repository(self, github_url: str) -> Dict:
"""Analyze repository and extract key features"""
try:
repo_parts = github_url.replace('https://github.com/', '').split('/')
if len(repo_parts) < 2:
return {'success': False, 'error': 'Invalid GitHub URL'}
owner, repo = repo_parts[0], repo_parts[1]
headers = {}
if self.config.get('GITHUB_TOKEN'):
headers['Authorization'] = f"token {self.config['GITHUB_TOKEN']}"
# Get repo details
repo_response = requests.get(
f"https://api.github.com/repos/{owner}/{repo}",
headers=headers
)
if repo_response.status_code != 200:
return {'success': False, 'error': 'Repository not found or private'}
repo_data = repo_response.json()
# Get file list
contents_response = requests.get(
f"https://api.github.com/repos/{owner}/{repo}/contents",
headers=headers
)
files = []
if contents_response.status_code == 200:
contents = contents_response.json()
files = [item['name'] for item in contents if item['type'] == 'file']
# Generate fingerprint data
fingerprint_data = {
'name': repo_data.get('name', ''),
'description': repo_data.get('description', ''),
'language': repo_data.get('language', ''),
'size': repo_data.get('size', 0),
'files': files[:10],
'created_at': repo_data.get('created_at', ''),
}
# Generate hashes
repo_hash = hashlib.sha256(
json.dumps(fingerprint_data, sort_keys=True).encode()
).hexdigest()
fingerprint = hashlib.sha256(
f"{repo_data.get('full_name', '')}{repo_data.get('created_at', '')}".encode()
).hexdigest()
# AI feature extraction
features_prompt = f"""
Analyze this GitHub repository and identify key unique features:
Name: {repo_data.get('name', '')}
Description: {repo_data.get('description', '')}
Language: {repo_data.get('language', '')}
Files: {', '.join(files[:5])}
List 3-5 distinctive features that make this repository unique.
"""
try:
response = self.llm.invoke(features_prompt)
key_features = response.content
except Exception as e:
key_features = f"Language: {repo_data.get('language', 'Unknown')}, Files: {len(files)}"
return {
'success': True,
'repo_hash': repo_hash,
'fingerprint': fingerprint,
'key_features': key_features,
'total_files': len(files),
'analysis': fingerprint_data,
'repo_data': repo_data
}
except Exception as e:
return {'success': False, 'error': str(e)}
def register_repository(self, github_url: str, license_type: str = "MIT") -> Dict:
"""Register repository on blockchain"""
try:
analysis = self.analyze_repository(github_url)
if not analysis['success']:
return analysis
# Simulate blockchain transaction
tx_hash = f"0x{hashlib.sha256(f'{github_url}{time.time()}'.encode()).hexdigest()}"
repo_id = len(self.repositories) + 1
self.repositories[repo_id] = {
'id': repo_id,
'github_url': github_url,
'repo_hash': analysis['repo_hash'],
'fingerprint': analysis['fingerprint'],
'key_features': analysis['key_features'],
'license_type': license_type,
'registered_at': datetime.now().isoformat(),
'tx_hash': tx_hash
}
print(f"📝 Repository registered with ID: {repo_id}")
return {
'success': True,
'repo_id': repo_id,
'tx_hash': tx_hash,
'repo_hash': analysis['repo_hash'],
'fingerprint': analysis['fingerprint']
}
except Exception as e:
return {'success': False, 'error': str(e)}
# ===== COMPREHENSIVE SECURITY AUDIT =====
def comprehensive_security_audit(self, input_url: str) -> Dict:
"""Enhanced comprehensive security audit with multi-platform support"""
try:
print("🔍 Starting comprehensive security audit...")
# Step 1: Clean and categorize the input URL
url_analysis = self.analyze_and_clean_url(input_url)
if not url_analysis['valid']:
return {
'success': False,
'error': f"Invalid URL: {url_analysis['error']}",
'url_analysis': url_analysis
}
audit_id = len(self.security_audits) + 1
audit_result = {
'audit_id': audit_id,
'input_url': input_url,
'cleaned_url': url_analysis['cleaned_url'],
'platform': url_analysis['platform'],
'url_type': url_analysis['url_type'],
'timestamp': datetime.now().isoformat(),
'findings': [],
'files_scanned': 0,
'total_findings': 0,
'critical_findings': 0,
'high_findings': 0,
'medium_findings': 0,
'low_findings': 0
}
# Step 2: Route to appropriate audit method
if url_analysis['platform'] == 'github':
github_results = self.audit_github_repository(url_analysis['cleaned_url'])
audit_result.update(github_results)
elif url_analysis['platform'] == 'reddit':
reddit_results = self.audit_reddit_content(url_analysis['cleaned_url'])
audit_result.update(reddit_results)
elif url_analysis['platform'] == 'twitter':
twitter_results = self.audit_twitter_content(url_analysis['cleaned_url'])
audit_result.update(twitter_results)
elif url_analysis['url_type'] == 'image':
image_results = self.audit_image_watermarks(url_analysis['cleaned_url'])
audit_result.update(image_results)
else:
web_results = self.audit_web_content(url_analysis['cleaned_url'])
audit_result.update(web_results)
# Step 3: Generate AI summary
audit_result['ai_summary'] = self.generate_ai_summary(audit_result)
# Step 4: Generate PDF report if findings exist
if audit_result['total_findings'] > 0 and PDF_AVAILABLE:
pdf_path = self.generate_security_pdf_report(audit_result)
audit_result['pdf_report'] = pdf_path
# Store the audit
self.security_audits[audit_id] = audit_result
return {
'success': True,
'audit_id': audit_id,
**audit_result
}
except Exception as e:
return {'success': False, 'error': str(e)}
# ===== URL ANALYSIS AND CLEANING =====
def analyze_and_clean_url(self, input_url: str) -> Dict:
"""AI-powered URL analysis and cleaning"""
try:
url = input_url.strip()
# Basic cleaning
url = re.sub(r'^["\'\s]+|["\'\s]+$', '', url)
url = re.sub(r'\s+', '', url)
# Add protocol if missing
if not url.startswith(('http://', 'https://')):
if any(domain in url for domain in ['github.com', 'reddit.com', 'twitter.com', 'x.com']):
url = 'https://' + url
else:
url = 'https://' + url
parsed = urlparse(url)
# AI categorization
categorization_prompt = f"""
Analyze this URL and categorize it:
URL: {url}
Determine:
1. Platform (github, reddit, twitter, instagram, generic_web, image_hosting, etc.)
2. Content type (repository, profile, post, image, video, etc.)
3. If it's a GitHub URL, extract owner/repo
4. If it's an image URL, confirm it's a direct image link
Respond in JSON format:
{{
"platform": "platform_name",
"content_type": "type",
"is_valid": true/false,
"github_owner": "owner" (if GitHub),
"github_repo": "repo" (if GitHub),
"is_image": true/false,
"confidence": 0.0-1.0
}}
"""
try:
ai_response = self.llm.invoke(categorization_prompt)
ai_analysis = json.loads(ai_response.content)
except:
ai_analysis = self.manual_url_analysis(url, parsed)
cleaned_url = self.clean_url_based_on_platform(url, parsed, ai_analysis)
return {
'valid': True,
'original_url': input_url,
'cleaned_url': cleaned_url,
'platform': ai_analysis.get('platform', 'unknown'),
'url_type': ai_analysis.get('content_type', 'unknown'),
'ai_analysis': ai_analysis
}
except Exception as e:
return {
'valid': False,
'error': str(e),
'original_url': input_url
}
def manual_url_analysis(self, url: str, parsed) -> Dict:
"""Fallback manual URL analysis"""
domain = parsed.netloc.lower()
path = parsed.path.lower()
if 'github.com' in domain:
path_parts = [p for p in parsed.path.split('/') if p]
return {
'platform': 'github',
'content_type': 'repository' if len(path_parts) >= 2 else 'profile',
'is_valid': True,
'github_owner': path_parts[0] if path_parts else None,
'github_repo': path_parts[1] if len(path_parts) > 1 else None,
'is_image': False,
'confidence': 0.9
}
elif 'reddit.com' in domain or 'redd.it' in domain:
return {
'platform': 'reddit',
'content_type': 'post' if '/comments/' in path else 'profile',
'is_valid': True,
'is_image': False,
'confidence': 0.9
}
elif 'twitter.com' in domain or 'x.com' in domain:
return {
'platform': 'twitter',
'content_type': 'post' if '/status/' in path else 'profile',
'is_valid': True,
'is_image': False,
'confidence': 0.9
}
elif any(ext in path for ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']):
return {
'platform': 'image_hosting',
'content_type': 'image',
'is_valid': True,
'is_image': True,
'confidence': 0.8
}
else:
return {
'platform': 'generic_web',
'content_type': 'webpage',
'is_valid': True,
'is_image': False,
'confidence': 0.6
}
def clean_url_based_on_platform(self, url: str, parsed, ai_analysis: Dict) -> str:
"""Clean URL based on platform-specific rules"""
platform = ai_analysis.get('platform', 'unknown')
if platform == 'github':
path_parts = [p for p in parsed.path.split('/') if p]
if len(path_parts) >= 2:
clean_path = f"/{path_parts[0]}/{path_parts[1]}"
return f"https://github.com{clean_path}"
elif platform == 'reddit':
base_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
return base_url.rstrip('/')
elif platform == 'twitter':
if 'x.com' in parsed.netloc:
base_url = f"https://x.com{parsed.path}"
else:
base_url = f"https://twitter.com{parsed.path}"
return base_url.rstrip('/')
elif ai_analysis.get('is_image', False):
return f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
return f"{parsed.scheme}://{parsed.netloc}{parsed.path}".rstrip('/')
# ===== GITHUB SECURITY SCANNING =====
def audit_github_repository(self, github_url: str) -> Dict:
"""Enhanced GitHub repository audit with comprehensive secret scanning"""
print("🔍 Starting comprehensive GitHub repository audit...")
path_parts = [p for p in urlparse(github_url).path.split('/') if p]
if len(path_parts) < 2:
return {'error': 'Invalid GitHub repository URL'}
owner, repo = path_parts[0], path_parts[1]
findings = []
files_scanned = 0
try:
temp_dir = tempfile.mkdtemp()
repo_path = os.path.join(temp_dir, repo)
print(f"📥 Cloning repository: {github_url}")
git_repo = git.Repo.clone_from(github_url, repo_path)
# Scan all files
for root, dirs, files in os.walk(repo_path):
if '.git' in root:
continue
for file in files:
file_path = os.path.join(root, file)
relative_path = os.path.relpath(file_path, repo_path)
try:
if self.is_text_file(file_path):
file_findings = self.scan_file_for_secrets(file_path, relative_path)
findings.extend(file_findings)
files_scanned += 1
except Exception as e:
print(f"⚠️ Error scanning {relative_path}: {e}")
# Scan commit history
print("🔍 Scanning commit history...")
commit_findings = self.scan_commit_history_for_secrets(git_repo, repo_path)
findings.extend(commit_findings)
shutil.rmtree(temp_dir)
except Exception as e:
return {'error': f'Failed to clone or scan repository: {str(e)}'}
# Categorize findings
critical_findings = [f for f in findings if f['severity'] == 'critical']
high_findings = [f for f in findings if f['severity'] == 'high']
medium_findings = [f for f in findings if f['severity'] == 'medium']
low_findings = [f for f in findings if f['severity'] == 'low']
return {
'findings': findings,
'files_scanned': files_scanned,
'total_findings': len(findings),
'critical_findings': len(critical_findings),
'high_findings': len(high_findings),
'medium_findings': len(medium_findings),
'low_findings': len(low_findings),
'repository_info': {
'owner': owner,
'repo': repo,
'url': github_url
}
}
def scan_file_for_secrets(self, file_path: str, relative_path: str) -> List[Dict]:
"""Comprehensive file scanning for secrets"""
findings = []
try:
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
content = f.read()
lines = content.split('\n')
for line_num, line in enumerate(lines, 1):
for pattern_name, pattern_info in self.get_secret_patterns().items():
matches = re.finditer(pattern_info['pattern'], line, re.IGNORECASE)
for match in matches:
if self.is_likely_real_secret(match.group(), pattern_name):
findings.append({
'type': 'secret_leak',
'pattern_name': pattern_name,
'file_path': relative_path,
'line_number': line_num,
'line_content': line.strip(),
'matched_content': match.group()[:50] + '...' if len(match.group()) > 50 else match.group(),
'severity': pattern_info['severity'],
'description': pattern_info['description'],
'recommendation': pattern_info['recommendation']
})
except Exception as e:
print(f"Error scanning {relative_path}: {e}")
return findings
def get_secret_patterns(self) -> Dict:
"""Comprehensive patterns for detecting secrets"""
return {
'aws_access_key': {
'pattern': r'AKIA[0-9A-Z]{16}',
'severity': 'critical',
'description': 'AWS Access Key ID detected',
'recommendation': 'Immediately revoke this AWS access key and rotate credentials'
},
'private_key_general': {
'pattern': r'(?i)([A-Z_]*PRIVATE_KEY\s*[=:]\s*[\'"]?[^\s\'"]+[\'"]?)',
'severity': 'critical',
'description': 'Private key detected',
'recommendation': 'Remove private key and use secure key management'
},
'api_key_general': {
'pattern': r'(?i)([A-Z_]*API_KEY\s*[=:]\s*[\'"]?[^\s\'"]+[\'"]?)',
'severity': 'high',
'description': 'API key detected',
'recommendation': 'Remove API key and use environment variables'
},
'github_token': {
'pattern': r'gh[pousr]_[A-Za-z0-9_]{36,251}',
'severity': 'critical',
'description': 'GitHub token detected',
'recommendation': 'Immediately revoke this GitHub token'
},
'openai_api_key': {
'pattern': r'sk-[A-Za-z0-9]{48}',
'severity': 'critical',
'description': 'OpenAI API key detected',
'recommendation': 'Revoke this OpenAI API key immediately'
},
'database_url': {
'pattern': r'(?i)(postgres|mysql|mongodb)://[^\s\'"]+',
'severity': 'high',
'description': 'Database connection string detected',
'recommendation': 'Use environment variables for database credentials'
},
'jwt_token': {
'pattern': r'eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*',
'severity': 'high',
'description': 'JWT token detected',
'recommendation': 'Remove JWT token from code'
},
'ssh_private_key': {
'pattern': r'-----BEGIN [A-Z ]*PRIVATE KEY-----',
'severity': 'critical',
'description': 'SSH private key detected',
'recommendation': 'Remove SSH private key immediately'
}
}
def is_likely_real_secret(self, matched_text: str, pattern_name: str) -> bool:
"""Validate if matched text is likely a real secret"""
if any(sep in matched_text for sep in ['=', ':']):
for sep in ['=', ':']:
if sep in matched_text:
value_part = matched_text.split(sep, 1)[1].strip().strip('\'"')
break
else:
value_part = matched_text
# Skip common placeholders
placeholder_patterns = [
r'^\s*$', r'^your[_\s]*\w*[_\s]*key', r'^example', r'^test[_\s]*',
r'^dummy[_\s]*', r'^placeholder', r'^\.\.\.$', r'^x+$', r'^0+$'
]
for pattern in placeholder_patterns:
if re.match(pattern, value_part.lower()):
return False
# Pattern-specific validation
if pattern_name == 'aws_access_key':
return len(value_part) == 20 and value_part.startswith('AKIA')
elif pattern_name == 'openai_api_key':
return value_part.startswith('sk-') and len(value_part) == 51
elif pattern_name == 'github_token':
return (value_part.startswith(('ghp_', 'gho_', 'ghu_', 'ghs_', 'ghr_')) and len(value_part) >= 40)
return len(value_part) > 8
def is_text_file(self, file_path: str) -> bool:
"""Check if file is a text file suitable for scanning"""
text_extensions = {
'.py', '.js', '.ts', '.jsx', '.tsx', '.java', '.c', '.cpp', '.h',
'.cs', '.php', '.rb', '.go', '.rs', '.swift', '.kt', '.scala',
'.sql', '.html', '.htm', '.css', '.scss', '.xml', '.json', '.yaml',
'.yml', '.toml', '.ini', '.cfg', '.conf', '.txt', '.md', '.log',
'.sh', '.bash', '.env', '.gitignore'
}
file_ext = os.path.splitext(file_path)[1].lower()
if file_ext in text_extensions:
return True
filename = os.path.basename(file_path).lower()
if filename in {'dockerfile', 'makefile', 'rakefile'}:
return True
try:
with open(file_path, 'rb') as f:
chunk = f.read(1024)
if b'\0' in chunk:
return False
try:
chunk.decode('utf-8')
return True
except UnicodeDecodeError:
return False
except:
return False
def scan_commit_history_for_secrets(self, git_repo, repo_path: str) -> List[Dict]:
"""Scan git commit history for secrets"""
findings = []
try:
commits = list(git_repo.iter_commits('--all', max_count=50))
print(f"🔍 Scanning {len(commits)} commits...")
for commit in commits:
try:
if commit.parents:
diffs = commit.parents[0].diff(commit, create_patch=True)
else:
continue
for diff in diffs:
if diff.deleted_file or diff.new_file or diff.a_blob != diff.b_blob:
patch_text = str(diff)
lines = patch_text.split('\n')
for line in lines:
if line.startswith('-') and not line.startswith('---'):
line_content = line[1:]
for pattern_name, pattern_info in self.get_secret_patterns().items():
matches = re.finditer(pattern_info['pattern'], line_content, re.IGNORECASE)
for match in matches:
if self.is_likely_real_secret(match.group(), pattern_name):
findings.append({
'type': 'historical_secret_leak',
'pattern_name': pattern_name,
'file_path': diff.a_path or diff.b_path or 'unknown',
'commit_hash': commit.hexsha[:8],
'commit_date': commit.committed_datetime.isoformat(),
'line_content': line_content.strip(),
'matched_content': match.group()[:50] + '...' if len(match.group()) > 50 else match.group(),
'severity': pattern_info['severity'],
'description': f"Historical {pattern_info['description']} found in commit history",
'recommendation': f"{pattern_info['recommendation']} Found in git history."
})
except:
continue
except Exception as e:
print(f"⚠️ Error scanning commit history: {e}")
return findings
# ===== URL CLEANING METHODS =====
def clean_github_urls(self, url_text: str) -> Dict:
"""Clean and standardize GitHub URLs from text input"""
try:
print(f"🧹 Cleaning URLs from text input...")
raw_urls = self.extract_urls_from_text(url_text)
cleaned_urls = []
github_urls = []
other_urls = []
for url in raw_urls:
cleaned_result = self.clean_single_url(url)
if cleaned_result['success']:
cleaned_urls.append(cleaned_result['cleaned_url'])
if cleaned_result['platform'] == 'github':
github_urls.append({
'original': url,
'cleaned': cleaned_result['cleaned_url'],
'owner': cleaned_result.get('owner'),
'repo': cleaned_result.get('repo'),
'type': cleaned_result.get('url_type', 'repository')
})
else:
other_urls.append({
'original': url,
'cleaned': cleaned_result['cleaned_url'],
'platform': cleaned_result['platform'],
'type': cleaned_result.get('url_type', 'unknown')
})
ai_analysis = self.ai_analyze_url_collection(cleaned_urls)
return {
'success': True,
'original_text': url_text,
'total_urls_found': len(raw_urls),
'cleaned_urls': cleaned_urls,
'github_urls': github_urls,
'other_urls': other_urls,
'ai_analysis': ai_analysis,
'recommendations': self.generate_url_recommendations(github_urls, other_urls)
}
except Exception as e:
return {
'success': False,
'error': str(e),
'original_text': url_text
}
def extract_urls_from_text(self, text: str) -> List[str]:
"""Extract potential URLs from text"""
urls = []
# Standard URLs
url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
urls.extend(re.findall(url_pattern, text))
# URLs without protocol
no_protocol_pattern = r'(?:github\.com|reddit\.com|twitter\.com|x\.com)[^\s<>"{}|\\^`\[\]]+'
no_protocol_urls = re.findall(no_protocol_pattern, text, re.IGNORECASE)
urls.extend([f"https://{url}" for url in no_protocol_urls])
# GitHub-specific patterns
github_patterns = [
r'github\.com/[\w\-\.]+/[\w\-\.]+',
r'git@github\.com:[\w\-\.]+/[\w\-\.]+\.git'
]
for pattern in github_patterns:
matches = re.findall(pattern, text, re.IGNORECASE)
for match in matches:
if match.startswith('git@'):
clean_match = match.replace('git@github.com:', 'https://github.com/').replace('.git', '')
urls.append(clean_match)
elif not match.startswith('http'):
urls.append(f"https://{match}")
else:
urls.append(match)
# Remove duplicates
unique_urls = []
seen = set()
for url in urls:
url_clean = url.strip().lower()
if url_clean not in seen and len(url_clean) > 10:
seen.add(url_clean)
unique_urls.append(url.strip())
return unique_urls
def clean_single_url(self, url: str) -> Dict:
"""Clean and analyze a single URL"""
try:
cleaned_url = url.strip()
cleaned_url = re.sub(r'^["\'\s\[\]()]+|["\'\s\[\]()]+, '', cleaned_url)
cleaned_url = re.sub(r'\s+', '', cleaned_url)
if cleaned_url.startswith('git@github.com:'):
cleaned_url = cleaned_url.replace('git@github.com:', 'https://github.com/').replace('.git', '')
elif not cleaned_url.startswith(('http://', 'https://')):
cleaned_url = 'https://' + cleaned_url
parsed = urlparse(cleaned_url)
if not parsed.netloc:
return {'success': False, 'error': 'Invalid URL format'}
platform_result = self.identify_and_clean_platform_url(cleaned_url, parsed)
return {
'success': True,
'original_url': url,
'cleaned_url': platform_result['cleaned_url'],
'platform': platform_result['platform'],
'url_type': platform_result.get('url_type', 'unknown'),
'owner': platform_result.get('owner'),
'repo': platform_result.get('repo')
}
except Exception as e:
return {
'success': False,
'error': str(e),
'original_url': url
}
def identify_and_clean_platform_url(self, url: str, parsed) -> Dict:
"""Identify platform and clean URL"""
domain = parsed.netloc.lower()
path = parsed.path
if 'github.com' in domain:
path_parts = [p for p in path.split('/') if p]
if len(path_parts) >= 2:
owner, repo = path_parts[0], path_parts[1]
clean_path = f"/{owner}/{repo}"
clean_url = f"https://github.com{clean_path}"
return {
'platform': 'github',
'url_type': 'repository',
'cleaned_url': clean_url,
'owner': owner,
'repo': repo
}
elif len(path_parts) == 1:
owner = path_parts[0]
return {
'platform': 'github',
'url_type': 'profile',
'cleaned_url': f"https://github.com/{owner}",
'owner': owner
}
elif 'reddit.com' in domain or 'redd.it' in domain:
clean_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}".rstrip('/')
url_type = 'post' if '/comments/' in path else 'profile' if '/user/' in path else 'subreddit'
return {
'platform': 'reddit',
'url_type': url_type,
'cleaned_url': clean_url
}
elif 'twitter.com' in domain or 'x.com' in domain:
if 'twitter.com' in domain:
clean_url = url.replace('twitter.com', 'x.com')
else:
clean_url = url
clean_url = clean_url.split('?')[0].rstrip('/')
url_type = 'post' if '/status/' in path else 'profile'
return {
'platform': 'twitter',
'url_type': url_type,
'cleaned_url': clean_url
}
elif any(ext in path.lower() for ext in ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']):
return {
'platform': 'image_hosting',
'url_type': 'image',
'cleaned_url': f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
}
else:
return {
'platform': 'generic_web',
'url_type': 'webpage',
'cleaned_url': f"{parsed.scheme}://{parsed.netloc}{parsed.path}".rstrip('/')
}
def ai_analyze_url_collection(self, urls: List[str]) -> Dict:
"""AI analysis of URL collection"""
if not urls:
return {'analysis': 'No URLs to analyze'}
try:
analysis_prompt = f"""
Analyze this collection of URLs:
{json.dumps(urls, indent=2)}
Provide:
1. Platform distribution (GitHub, Reddit, Twitter, etc.)
2. Content types (repositories, profiles, posts, images)
3. Security assessment
4. Recommendations
Keep response concise.
"""
response = self.llm.invoke(analysis_prompt)
return {'analysis': response.content, 'platform_summary': self.basic_platform_analysis(urls)}
except Exception as e:
return {'error': str(e), 'platform_summary': self.basic_platform_analysis(urls)}
def basic_platform_analysis(self, urls: List[str]) -> Dict:
"""Basic platform analysis"""