diff --git a/vulnerabilities/middleware/ban_user_agent.py b/vulnerabilities/middleware/ban_user_agent.py new file mode 100644 index 000000000..6aafc490c --- /dev/null +++ b/vulnerabilities/middleware/ban_user_agent.py @@ -0,0 +1,18 @@ +# +# Copyright (c) nexB Inc. and others. All rights reserved. +# VulnerableCode is a trademark of nexB Inc. +# SPDX-License-Identifier: Apache-2.0 +# See http://www.apache.org/licenses/LICENSE-2.0 for the license text. +# See https://github.com/nexB/vulnerablecode for support or download. +# See https://aboutcode.org for more information about nexB OSS projects. +# + +from django.http import HttpResponseNotFound +from django.utils.deprecation import MiddlewareMixin + + +class BanUserAgent(MiddlewareMixin): + def process_request(self, request): + user_agent = request.META.get("HTTP_USER_AGENT", None) + if user_agent and "bytedance" in user_agent: + return HttpResponseNotFound(404) diff --git a/vulnerabilities/tests/test_api.py b/vulnerabilities/tests/test_api.py index 5ead38a2d..5dd9a2319 100644 --- a/vulnerabilities/tests/test_api.py +++ b/vulnerabilities/tests/test_api.py @@ -650,3 +650,9 @@ def test_with_invalid_cpes(self): content_type="application/json", ).json() assert response == {"Error": "Invalid CPE: CVE-2022-2022"} + + +class TesBanUserAgent(TestCase): + def test_ban_request_with_bytedance_user_agent(self): + response = self.client.get(f"/api/packages", format="json", HTTP_USER_AGENT="bytedance") + assert 404 == response.status_code diff --git a/vulnerablecode/settings.py b/vulnerablecode/settings.py index 525127915..48c849225 100644 --- a/vulnerablecode/settings.py +++ b/vulnerablecode/settings.py @@ -89,6 +89,7 @@ "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", + "vulnerabilities.middleware.ban_user_agent.BanUserAgent", ) ROOT_URLCONF = "vulnerablecode.urls"