Skip to content

Commit d95b180

Browse files
committedMay 1, 2023
added firewall
1 parent d5b4f06 commit d95b180

File tree

5 files changed

+33
-27
lines changed

5 files changed

+33
-27
lines changed
 

‎requirements.txt

20 Bytes
Binary file not shown.

‎src/config/config.py

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ class Config:
8282
class CloudFlareSettings(BaseSettings):
8383
EMAIL: str = Field(..., env="CLOUDFLARE_EMAIL")
8484
TOKEN: str = Field(..., env="CLOUDFLARE_TOKEN")
85+
X_CLIENT_SECRET_TOKEN: str = Field(..., env="X_CLIENT_SECRET_TOKEN")
8586

8687
class Config:
8788
case_sensitive = True

‎src/firewall/__init__.py

+23-26
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import re
2+
import hmac
23
import ipaddress
3-
import httpx
4+
5+
import requests
46
from CloudFlare import CloudFlare
57
from CloudFlare.exceptions import CloudFlareAPIError
68
from flask import Flask, request
@@ -68,27 +70,6 @@ def contains_malicious_patterns(_input: str) -> bool:
6870
EMAIL: str = config_instance().CLOUDFLARE_SETTINGS.EMAIL
6971
TOKEN: str = config_instance().CLOUDFLARE_SETTINGS.TOKEN
7072

71-
async_client = httpx.AsyncClient(http2=True, limits=httpx.Limits(max_connections=100, max_keepalive_connections=20))
72-
73-
74-
async def send_request(api_url: str, headers: dict[str, str | int], method: str = 'get',
75-
data: str | None = None):
76-
try:
77-
if method.lower() == "get":
78-
response = await async_client.get(url=api_url, headers=headers, timeout=360000)
79-
elif method.lower() == "post":
80-
if data:
81-
response = await async_client.post(url=api_url, json=data, headers=headers, timeout=360000)
82-
else:
83-
response = await async_client.post(url=api_url, headers=headers, timeout=360000)
84-
else:
85-
return None
86-
except httpx.HTTPError as http_err:
87-
raise http_err
88-
except Exception as err:
89-
raise err
90-
return response.json()
91-
9273

9374
class Firewall:
9475
"""
@@ -116,6 +97,7 @@ def init_app(self, app: Flask):
11697
app.before_request(self.is_host_valid)
11798
app.before_request(self.is_edge_ip_allowed)
11899
app.before_request(self.check_if_request_malicious)
100+
app.before_request(self.verify_client_secret_token)
119101
# obtain the latest cloudflare edge servers
120102
ipv4, ipv6 = self.get_ip_ranges()
121103
# updating the ip ranges
@@ -161,6 +143,19 @@ def check_if_request_malicious(self):
161143
if any((pattern.match(path) for pattern in self.compiled_bad_patterns)):
162144
raise UnAuthenticatedError('Payload is suspicious')
163145

146+
@staticmethod
147+
def verify_client_secret_token():
148+
client_secret_token = request.headers.get('X_CLIENT_SECRET_TOKEN')
149+
if not client_secret_token:
150+
raise UnAuthenticatedError('Missing client secret token')
151+
152+
expected_secret_token = config_instance().CLOUDFLARE_SETTINGS.get('X_CLIENT_SECRET_TOKEN')
153+
if not expected_secret_token:
154+
raise ValueError('Missing expected client secret token')
155+
156+
if not hmac.compare_digest(client_secret_token, expected_secret_token):
157+
raise UnAuthenticatedError('Invalid client secret token')
158+
164159
@staticmethod
165160
def get_client_ip() -> str:
166161
"""
@@ -184,10 +179,12 @@ def get_ip_ranges() -> tuple[list[str], list[str]]:
184179
_uri = 'https://api.cloudflare.com/client/v4/ips'
185180
_headers = {'Accept': 'application/json', 'X-Auth-Email': EMAIL}
186181
try:
187-
response = await send_request(api_url=_uri, headers=_headers)
188-
ipv4_cidrs = response.get('result', {}).get('ipv4_cidrs', DEFAULT_IPV4)
189-
ipv6_cidrs = response.get('result', {}).get('ipv6_cidrs', [])
190-
return ipv4_cidrs, ipv6_cidrs
182+
with requests.Session() as send_request:
183+
response = send_request.get(url=_uri, headers=_headers)
184+
response_data: dict[str, dict[str, str] | list[str]] = response.json()
185+
ipv4_cidrs = response_data.get('result', {}).get('ipv4_cidrs', DEFAULT_IPV4)
186+
ipv6_cidrs = response_data.get('result', {}).get('ipv6_cidrs', [])
187+
return ipv4_cidrs, ipv6_cidrs
191188

192189
except CloudFlareAPIError:
193190
return [], []

‎src/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def create_blog_url():
2323
server_url = config_instance().SERVER_NAME
2424
scheme = "http://" if "local" in server_url else "https://"
2525
blog_url = f"{scheme}{server_url}/blog/"
26-
main_logger.info("Blog URL: {}".format(blog_url))
26+
main_logger.info("Blog URL: {}".format(blog_url[:-1]))
2727
return blog_url
2828

2929

‎src/template/dashboard/home.html

+8
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,14 @@ <h3 class="card-title"> Quora Community</h3>
458458
<li class="font-weight-bold text-info"><a href="https://eodstockmarketapi.quora.com/" target="_blank">Join our Quora Community</a></li>
459459
</ul>
460460
</div>
461+
<div class="card-body">
462+
<div class="card-header">
463+
<h3 class="card-title"> Slack Community </h3>
464+
<ul class="card-footer">
465+
<li class="font-weight-bold"><a href="https://join.slack.com/t/eod-stock-apisite/shared_invite/zt-1uelcf229-c_6QAgWFNyVfXKZr1hYYoQ" target="_blank"> Join our Slack Community</a></li>
466+
</ul>
467+
</div>
468+
</div>
461469

462470
</div>
463471
</div>

0 commit comments

Comments
 (0)