From fca8815876d9d6f8bd5eab8ee9bdf281bde896ed Mon Sep 17 00:00:00 2001 From: Tushar Goel <34160672+TG1999@users.noreply.github.com> Date: Mon, 27 Nov 2023 12:20:09 +0530 Subject: [PATCH] Add middleware to ban bytedance user agent (#1347) * Add middleware to ban bytedance user agent Signed-off-by: Tushar Goel * Change response type Signed-off-by: Tushar Goel --------- Signed-off-by: Tushar Goel --- vulnerabilities/middleware/ban_user_agent.py | 18 ++++++++++++++++++ vulnerabilities/tests/test_api.py | 6 ++++++ vulnerablecode/settings.py | 1 + 3 files changed, 25 insertions(+) create mode 100644 vulnerabilities/middleware/ban_user_agent.py 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"