Skip to content

Commit

Permalink
Add middleware to ban bytedance user agent (#1347)
Browse files Browse the repository at this point in the history
* Add middleware to ban bytedance user agent

Signed-off-by: Tushar Goel <tushar.goel.dav@gmail.com>

* Change response type

Signed-off-by: Tushar Goel <tushar.goel.dav@gmail.com>

---------

Signed-off-by: Tushar Goel <tushar.goel.dav@gmail.com>
  • Loading branch information
TG1999 authored Nov 27, 2023
1 parent c94e7e9 commit fca8815
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
18 changes: 18 additions & 0 deletions vulnerabilities/middleware/ban_user_agent.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 6 additions & 0 deletions vulnerabilities/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions vulnerablecode/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit fca8815

Please sign in to comment.