Skip to content
Draft
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
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,22 @@
# Changelog

## 3.7.0

### Added: `SocketAlert.actionAfterPullRequestIgnore`

- Alerts read from `diffscans.get()` (through `DiffArtifacts.from_dict`),
`fullscans.stream_diff()` and `fullscans.stream()` carry the API's new
`actionAfterPullRequestIgnore`: the action an alert keeps when a pull or
merge request comment ignores its package (`error`, `warn` or `monitor`).
It is `None` when the API leaves it out, which means the ignore removes the
alert. The API sends it only for organizations on the new Socket Policies.
- `fullscans.stream()` keeps it when it merges duplicate alerts, taking the
strictest value across the sightings (`error`, then `warn`, then `monitor`).
A sighting without it counts as least strict.
- Serializing an alert (`to_dict()`, or `dataclasses.asdict()` on an alert or
on anything that contains alerts) now includes an
`actionAfterPullRequestIgnore` key, `None` when the API didn't send it.

## 3.6.4

### Fixed: every advisory on a package is kept
Expand Down
7 changes: 7 additions & 0 deletions socketdev/core/dedupe.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ def consolidate_and_merge_alerts(package_group: List[Dict[str, Any]]) -> Dict[st
consolidated_alert["start"] = alert["start"]
if "end" in alert:
consolidated_alert["end"] = alert["end"]
if alert.get("actionAfterPullRequestIgnore") is not None:
consolidated_alert["actionAfterPullRequestIgnore"] = alert["actionAfterPullRequestIgnore"]

alert_map[identity] = consolidated_alert
else:
Expand All @@ -99,6 +101,11 @@ def consolidate_and_merge_alerts(package_group: List[Dict[str, Any]]) -> Dict[st
# key can belong to a release with a less severe action.
if Dedupe.action_rank(alert.get("action")) > Dedupe.action_rank(merged.get("action")):
merged["action"] = alert.get("action")
after_ignore = alert.get("actionAfterPullRequestIgnore")
if Dedupe.action_rank(after_ignore) > Dedupe.action_rank(
merged.get("actionAfterPullRequestIgnore")
):
merged["actionAfterPullRequestIgnore"] = after_ignore

base = package_group[0]
base["releases"] = sorted(releases)
Expand Down
2 changes: 2 additions & 0 deletions socketdev/fullscans/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,7 @@ class SocketAlert:
props: Optional[Dict[str, Any]] = None
action: Optional[str] = None
actionPolicyIndex: Optional[int] = None
actionAfterPullRequestIgnore: Optional[str] = None

def __getitem__(self, key):
return getattr(self, key)
Expand All @@ -525,6 +526,7 @@ def from_dict(cls, data: dict) -> "SocketAlert":
props=data.get("props"),
action=data.get("action"),
actionPolicyIndex=data.get("actionPolicyIndex"),
actionAfterPullRequestIgnore=data.get("actionAfterPullRequestIgnore"),
)


Expand Down
2 changes: 1 addition & 1 deletion socketdev/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "3.6.4"
__version__ = "3.7.0"
43 changes: 43 additions & 0 deletions tests/unit/test_dedupe.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,49 @@ def file_alert(path, action):
self.assertEqual(alerts[0]["action"], "warn")
self.assertEqual(alerts[0]["releases"], ["wheel", "sdist"])

@staticmethod
def _sightings(*after_ignore_actions, action="error"):
alerts = []
for after_ignore in after_ignore_actions:
alert = {"key": "key-malware", "type": "malware", "severity": "critical",
"category": "supplyChainRisk", "action": action, "props": {}}
if after_ignore is not None:
alert["actionAfterPullRequestIgnore"] = after_ignore
alerts.append(alert)
return [
{"id": f"artifact-{i}", "type": "pypi", "name": "example", "version": "1.0",
"release": f"r{i}", "inputPurl": "pkg:pypi/example@1.0", "alerts": [alert]}
for i, alert in enumerate(alerts)
]

def test_alert_without_action_after_pull_request_ignore_gets_no_key(self):
alerts = Dedupe.dedupe(self._sightings(None, None))[0]["alerts"]

self.assertEqual(len(alerts), 1)
self.assertNotIn("actionAfterPullRequestIgnore", alerts[0])

def test_action_after_pull_request_ignore_is_copied_from_a_single_sighting(self):
for after_ignore in ("error", "warn", "monitor"):
with self.subTest(after_ignore=after_ignore):
alerts = Dedupe.dedupe(self._sightings(after_ignore))[0]["alerts"]
self.assertEqual(alerts[0]["actionAfterPullRequestIgnore"], after_ignore)

def test_merged_action_after_pull_request_ignore_is_the_strictest_sighting(self):
"""A sighting without the key means the ignore removes it there, so it ranks lowest"""
cases = [
([None, "warn"], "warn"),
(["warn", None], "warn"),
(["monitor", "error", "warn"], "error"),
(["warn", "monitor"], "warn"),
([None, "monitor"], "monitor"),
]
for after_ignore_actions, expected in cases:
with self.subTest(after_ignore_actions=after_ignore_actions):
alerts = Dedupe.dedupe(self._sightings(*after_ignore_actions))[0]["alerts"]
self.assertEqual(len(alerts), 1)
self.assertEqual(alerts[0]["action"], "error")
self.assertEqual(alerts[0]["actionAfterPullRequestIgnore"], expected)


if __name__ == '__main__':
unittest.main()
43 changes: 43 additions & 0 deletions tests/unit/test_full_scan_cached_polling_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,49 @@ def cve(ghsa, cve_id, action):
]


