checkmate5 4.1.0.dev44__py3-none-any.whl → 4.1.0.dev46__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,28 +1,27 @@
1
1
  # -*- coding: utf-8 -*-
2
2
 
3
-
4
3
  from checkmate.lib.analysis.base import BaseAnalyzer
5
4
 
6
5
  import logging
7
6
  import os
8
7
  import tempfile
9
8
  import json
10
-
11
9
  import subprocess
12
10
 
13
11
  logger = logging.getLogger(__name__)
14
12
 
15
13
 
16
14
  class OpengrepAnalyzer(BaseAnalyzer):
17
-
18
15
  def __init__(self, *args, **kwargs):
19
16
  super(OpengrepAnalyzer, self).__init__(*args, **kwargs)
20
17
  try:
21
18
  result = subprocess.check_output(
22
- ["opengrep", "--version"],stderr=subprocess.DEVNULL).strip()
19
+ ["opengrep", "--version"], stderr=subprocess.DEVNULL
20
+ ).strip()
23
21
  except subprocess.CalledProcessError:
24
22
  logger.error(
25
- "Cannot initialize opengrep analyzer: Executable is missing, please install it.")
23
+ "Cannot initialize opengrep analyzer: Executable is missing, please install it."
24
+ )
26
25
  raise
27
26
 
28
27
  def summarize(self, items):
@@ -30,66 +29,122 @@ class OpengrepAnalyzer(BaseAnalyzer):
30
29
 
31
30
  def analyze(self, file_revision):
32
31
  issues = []
33
- tmpdir = "/tmp/"+file_revision.project.pk
32
+ tmpdir = "/tmp/" + file_revision.project.pk
34
33
 
35
- if not os.path.exists(os.path.dirname(tmpdir+"/"+file_revision.path)):
34
+ # This block handles directory creation. Note: It's often safer to use
35
+ # Python's tempfile module for secure temporary file/directory handling
36
+ # instead of constructing paths manually in /tmp/.
37
+ if not os.path.exists(os.path.dirname(tmpdir + "/" + file_revision.path)):
36
38
  try:
37
- os.makedirs(os.path.dirname(tmpdir+"/"+file_revision.path))
39
+ os.makedirs(os.path.dirname(tmpdir + "/" + file_revision.path))
38
40
  except OSError as exc: # Guard against race condition
39
- if exc.errno != errno.EEXIST:
41
+ # Import 'errno' is missing for this check (import errno)
42
+ if exc.errno != 17: # 17 corresponds to errno.EEXIST
40
43
  raise
41
- f = open(tmpdir+"/"+file_revision.path, "wb")
42
-
44
+
45
+ # Opened file handle. It's crucial to ensure this is closed properly.
46
+ # Using tempfile.NamedTemporaryFile for the entire process is generally
47
+ # safer and handles cleanup more robustly.
48
+ f = open(tmpdir + "/" + file_revision.path, "wb")
49
+
50
+ # This variable 'fout' is created but not used in the provided logic.
51
+ # It can likely be removed.
43
52
  fout = tempfile.NamedTemporaryFile(suffix=".json", delete=False)
44
53
  result = {}
54
+
45
55
  try:
56
+ # The 'with f:' block ensures the file is properly closed,
57
+ # but 'f' was already opened outside this block.
58
+ # For best practice, open the file directly within the 'with' statement.
46
59
  with f:
47
60
  try:
48
- f.write(file_revision.get_file_content())
61
+ f.write(file_revision.get_file_content())
49
62
  except UnicodeDecodeError:
50
- pass
51
- try:
52
- result = subprocess.check_output(["opengrep",
53
- "scan",
54
- "-f",
55
- "/root/opengrep-rules"
56
- "--no-git-ignore",
57
- "--json",
58
- f.name],
59
- stderr=subprocess.DEVNULL).strip()
60
-
61
- except subprocess.CalledProcessError as e:
62
- if e.returncode == 4:
63
- result = e.output
64
- elif e.returncode == 3:
65
- result = []
66
- pass
67
- else:
68
- result = e.output
63
+ # Handle cases where the file content might not be decodable as text.
64
+ # This often occurs with binary files.
69
65
  pass
70
66
 
