From d1ea22771bd792604e72cbe5b23389839b17777e Mon Sep 17 00:00:00 2001 From: Aakash Velusamy Date: Mon, 30 Nov 2026 02:49:17 +0530 Subject: [PATCH] refactor: send device_discovery_id on the discovery wire (#380) * feat(web-5977): send device_discovery_id on the discovery wire Renames the payload key device_id -> device_discovery_id across the report, scan-event, metrics, and S3 (meta + notify) payloads. The S3 uploader reads the new key with a fallback to device_id so any old-format payloads already queued offline still upload. Deploy AFTER gateway-data accepts both keys. Updated the wire-key assertions in the discovery-flow, s3-uploader and send-and-persist tests. * Merge pull request #433 from websentry-ai/WEB-6710 [WEB-6710] (#434) [WEB-6710] fix(skills): fit skill folders to a report budget, never drop a report [WEB-6710] * test: cover the new wire key on the s3 path, not just the fallback Every S3 fixture built its payload with the legacy device_id, so the tests only ever exercised the uploader's fallback branch while production now sends device_discovery_id. The default fixture now matches what the device builds, and a separate test covers a report queued before the rename. Verified the new test fails without the fallback and passes with it. Co-Authored-By: Claude Opus 5 * test: guard the metrics payload's device key The metrics POST piggybacks on the report endpoint and carries the device key like any other payload, but nothing asserted it. A regression to the old key would have shipped silently. Verified the guard bites: reverting just the metrics key makes this test fail with a KeyError, and it passes again once restored. Co-Authored-By: Claude Opus 5 * fix: send device_discovery_id on the memory-fix wire too The memory-fix fetch and results POSTs were the last outbound paths still naming the device with the legacy key, so the claim that every path moved was not yet true. Nothing breaks either way today because the backend accepts both names, but it would once the legacy key is retired. The payload assertions move with it and stay exact-match, so a regression to the old key still fails them. Co-Authored-By: Claude Opus 5 --------- Co-authored-by: AakashVelusamy Co-authored-by: Vishnu <79318686+zeus-12@users.noreply.github.com> Co-authored-by: NandaPranesh <106886030+anonpran@users.noreply.github.com> Co-authored-by: Vignesh Subbiah <51325334+vigneshsubbiah16@users.noreply.github.com> Co-authored-by: Claude Fable 5.2 Co-authored-by: pugazhendhi-m <132246623+pugazhendhi-m@users.noreply.github.com> Co-authored-by: Iyad Zargar Co-authored-by: Iyad Zargar Co-authored-by: Attachment Aditya --- .../ai_tools_discovery.py | 4 +-- scripts/coding_discovery_tools/memory_fix.py | 4 +-- scripts/coding_discovery_tools/s3_uploader.py | 4 +-- scripts/coding_discovery_tools/utils.py | 4 +-- tests/test_discovery_flow.py | 2 +- tests/test_memory_fix.py | 4 +-- tests/test_s3_uploader.py | 28 +++++++++++++++++-- tests/test_send_and_persist.py | 22 ++++++++++++++- 8 files changed, 58 insertions(+), 14 deletions(-) diff --git a/scripts/coding_discovery_tools/ai_tools_discovery.py b/scripts/coding_discovery_tools/ai_tools_discovery.py index 62f50cb4a..7648c5dcb 100644 --- a/scripts/coding_discovery_tools/ai_tools_discovery.py +++ b/scripts/coding_discovery_tools/ai_tools_discovery.py @@ -3818,7 +3818,7 @@ def generate_single_tool_report(self, tool: Dict, device_id: str, home_user: str report = { "home_user": home_user, "system_user": system_user or home_user, - "device_id": device_id, + "device_discovery_id": device_id, "is_container": in_container(), "tools": [tool_for_report] } @@ -3850,7 +3850,7 @@ def generate_report(self) -> Dict: return { "system_user": user_info, - "device_id": device_id, + "device_discovery_id": device_id, "tools": tools_with_projects } diff --git a/scripts/coding_discovery_tools/memory_fix.py b/scripts/coding_discovery_tools/memory_fix.py index c4e625cc7..c587e2f52 100644 --- a/scripts/coding_discovery_tools/memory_fix.py +++ b/scripts/coding_discovery_tools/memory_fix.py @@ -205,14 +205,14 @@ def _post_json(link: _Link, path: str, body: Dict) -> Optional[Dict]: def _placements(link: _Link, posted: List[Dict]) -> Optional[List[Dict]]: """Every answer the backend gave for the posted files, or None when the post failed.""" files = [{key: entry[key] for key in ("home_user", "file_path", "sha256")} for entry in posted] - answer = _post_json(link, FIXES_PATH, {"device_id": link.device_id, "files": files}) + answer = _post_json(link, FIXES_PATH, {"device_discovery_id": link.device_id, "files": files}) fixes = answer.get("fixes") if answer else None return [fix for fix in fixes if isinstance(fix, dict)] if isinstance(fixes, list) else None def _post_result(link: _Link, result: Dict) -> bool: """True when the result reached the backend; a post that fails is tried again, as the edit is already made.""" - body = {"device_id": link.device_id, "results": [result]} + body = {"device_discovery_id": link.device_id, "results": [result]} return any(_post_json(link, RESULTS_PATH, body) is not None for _ in range(RESULT_POST_TRIES)) diff --git a/scripts/coding_discovery_tools/s3_uploader.py b/scripts/coding_discovery_tools/s3_uploader.py index 287d5189b..8b92b6f45 100644 --- a/scripts/coding_discovery_tools/s3_uploader.py +++ b/scripts/coding_discovery_tools/s3_uploader.py @@ -157,7 +157,7 @@ def try_s3_upload( ctx = sentry_context or {} # ─── Step 1: get presigned URL ────────────────────────────────────── - meta_body = {"device_id": payload.get("device_id")} + meta_body = {"device_discovery_id": payload.get("device_discovery_id") or payload.get("device_id")} if payload.get("run_id"): meta_body["run_id"] = payload["run_id"] @@ -209,7 +209,7 @@ def try_s3_upload( # backend's /from-s3/ handler receives the same context (including # `app_name` for MDM-tagged scans like JumpCloud). notify_body = { - "device_id": payload.get("device_id"), + "device_discovery_id": payload.get("device_discovery_id") or payload.get("device_id"), "object_key": object_key, "system_user": payload.get("system_user"), "home_user": payload.get("home_user"), diff --git a/scripts/coding_discovery_tools/utils.py b/scripts/coding_discovery_tools/utils.py index c3f7135e7..386617efc 100644 --- a/scripts/coding_discovery_tools/utils.py +++ b/scripts/coding_discovery_tools/utils.py @@ -1516,7 +1516,7 @@ def send_scan_event( Tuple of (success, retryable): success=True if sent, retryable=True if caller should queue """ payload = { - "device_id": device_id, + "device_discovery_id": device_id, "run_id": run_id, "scan_event": scan_event, } @@ -3798,7 +3798,7 @@ def send_discovery_metrics( url = f"{normalize_url(backend_url)}/api/v1/ai-tools/report/" payload: Dict[str, Any] = { - "device_id": device_id, + "device_discovery_id": device_id, "tools": [], "sentry_metrics": sentry_metrics, } diff --git a/tests/test_discovery_flow.py b/tests/test_discovery_flow.py index cdd4e00f8..9588143b5 100644 --- a/tests/test_discovery_flow.py +++ b/tests/test_discovery_flow.py @@ -180,7 +180,7 @@ def test_detect_and_report_flow(self): # Assert required top-level keys self.assertIn("home_user", report) self.assertIn("system_user", report) - self.assertIn("device_id", report) + self.assertIn("device_discovery_id", report) self.assertIn("tools", report) self.assertEqual(len(report["tools"]), 1) diff --git a/tests/test_memory_fix.py b/tests/test_memory_fix.py index 7076e4e49..d29a24e2b 100644 --- a/tests/test_memory_fix.py +++ b/tests/test_memory_fix.py @@ -484,13 +484,13 @@ def test_a_ready_fix_runs_the_helper_and_posts_the_result_with_its_token(self): counts = self.run_fixes([held]) posted = self.fix_posts()[0] - self.assertEqual(posted, {"device_id": "dev-1", "files": [ + self.assertEqual(posted, {"device_discovery_id": "dev-1", "files": [ {"home_user": ME, "file_path": held["file_path"], "sha256": _sha(text.encode())}]}) self.assertEqual(self.helper_calls[0][0], { "op": "fix", "file_path": held["file_path"], "memory_root": str(self.root), "sha256": _sha(text.encode()), "spans": [_span(text, SECRET_A)]}) self.assertEqual(self.helper_calls[0][1:], (pwd.getpwnam(ME).pw_uid, pwd.getpwnam(ME).pw_gid)) - self.assertEqual(self.result_posts(), [{"device_id": "dev-1", "results": [ + self.assertEqual(self.result_posts(), [{"device_discovery_id": "dev-1", "results": [ {"id": 7, "outcome": "fixed", "token": "T-7"}]}]) self.assertEqual(Path(held["file_path"]).read_text(), "t " + MARKER) self.assertEqual(counts, {"rounds": 1, "fixed": 1}) diff --git a/tests/test_s3_uploader.py b/tests/test_s3_uploader.py index 534fa5679..4c862b189 100644 --- a/tests/test_s3_uploader.py +++ b/tests/test_s3_uploader.py @@ -96,7 +96,7 @@ def _set_path_response(self, path, code, body): class TestS3UploadFlow(_ServerMixin, unittest.TestCase): def _payload(self): return { - "device_id": "DEV-1", + "device_discovery_id": "DEV-1", "system_user": "alice", "home_user": "alice", "run_id": str(uuid.uuid4()), @@ -135,7 +135,31 @@ def test_happy_path_three_steps(self): from_s3_body = json.loads(self.server.requests[2]["body"]) self.assertNotIn("tools", from_s3_body) self.assertEqual(from_s3_body["object_key"], "org/1/run/abc.json") - self.assertEqual(from_s3_body["device_id"], "DEV-1") + self.assertEqual(from_s3_body["device_discovery_id"], "DEV-1") + + @patch.object(utils_mod, "_SENTRY_DSN", "") + def test_queued_payload_with_legacy_key_still_sends_the_new_one(self): + """A report queued before the rename carries device_id; both bodies must still name the device.""" + upload_url = f"{self.base_url}/s3-bucket/object-key.json" + self._set_path_response("/api/v1/ai-tools/report/upload-url/", 200, json.dumps({ + "upload_url": upload_url, + "object_key": "org/1/run/legacy.json", + "expires_in": 300, + }).encode()) + self._set_path_response("/s3-bucket/object-key.json", 200, b"") + self._set_path_response("/api/v1/ai-tools/report/from-s3/", 202, json.dumps({"status": "queued"}).encode()) + + legacy = self._payload() + legacy["device_id"] = legacy.pop("device_discovery_id") + + success, retryable = try_s3_upload(self.base_url, "k", legacy) + + self.assertTrue(success) + self.assertFalse(retryable) + meta_body = json.loads(self.server.requests[0]["body"]) + from_s3_body = json.loads(self.server.requests[2]["body"]) + self.assertEqual(meta_body["device_discovery_id"], "DEV-1") + self.assertEqual(from_s3_body["device_discovery_id"], "DEV-1") @patch.object(utils_mod, "_SENTRY_DSN", "") def test_app_name_forwarded_to_step3(self): diff --git a/tests/test_send_and_persist.py b/tests/test_send_and_persist.py index a2d9ce6f9..4441793ed 100644 --- a/tests/test_send_and_persist.py +++ b/tests/test_send_and_persist.py @@ -388,7 +388,7 @@ def test_scan_in_progress_event(self, _sleep): # Verify payload structure payload = json.loads(self.server.requests[0]["body"]) - self.assertEqual(payload["device_id"], "DEVICE123") + self.assertEqual(payload["device_discovery_id"], "DEVICE123") self.assertEqual(payload["run_id"], "run-uuid-1234") self.assertEqual(payload["scan_event"], "in_progress") self.assertEqual(payload["app_name"], "JumpCloud") @@ -502,6 +502,26 @@ def test_scan_failed_device_level_error(self, _sleep): self.assertNotIn("home_user", payload) # No user context for device-level errors self.assertEqual(payload["scan_error"]["error_type"], "RuntimeError") + @patch("time.sleep") + @patch.object(utils_mod, "_SENTRY_DSN", "") + def test_metrics_payload_names_the_device_with_the_new_key(self, _sleep): + """Metrics piggyback on the report endpoint, so they must carry the new wire key too.""" + sent = utils_mod.send_discovery_metrics( + self.base_url, + "test-key", + "DEVICE123", + {"run_seconds": 1.5}, + run_id="run-uuid-1234", + ) + + self.assertTrue(sent) + self.assertEqual(len(self.server.requests), 1) + payload = json.loads(self.server.requests[0]["body"]) + self.assertEqual(payload["device_discovery_id"], "DEVICE123") + self.assertNotIn("device_id", payload) + + + class TestSentryPriorityBypassesCap(unittest.TestCase): """A priority=True event (the terminal no_tools_found summary) bypasses the