def test_stream_carries_action_after_pull_request_ignore(api_fixture):
path = "orgs/org/full-scans/scan"

def release(name, alerts):
return {
"id": "artifact-1", "type": "pypi", "name": "example", "version": "1.0",
"release": name, "inputPurl": "pkg:pypi/example@1.0", "alerts": alerts,
}

malware = {"key": "key-malware", "type": "malware", "severity": "critical",
"category": "supplyChainRisk", "action": "error"}
typosquat = {"key": "key-typo", "type": "didYouMean", "severity": "high",
"category": "supplyChainRisk", "action": "error"}
api_fixture.route("GET", path, ndjson(
release("wheel", [malware, dict(typosquat, actionAfterPullRequestIgnore="error")]),
release("sdist", [dict(malware, actionAfterPullRequestIgnore="warn"), typosquat]),
))

typed = sdk_for(api_fixture).fullscans.stream("org", "scan", use_types=True)

alerts = {alert.type: alert for alert in typed.artifacts["artifact-1"].alerts}
assert alerts["malware"].action == "error"
assert alerts["malware"].actionAfterPullRequestIgnore == "warn"
assert alerts["didYouMean"].actionAfterPullRequestIgnore == "error"


def test_stream_alert_without_action_after_pull_request_ignore_reads_none(api_fixture):
path = "orgs/org/full-scans/scan"
artifact = {
"id": "artifact-1",
"alerts": [{"key": "test-key", "type": "test", "severity": "high", "category": "quality",
"action": "error"}],
}
api_fixture.route("GET", path, ndjson(artifact))
sdk = sdk_for(api_fixture)

raw = sdk.fullscans.stream("org", "scan")
typed = sdk.fullscans.stream("org", "scan", use_types=True)

assert "actionAfterPullRequestIgnore" not in raw["artifact-1"]["alerts"][0]
assert typed.artifacts["artifact-1"].alerts[0].actionAfterPullRequestIgnore is None


@pytest.mark.parametrize("status", [403, 404])
def test_deterministic_errors_stop_immediately(api_fixture, status):
api_fixture.route("GET", "orgs/org/full-scans/scan", SocketResponse(status, {"error": {"message": "denied"}}))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import json
import unittest
from dataclasses import asdict

from socketdev.fullscans import DiffArtifacts, SocketAlert

DIFF_SCAN_ARTIFACTS = json.loads("""
{
"added": [
{
"diffType": "added",
"id": "artifact-1",
"type": "npm",
"name": "minimist",
"version": "0.0.4",
"licenseDetails": [],
"alerts": [
{"key": "key-kept", "type": "malware", "severity": "critical",
"category": "supplyChainRisk", "action": "error", "actionPolicyIndex": 1,
"actionAfterPullRequestIgnore": "error"},
{"key": "key-lowered", "type": "didYouMean", "severity": "high",
"category": "supplyChainRisk", "action": "error",
"actionAfterPullRequestIgnore": "warn"},
{"key": "key-removed", "type": "envVars", "severity": "low",
"category": "supplyChainRisk", "action": "error"}
]
}
],
"removed": [],
"unchanged": [],
"replaced": [],
"updated": []
}
""")


class TestActionAfterPullRequestIgnore(unittest.TestCase):
def test_diff_artifacts_read_the_field_per_alert(self):
artifacts = DiffArtifacts.from_dict(DIFF_SCAN_ARTIFACTS)

alerts = {alert.key: alert for alert in artifacts.added[0].alerts}
self.assertEqual(alerts["key-kept"].actionAfterPullRequestIgnore, "error")
self.assertEqual(alerts["key-lowered"].actionAfterPullRequestIgnore, "warn")
self.assertIsNone(alerts["key-removed"].actionAfterPullRequestIgnore)
self.assertEqual(alerts["key-kept"].actionPolicyIndex, 1)

def test_absent_field_serializes_as_none(self):
alert = SocketAlert.from_dict(
{"key": "k", "type": "malware", "severity": "critical",
"category": "supplyChainRisk", "action": "error"}
)

self.assertIsNone(alert.actionAfterPullRequestIgnore)
self.assertIsNone(asdict(alert)["actionAfterPullRequestIgnore"])
self.assertEqual(alert.to_dict(), asdict(alert))
self.assertEqual(list(asdict(alert))[-1], "actionAfterPullRequestIgnore")


if __name__ == "__main__":
unittest.main()