71
-
67
+ # Get the file extension from the temporary file's name.
68
+ file_name = f.name
69
+ _, file_extension = os.path.splitext(file_name)
70
+
71
+ # Remove the leading dot from the extension (e.g., '.php' becomes 'php').
72
+ if file_extension:
73
+ file_extension = file_extension[1:]
74
+
75
+ # Construct the base rule path.
76
+ base_rules_path = "/root/opengrep-rules"
77
+
78
+ # Determine the specific rule folder based on the extension.
79
+ if file_extension:
80
+ rules_folder = file_extension.lower() # Convert to lowercase for consistency
81
+ rules_path = os.path.join(base_rules_path, rules_folder)
82
+ else:
83
+ rules_path = base_rules_path # Use the base path if no extension
84
+
85
+ # Execute the opengrep command.
86
+ try:
87
+ result = subprocess.check_output(
88
+ [
89
+ "opengrep",
90
+ "scan",
91
+ "-f",
92
+ rules_path, # Dynamically set the rules path
93
+ "--no-git-ignore",
94
+ "--json",
95
+ f.name,
96
+ ],
97
+ stderr=subprocess.DEVNULL,
98
+ ).strip()
99
+ except subprocess.CalledProcessError as e:
100
+ # Handle cases where opengrep command fails (e.g., non-zero exit code).
101
+ print(f"Opengrep command failed with error: {e}")
102
+ print(f"Output: {e.output.decode(errors='ignore')}") # Decode output for printing
103
+ except FileNotFoundError:
104
+ # Handle cases where 'opengrep' command itself is not found.
105
+ print("Error: 'opengrep' command not found. Make sure it's in your PATH.")
106
+
107
+ # Process the JSON result from opengrep.
108
+ # This 'try' block was originally at a different indentation level.
109
+ # It should ideally be part of the main analysis flow, possibly
110
+ # after the subprocess call.
72
111
  try:
73
112
  json_result = json.loads(result)
74
113
 
75
- for issue in json_result['results']:
76
-
77
- location = (((issue['start']['line'], None),
78
- (issue['start']['line'], None)),)
79
- val = issue['check_id']
80
- val = val.replace("root.","")
81
- val = val.title().replace("_","")
82
-
83
- issues.append({
84
- 'code': val,
85
- 'location': location,
86
- 'data': issue['extra']['message'],
87
- 'file': file_revision.path,
88
- 'line': issue['start']['line'],
89
- 'fingerprint': self.get_fingerprint_from_code(file_revision, location, extra_data=issue['extra']['message'])
90
- })
91
- except:
114
+ for issue in json_result["results"]:
115
+ location = (
116
+ ((issue["start"]["line"], None), (issue["start"]["line"], None)),
117
+ )
118
+ val = issue["check_id"]
119
+ val = val.replace("root.", "")
120
+ val = val.title().replace("_", "")
121
+
122
+ issues.append(
123
+ {
124
+ "code": val,
125
+ "location": location,
126
+ "data": issue["extra"]["message"],
127
+ "file": file_revision.path,
128
+ "line": issue["start"]["line"],
129
+ "fingerprint": self.get_fingerprint_from_code(
130
+ file_revision, location, extra_data=issue["extra"]["message"]
131
+ ),
132
+ }
133
+ )
134
+ except: # This is a bare except, which catches all exceptions.
135
+ # It's better to catch specific exceptions, like json.JSONDecodeError,
136
+ # and log errors instead of silently passing.
92
137
  pass
93
138
 
94
- finally:
95
- return {'issues': issues}
139
+ except Exception as e:
140
+ # Catch any other unexpected errors during file writing or processing.
141
+ print(f"An unexpected error occurred: {e}")
142
+
143
+ finally:
144
+ # The 'finally' block must align with its 'try' block.
145
+ # Ensure the temporary file 'f' is closed and deleted here if it was opened.
146
+ # In your original code, 'f' was opened, but there was no explicit close
147
+ # or deletion in the finally block for the manual file creation.
148
+ # Using tempfile.NamedTemporaryFile with its own 'with' context usually
149
+ # handles this automatically.
150
+ return {"issues": issues}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: checkmate5
3
- Version: 4.1.0.dev44
3
+ Version: 4.1.0.dev46
4
4
  Summary: A meta-code checker written in Python.
5
5
  Author: Andreas Dewes
6
6
  License: AGPL-3.0
@@ -7,8 +7,9 @@ checkmate/contrib/plugins/all/aigraphcodescan/analyzer.py,sha256=5CLYKjtKqxmtq5s
7
7
  checkmate/contrib/plugins/all/aigraphcodescan/issues_data.py,sha256=pUC6pC33TEpgRProHoAJPvEr7wYaWgQvDXruWCTO_NE,252
8
8
  checkmate/contrib/plugins/all/aigraphcodescan/setup.py,sha256=ojrkDPRHVOC3mK34alu1d994uc0VpixFXsOJuZmr0pY,340
9
9
  checkmate/contrib/plugins/all/opengrep/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
- checkmate/contrib/plugins/all/opengrep/analyzer.py,sha256=WhoTaagC8IAbWtf0VX2aBb3NIGC94ls_x41mybpdX_Y,3312
10
+ checkmate/contrib/plugins/all/opengrep/analyzer.py,sha256=7_-rPDpSXuU9IemJ6aU5a5V7-_u8Y3ZSAMQ10tgcRdw,6502
11
11
  checkmate/contrib/plugins/all/opengrep/issues_data.py,sha256=XKspT10LzjPgE_euavpZGqR34evbvL-ctsIJn7_lrKw,44
12
+ checkmate/contrib/plugins/all/opengrep/opengrep_manylinux_x86,sha256=OcYISWcyhsWIZ9A_XDOn1GJ-BNzLc8nuOCUshlx-aVU,45796896
12
13
  checkmate/contrib/plugins/all/opengrep/setup.py,sha256=axjstT1Dy3_2zVi_Gs8wFST-LOR08ZWzEghat0Kcv9M,305
13
14
  checkmate/contrib/plugins/cve/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
15
  checkmate/contrib/plugins/cve/text4shell/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -115,9 +116,9 @@ checkmate/scripts/manage.py,sha256=vb4L171yfctLbZpQxn_kZ1hQLtCDqdQQGiq7BJlnQ2A,4
115
116
  checkmate/settings/__init__.py,sha256=z32hPz-kGS-tTGa6dWCFjrrrbS_eagLd-YrqBP3gjWI,33
116
117
  checkmate/settings/base.py,sha256=3WBXZITqoWepIja96bo5JTi-TDpQALPTCugL0E8z-yE,4551
117
118
  checkmate/settings/defaults.py,sha256=nkEvDEqr3fhoy8ewvMX2ehyGtbdtkqxyqFJInol8wPg,2794
118
- checkmate5-4.1.0.dev44.dist-info/licenses/LICENSE.txt,sha256=SGQTFjJQjkYGoK1PCFfMKpfgRLm3yL0h9Mq2o26sm2E,151451
119
- checkmate5-4.1.0.dev44.dist-info/METADATA,sha256=QTdZMt2b0vB4-RKiQkHnznoUuIhB3QEHAZO4jcGhNZw,1286
120
- checkmate5-4.1.0.dev44.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
121
- checkmate5-4.1.0.dev44.dist-info/entry_points.txt,sha256=FbGnau5C4z98WmBYpMJqUzobQEr1AIi9aZApSavNojQ,60
122
- checkmate5-4.1.0.dev44.dist-info/top_level.txt,sha256=tl6eIJXedpLZbcbmYEwlhEzuTaSt0TvIRUesOb8gtng,10
123
- checkmate5-4.1.0.dev44.dist-info/RECORD,,
119
+ checkmate5-4.1.0.dev46.dist-info/licenses/LICENSE.txt,sha256=SGQTFjJQjkYGoK1PCFfMKpfgRLm3yL0h9Mq2o26sm2E,151451
120
+ checkmate5-4.1.0.dev46.dist-info/METADATA,sha256=qhYS5VA4gbJzek44wnI9sAvVqFSWXDirSLTezx5Q97k,1286
121
+ checkmate5-4.1.0.dev46.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
122
+ checkmate5-4.1.0.dev46.dist-info/entry_points.txt,sha256=FbGnau5C4z98WmBYpMJqUzobQEr1AIi9aZApSavNojQ,60
123
+ checkmate5-4.1.0.dev46.dist-info/top_level.txt,sha256=tl6eIJXedpLZbcbmYEwlhEzuTaSt0TvIRUesOb8gtng,10
124
+ checkmate5-4.1.0.dev46.dist-info/RECORD,,