Skip to content

Added Slack plugin support #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ If you don't want to provide the Socket API Token every time then you can use th
The Python CLI currently Supports the following plugins:

- Jira
- Slack

##### Jira

Expand All @@ -95,6 +96,18 @@ Example `SOCKET_JIRA_CONFIG_JSON` value
{"url": "https://REPLACE_ME.atlassian.net", "email": "[email protected]", "api_token": "REPLACE_ME", "project": "REPLACE_ME" }
````

##### Slack

| Environment Variable | Required | Default | Description |
|:-------------------------|:---------|:--------|:-----------------------------------|
| SOCKET_SLACK_ENABLED | False | false | Enables/Disables the Slack Plugin |
| SOCKET_SLACK_CONFIG_JSON | True | None | Required if the Plugin is enabled. |

Example `SOCKET_SLACK_CONFIG_JSON` value

````json
{"url": "https://REPLACE_ME_WEBHOOK"}
````

## File Selection Behavior

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "hatchling.build"

[project]
name = "socketsecurity"
version = "2.0.50"
version = "2.0.51"
requires-python = ">= 3.10"
license = {"file" = "LICENSE"}
dependencies = [
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
__author__ = 'socket.dev'
__version__ = '2.0.50'
__version__ = '2.0.51'
6 changes: 6 additions & 0 deletions socketsecurity/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ class CliConfig:
include_module_folders: bool = False
version: str = __version__
jira_plugin: PluginConfig = field(default_factory=PluginConfig)
slack_plugin: PluginConfig = field(default_factory=PluginConfig)

@classmethod
def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
Expand Down Expand Up @@ -100,6 +101,11 @@ def from_args(cls, args_list: Optional[List[str]] = None) -> 'CliConfig':
enabled=os.getenv("SOCKET_JIRA_ENABLED", "false").lower() == "true",
levels=os.getenv("SOCKET_JIRA_LEVELS", "block,warn").split(","),
config=get_plugin_config_from_env("SOCKET_JIRA")
),
"slack_plugin": PluginConfig(
enabled=os.getenv("SOCKET_SLACK_ENABLED", "false").lower() == "true",
levels=os.getenv("SOCKET_SLACK_LEVELS", "block,warn").split(","),
config=get_plugin_config_from_env("SOCKET_SLACK")
)
})

Expand Down
16 changes: 12 additions & 4 deletions socketsecurity/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
from .core.classes import Diff, Issue
from .config import CliConfig
from socketsecurity.plugins.manager import PluginManager
from socketdev import socketdev


class OutputHandler:
config: CliConfig
logger: logging.Logger

def __init__(self, config: CliConfig):
def __init__(self, config: CliConfig, sdk: socketdev):
self.config = config
self.logger = logging.getLogger("socketcli")

Expand All @@ -24,16 +25,23 @@ def handle_output(self, diff_report: Diff) -> None:
self.output_console_sarif(diff_report, self.config.sbom_file)
else:
self.output_console_comments(diff_report, self.config.sbom_file)
if hasattr(self.config, "jira_plugin") and self.config.jira_plugin.enabled:
if self.config.jira_plugin.enabled:
jira_config = {
"enabled": self.config.jira_plugin.enabled,
"levels": self.config.jira_plugin.levels or [],
**(self.config.jira_plugin.config or {})
}

plugin_mgr = PluginManager({"jira": jira_config})
plugin_mgr.send(diff_report, config=self.config)

if self.config.slack_plugin.enabled:
slack_config = {
"enabled": self.config.slack_plugin.enabled,
"levels": self.config.slack_plugin.levels or [],
**(self.config.slack_plugin.config or {})
}

# The Jira plugin knows how to build title + description from diff/config
plugin_mgr = PluginManager({"slack": slack_config})
plugin_mgr.send(diff_report, config=self.config)

self.save_sbom_file(diff_report, self.config.sbom_file)
Expand Down
2 changes: 1 addition & 1 deletion socketsecurity/plugins/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ class Plugin:
def __init__(self, config):
self.config = config

def send(self, message, level):
def send(self, diff, config):
raise NotImplementedError("Plugin must implement send()")
81 changes: 76 additions & 5 deletions socketsecurity/plugins/slack.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,83 @@
from .base import Plugin
import logging
import requests
from config import CliConfig
from .base import Plugin
from socketsecurity.core.classes import Diff
from socketsecurity.core.messages import Messages

logger = logging.getLogger(__name__)


class SlackPlugin(Plugin):
def send(self, message, level):
@staticmethod
def get_name():
return "slack"

def send(self, diff, config: CliConfig):
if not self.config.get("enabled", False):
return
if level not in self.config.get("levels", ["block", "warn"]):
if not self.config.get("url"):
logger.warning("Slack webhook URL not configured.")
return
else:
url = self.config.get("url")

if not diff.new_alerts:
logger.debug("No new alerts to notify via Slack.")
return

payload = {"text": message.get("title", "No title")}
requests.post(self.config["webhook_url"], json=payload)
logger.debug("Slack Plugin Enabled")
logger.debug("Alert levels: %s", self.config.get("levels"))

message = self.create_slack_blocks_from_diff(diff, config)
logger.debug(f"Sending message to {url}")
response = requests.post(
url,
json={"blocks": message}
)

if response.status_code >= 400:
logger.error("Slack error %s: %s", response.status_code, response.text)

@staticmethod
def create_slack_blocks_from_diff(diff: Diff, config: CliConfig):
pr = getattr(config, "pr_number", None)
sha = getattr(config, "commit_sha", None)
scan_link = getattr(diff, "diff_url", "")
scan = f"<{scan_link}|scan>"
title_part = ""
if pr:
title_part += f" for PR {pr}"
if sha:
title_part += f" - {sha[:8]}"
blocks = [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*Socket Security issues were found in this *{scan}*{title_part}*"
}
},
{"type": "divider"}
]

for alert in diff.new_alerts:
manifest_str, source_str = Messages.create_sources(alert, "plain")
manifest_str = manifest_str.lstrip("• ")
source_str = source_str.lstrip("• ")
blocks.append({
"type": "section",
"text": {
"type": "mrkdwn",
"text": (
f"*{alert.title}*\n"
f"<{alert.url}|{alert.purl}>\n"
f"*Introduced by:* `{source_str}`\n"
f"*Manifest:* `{manifest_str}`\n"
f"*CI Status:* {'Block' if alert.error else 'Warn'}"
)
}
})
blocks.append({"type": "divider"})

return blocks
2 changes: 1 addition & 1 deletion socketsecurity/socketcli.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ def main_code():
config = CliConfig.from_args()
log.info(f"Starting Socket Security CLI version {config.version}")
log.debug(f"config: {config.to_dict()}")
output_handler = OutputHandler(config)

# Validate API token
if not config.api_token:
Expand All @@ -57,6 +56,7 @@ def main_code():
sys.exit(3)

sdk = socketdev(token=config.api_token)
output_handler = OutputHandler(config, sdk)
log.debug("sdk loaded")

if config.enable_debug:
Expand Down
Loading