Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f30db3c

Browse files
Merge pull request #61 from SocketDev/eric/use-types-and-logging
Eric/use types and logging
2 parents 9b4ad3d + 5d949d8 commit f30db3c

File tree

4 files changed

+41
-36
lines changed

4 files changed

+41
-36
lines changed

‎socketsecurity/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
__author__ = 'socket.dev'
2-
__version__ = '2.0.11'
2+
__version__ = '2.0.12'

‎socketsecurity/core/__init__.py‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -394,18 +394,23 @@ def get_repo_info(self, repo_slug: str, default_branch: str = "socket-default-br
394394
if not response.success:
395395
log.error(f"Failed to get repository: {response.status}")
396396
log.error(response.message)
397-
# raise Exception(f"Failed to get repository info: {response.status}, message: {response.message}")
398397
except APIFailure:
399398
log.warning(f"Failed to get repository {repo_slug}, attempting to create it")
400-
create_response = self.sdk.repos.post(self.config.org_slug, name=repo_slug, default_branch=default_branch)
401-
if not create_response.success:
402-
log.error(f"Failed to create repository: {create_response.status}")
403-
log.error(create_response.message)
404-
raise Exception(
405-
f"Failed to create repository: {create_response.status}, message: {create_response.message}"
406-
)
407-
else:
408-
return create_response.data
399+
try:
400+
401+
create_response = self.sdk.repos.post(self.config.org_slug, name=repo_slug, default_branch=default_branch)
402+
403+
# Check if the response is empty (failure) or has content (success)
404+
if not create_response:
405+
log.error("Failed to create repository: empty response")
406+
raise Exception("Failed to create repository: empty response")
407+
else:
408+
return create_response
409+
410+
except APIFailure as e:
411+
log.error(f"API failure while creating repository: {e}")
412+
sys.exit(2) # Exit here with code 2. Code 1 indicates a successfully-detected security issue.
413+
409414
return response.data
410415

411416
def get_head_scan_for_repo(self, repo_slug: str) -> str:

‎socketsecurity/core/logging.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22

3+
34
def initialize_logging(
45
level: int = logging.INFO,
56
format: str = "%(asctime)s: %(message)s",
@@ -23,10 +24,11 @@ def initialize_logging(
2324
cli_logger = logging.getLogger(cli_logger_name)
2425
cli_logger.setLevel(level)
2526

27+
2628
return socket_logger, cli_logger
2729

28-
def set_debug_mode(enable: bool = True) -> None:
30+
def set_debug_mode(enable: bool = False) -> None:
2931
"""Toggle debug logging across all loggers"""
3032
level = logging.DEBUG if enable else logging.INFO
3133
logging.getLogger("socketdev").setLevel(level)
32-
logging.getLogger("socketcli").setLevel(level)
34+
logging.getLogger("socketcli").setLevel(level)

‎socketsecurity/core/messages.py‎

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
import json
2-
import os
3-
import re
4-
import json
52
import logging
6-
logging.basicConfig(level=logging.DEBUG)
7-
3+
import re
84
from pathlib import Path
5+
96
from mdutils import MdUtils
107
from prettytable import PrettyTable
118

129
from socketsecurity.core.classes import Diff, Issue, Purl
1310

11+
log = logging.getLogger("socketcli")
1412

1513
class Messages:
1614

@@ -46,21 +44,21 @@ def find_line_in_file(packagename: str, packageversion: str, manifest_file: str)
4644
- Uses regex patterns to detect a match line by line
4745
"""
4846
file_type = Path(manifest_file).name
49-
logging.debug("Processing file for line lookup: %s", manifest_file)
47+
log.debug("Processing file for line lookup: %s", manifest_file)
5048

5149
if file_type in ["package-lock.json", "Pipfile.lock", "composer.lock"]:
5250
try:
5351
with open(manifest_file, "r", encoding="utf-8") as f:
5452
raw_text = f.read()
55-
logging.debug("Read %d characters from %s", len(raw_text), manifest_file)
53+
log.debug("Read %d characters from %s", len(raw_text), manifest_file)
5654
data = json.loads(raw_text)
5755
packages_dict = (
5856
data.get("packages")
5957
or data.get("default")
6058
or data.get("dependencies")
6159
or {}
6260
)
63-
logging.debug("Found package keys in %s: %s", manifest_file, list(packages_dict.keys()))
61+
log.debug("Found package keys in %s: %s", manifest_file, list(packages_dict.keys()))
6462
found_key = None
6563
found_info = None
6664
for key, value in packages_dict.items():
@@ -72,16 +70,16 @@ def find_line_in_file(packagename: str, packageversion: str, manifest_file: str)
7270
if found_key and found_info:
7371
needle_key = f'"{found_key}":'
7472
lines = raw_text.splitlines()
75-
logging.debug("Total lines in %s: %d", manifest_file, len(lines))
73+
log.debug("Total lines in %s: %d", manifest_file, len(lines))
7674
for i, line in enumerate(lines, start=1):
7775
if needle_key in line:
78-
logging.debug("Found match at line %d in %s: %s", i, manifest_file, line.strip())
76+
log.debug("Found match at line %d in %s: %s", i, manifest_file, line.strip())
7977
return i, line.strip()
8078
return 1, f'"{found_key}": {found_info}'
8179
else:
8280
return 1, f"{packagename} {packageversion} (not found in {manifest_file})"
8381
except (FileNotFoundError, json.JSONDecodeError) as e:
84-
logging.error("Error reading %s: %s", manifest_file, e)
82+
log.error("Error reading %s: %s", manifest_file, e)
8583
return 1, f"Error reading {manifest_file}"
8684

8785
# For pnpm-lock.yaml, use a special regex pattern.
@@ -114,15 +112,15 @@ def find_line_in_file(packagename: str, packageversion: str, manifest_file: str)
114112
}
115113
searchstring = search_patterns.get(file_type, rf'{re.escape(packagename)}.*{re.escape(packageversion)}')
116114

117-
logging.debug("Using search pattern for %s: %s", file_type, searchstring)
115+
log.debug("Using search pattern for %s: %s", file_type, searchstring)
118116
try:
119117
with open(manifest_file, 'r', encoding="utf-8") as file:
120118
lines = [line.rstrip("\n") for line in file]
121-
logging.debug("Total lines in %s: %d", manifest_file, len(lines))
119+
log.debug("Total lines in %s: %d", manifest_file, len(lines))
122120
for line_number, line_content in enumerate(lines, start=1):
123121
line_main = line_content.split(";", 1)[0].strip()
124122
if re.search(searchstring, line_main, re.IGNORECASE):
125-
logging.debug("Match found at line %d in %s: %s", line_number, manifest_file, line_content.strip())
123+
log.debug("Match found at line %d in %s: %s", line_number, manifest_file, line_content.strip())
126124
return line_number, line_content.strip()
127125
except FileNotFoundError:
128126
return 1, f"{manifest_file} not found"
@@ -172,8 +170,8 @@ def create_security_comment_sarif(diff) -> dict:
172170
- For alerts with multiple manifest files, generates an individual SARIF result for each file.
173171
- Appends the manifest file name to the rule ID and name to make each result unique.
174172
- Does NOT fall back to 'requirements.txt' if no manifest file is provided.
175-
- Adds detailed logging to validate our assumptions.
176-
173+
- Adds detailed log to validate our assumptions.
174+
177175
"""
178176
if len(diff.new_alerts) == 0:
179177
for alert in diff.new_alerts:
@@ -204,7 +202,7 @@ def create_security_comment_sarif(diff) -> dict:
204202
base_rule_id = f"{pkg_name}=={pkg_version}"
205203
severity = alert.severity
206204

207-
logging.debug("Alert %s - introduced_by: %s, manifests: %s", base_rule_id, alert.introduced_by, getattr(alert, 'manifests', None))
205+
log.debug("Alert %s - introduced_by: %s, manifests: %s", base_rule_id, alert.introduced_by, getattr(alert, 'manifests', None))
208206
manifest_files = []
209207
if alert.introduced_by and isinstance(alert.introduced_by, list):
210208
for entry in alert.introduced_by:
@@ -216,21 +214,21 @@ def create_security_comment_sarif(diff) -> dict:
216214
elif hasattr(alert, 'manifests') and alert.manifests:
217215
manifest_files = [mf.strip() for mf in alert.manifests.split(";") if mf.strip()]
218216

219-
logging.debug("Alert %s - extracted manifest_files: %s", base_rule_id, manifest_files)
217+
log.debug("Alert %s - extracted manifest_files: %s", base_rule_id, manifest_files)
220218
if not manifest_files:
221-
logging.error("Alert %s: No manifest file found; cannot determine file location.", base_rule_id)
219+
log.error("Alert %s: No manifest file found; cannot determine file location.", base_rule_id)
222220
continue
223221

224-
logging.debug("Alert %s - using manifest_files for processing: %s", base_rule_id, manifest_files)
222+
log.debug("Alert %s - using manifest_files for processing: %s", base_rule_id, manifest_files)
225223

226224
# Create an individual SARIF result for each manifest file.
227225
for mf in manifest_files:
228-
logging.debug("Alert %s - Processing manifest file: %s", base_rule_id, mf)
226+
log.debug("Alert %s - Processing manifest file: %s", base_rule_id, mf)
229227
socket_url = Messages.get_manifest_type_url(mf, pkg_name, pkg_version)
230228
line_number, line_content = Messages.find_line_in_file(pkg_name, pkg_version, mf)
231229
if line_number < 1:
232230
line_number = 1
233-
logging.debug("Alert %s: Manifest %s, line %d: %s", base_rule_id, mf, line_number, line_content)
231+
log.debug("Alert %s: Manifest %s, line %d: %s", base_rule_id, mf, line_number, line_content)
234232

235233
# Create a unique rule id and name by appending the manifest file.
236234
unique_rule_id = f"{base_rule_id} ({mf})"
@@ -271,7 +269,7 @@ def create_security_comment_sarif(diff) -> dict:
271269
sarif_data["runs"][0]["results"] = results_list
272270

273271
return sarif_data
274-
272+
275273
@staticmethod
276274
def create_security_comment_json(diff: Diff) -> dict:
277275
scan_failed = False

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /