Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
328 lines (290 loc) · 14.2 KB
/
Copy pathserver.py
File metadata and controls
328 lines (290 loc) · 14.2 KB
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
import os
import re
import asyncio
import shutil
import time
import urllib.request
from collections import defaultdict
from urllib.parse import urlparse
from datetime import datetime
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Response
from fastapi.staticfiles import StaticFiles
import telnyx
from telnyx.lib.webhook_verification import verify_webhook_signature, WebhookVerificationError
from dotenv import load_dotenv
import uvicorn
import json
import logging
import ipaddress
load_dotenv()
# Simple in-memory rate limiter (100 req/min per IP)
_rate_buckets: dict = defaultdict(list)
def is_rate_limited(key: str, limit: int = 100, window: int = 60) -> bool:
now = time.monotonic()
_rate_buckets[key] = [t for t in _rate_buckets[key] if now - t < window]
if len(_rate_buckets[key]) >= limit:
return True
_rate_buckets[key].append(now)
return False
@asynccontextmanager
async def lifespan(app: FastAPI):
task = asyncio.create_task(event_handler.start_watching("Faxes/outbound"))
yield
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
# Initialize FastAPI
app = FastAPI(lifespan=lifespan)
app.mount("/static/outbound", StaticFiles(directory="Faxes/outbound"), name="static") # mount outbound faxes directory to webserver
# Determine the log level from environment variable or default to info
log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
log_level = getattr(logging, log_level_str, logging.DEBUG)
# Configure logging
logging.basicConfig(level=log_level, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def now_stamp():
return datetime.now().strftime('%Y%m%d_%H%M%S') # Using seconds for uniqueness
# Read and process whitelisted IP ranges from environment variable or use default
WHITELISTED_IP_RANGES_STR = os.getenv('WHITELISTED_IP_RANGES')
if WHITELISTED_IP_RANGES_STR is None:
logger.error("WHITELISTED_IP_RANGES environment variable is not set, using hardcoded Telnyx defaults")
WHITELISTED_IP_RANGES_STR = '["64.16.250.10/32", "192.76.120.10/32", "185.246.41.140/32", "185.246.41.141/32", "192.76.120.128/29", "192.76.120.136/29", "192.76.120.144/29", "192.76.120.160/29", "185.246.41.0/29", "185.246.41.8/29", "185.246.41.16/29", "36.255.198.128/25", "50.114.136.128/25", "50.114.144.0/21", "64.16.226.0/24", "64.16.227.0/24", "64.16.228.0/24", "64.16.229.0/24", "64.16.230.0/24", "64.16.248.0/24", "64.16.249.0/24", "103.115.244.128/25", "185.246.41.128/25"]'
try:
# Ensure the string is correctly formatted for JSON
WHITELISTED_IP_RANGES_STR = WHITELISTED_IP_RANGES_STR.strip().replace("'", '"')
ip_ranges = json.loads(WHITELISTED_IP_RANGES_STR)
WHITELISTED_IP_RANGES = []
for ip in ip_ranges:
try:
WHITELISTED_IP_RANGES.append(ipaddress.ip_network(ip))
except ValueError as e:
logger.error(f"[ERROR]:Invalid IP range '{ip}' skipped: {e}")
logger.debug(f"Parsed WHITELISTED_IP_RANGES: {WHITELISTED_IP_RANGES}")
except json.JSONDecodeError as e:
logger.debug(f"Unable to properly read whitelisted IP ranges. Are they set in environment and in proper JSON? {e}")
raise ValueError(f"Error decoding WHITELISTED_IP_RANGES: {e}")
def is_whitelisted(ip):
ip_address = ipaddress.ip_address(ip)
return any(ip_address in network for network in WHITELISTED_IP_RANGES)
LOCAL_NETWORKS = [
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("::1/128"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
ipaddress.ip_network("169.254.0.0/16"),
ipaddress.ip_network("fe80::/10"),
ipaddress.ip_network("fc00::/7"),
]
def is_local_ip(ip: str) -> bool:
try:
addr = ipaddress.ip_address(ip)
return any(addr in network for network in LOCAL_NETWORKS)
except ValueError:
return False
def secure_filename(name: str) -> str:
name = os.path.basename(name)
name = re.sub(r'[^A-Za-z0-9_.\-]', '_', name)
name = name.lstrip('.')
return name or 'file'
def safe_path(directory: str, file_name: str) -> str:
base = os.path.realpath(directory)
path = os.path.normpath(os.path.join(base, file_name))
if not path.startswith(base + os.sep):
raise ValueError(f"Unsafe file path: {file_name}")
return path
# SSRF guard for media URLs
def is_safe_media_url(url: str) -> bool:
try:
parsed = urlparse(url)
host = parsed.hostname or ''
return parsed.scheme == 'https' and (host == 'telnyx.com' or host.endswith('.telnyx.com') or host == 's3.amazonaws.com' or host.endswith('.s3.amazonaws.com'))
except Exception:
return False
# fax number validation
def is_valid_fax_number(number: str) -> bool:
return bool(re.fullmatch(r'\d{10,15}', number))
@app.middleware("http")
async def whitelist_middleware(request: Request, call_next):
direct_ip = request.client.host
if is_local_ip(direct_ip):
client_ip = request.headers.get("CF-Connecting-IP") or direct_ip
else:
client_ip = direct_ip
if not is_whitelisted(client_ip):
return Response(status_code=403, content="Forbidden")
return await call_next(request)
#Store SMS In as plain text
def store_sms(message: str, from_number: str, directory="Faxes"):
# store_sms / sanitize_and_store
file_name = f"SMS_from_{secure_filename(from_number)}_at_{now_stamp()}.txt"
os.makedirs(directory, exist_ok=True)
with open(safe_path(directory, file_name), "w") as file:
file.write(message)
class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
_url_opener = urllib.request.build_opener(_NoRedirectHandler)
#Sanitize and format Fax In File
def download_file(from_number, url, save_directory='Faxes'):
if not is_safe_media_url(url):
logger.error(f"Rejected unsafe media URL: {url}")
return None
try:
# redirects rejected; HTTPError raised on bad status
with _url_opener.open(url, timeout=30) as r:
content = r.read()
# download_file
file_name = f"Fax_{secure_filename(os.path.basename(urlparse(url).path)[:5])}_from_{secure_filename(from_number)}_at_{now_stamp()}.pdf"
os.makedirs(save_directory, exist_ok=True)
file_path = os.path.join(save_directory, file_name)
with open(file_path, "wb") as f:
f.write(content)
return file_path
except Exception as e:
logger.error(f"An error occurred while downloading the fax file: {e}")
return None
@app.get("/", include_in_schema=False)
# Block all root connections
async def root():
return Response(status_code=404)
# For uptime monitoring
@app.get("/status")
async def status():
return {"status": "ONLINE"}
@app.post("/sms")
async def handle_sms(request: Request):
if is_rate_limited(request.client.host): #Set SMS rate limit
return Response(status_code=429, content="Too Many Requests")
try:
data = await request.json()
message = data['data']['payload']['text']
from_number = data['data']['payload']['from']['phone_number']
store_sms(message, from_number)
logger.info(f"Received an SMS from {from_number} ({len(message)} chars)")
return Response(status_code=200)
except (KeyError, AttributeError, TypeError, ValueError):
logger.error("Incorrect incoming SMS data format received.")
return Response(status_code=400)
except Exception as e:
logger.error(f"An error occurred: {e}")
return Response(status_code=500)
@app.post("/telnyx-webhook")
async def inbound_message(request: Request):
if is_rate_limited(request.client.host): #Set webhook rate limit
return Response(status_code=429, content="Too Many Requests")
# verify webhook signature before processing
body = await request.body()
try:
verify_webhook_signature(body, request.headers, os.getenv("TELNYX_PUBLIC_KEY", ""))
except WebhookVerificationError as e:
logger.error(f"Webhook signature verification failed: {e}")
return Response(status_code=403, content="Forbidden")
try:
body_json = json.loads(body)
fax_id = body_json["data"]["payload"]["fax_id"]
event_type = body_json["data"]["event_type"]
direction = body_json["data"]["payload"]["direction"]
if event_type == "fax.delivered":
faxed_to = body_json["data"]["payload"]["to"]
# fax.delivered log line in inbound_message — drop the suffix entirely
logger.info(f"Fax ID {fax_id} delivered to {faxed_to}")
logger.debug(f"Received delivery confirmation for fax ID: {fax_id}")
# Call on_confirmed with the fax_id received from the webhook
event_handler.on_confirmed(faxed_to, fax_id)
elif event_type == "fax.failed":
failure_reason = body_json["data"]["payload"].get("failure_reason")
logger.error(f"Fax failed with reason: {failure_reason}")
if event_type != "fax.received" or direction != "inbound":
failure_reason = body_json["data"]["payload"].get("failure_reason")
if failure_reason:
logger.error(f"Fax failed due to: {failure_reason}")
logger.debug(f"Received fax event_type: {event_type} to {direction} fax_id: {fax_id}")
return Response(status_code=200)
to_number = body_json["data"]["payload"]["to"]
from_number = body_json["data"]["payload"]["from"]
media_url = body_json["data"]["payload"]["media_url"]
attachment = download_file(from_number, media_url)
if attachment is None:
logger.error(f"Failed to download fax with id: {fax_id} from {from_number} to {to_number}")
return Response(status_code=500)
logger.info(f"Received incoming fax with id: {fax_id} from {from_number} to {to_number}")
return Response(status_code=200)
except KeyError:
logger.error("Incorrect data format received.")
return Response(status_code=400)
except Exception as e:
logger.error(f"Error processing webhook: {str(e)}")
return Response(status_code=500)
class FaxEventHandler:
def __init__(self):
self.fax_id_to_file = {}
async def start_watching(self, path: str):
known = set(os.listdir(path)) if os.path.isdir(path) else set()
while True:
await asyncio.sleep(2)
try:
current = set(os.listdir(path)) if os.path.isdir(path) else set()
for filename in current - known:
if filename.endswith('.pdf'):
logger.debug(f"Processing fax for file: {filename}")
fax_to = os.path.splitext(filename)[0] # Extract fax number from file name
self.send_fax(os.path.join(path, filename), fax_to)
known = current
except Exception as e:
logger.error(f"Error polling outbound directory: {e}")
def send_fax(self, file_path, fax_number):
# validate fax number before sending
if not is_valid_fax_number(fax_number):
logger.error(f"Invalid fax number '{fax_number}', skipping")
return
logger.info(f"Faxing file {file_path} to {fax_number}")
file_name = os.path.basename(file_path)
media_url = f"{os.getenv('MEDIA_BASE_URL')}/outbound/{file_name}"
try:
fax_response = telnyx_client.faxes.create(
connection_id=os.getenv("TELNYX_FAX_CONNECTION_ID"),
from_=os.getenv("TELNYX_FAX_FROM_NUMBER"),
media_url=media_url,
monochrome=False,
t38_enabled=True,
to="+1" + fax_number
)
fax_id = fax_response.data.id
logger.debug(f"Sent fax with fax_id: {fax_id} to server")
self.fax_id_to_file[fax_id] = file_name # Store the mapping of fax_id to file_name
logger.debug(f"Stored mapping: {fax_id} -> {file_name}")
logger.debug(f"Fax sent successfully: {fax_response}")
except Exception as e:
logger.error(f"Failed to send fax: {str(e)}")
def on_confirmed(self, faxed_to, confirmation_number):
logger.debug(f"On confirmed file move called for confirmation number: {confirmation_number}")
# Retrieve the original file name using the fax_id
original_file_name = self.fax_id_to_file.get(confirmation_number)
if not original_file_name:
logger.error(f"No mapping found for confirmation number: {confirmation_number}")
return
new_file_name = f"Fax_{secure_filename(confirmation_number[:5])}_to_{secure_filename(faxed_to)}_at_{now_stamp()}_confirmed.pdf"
confirmations_dir = os.path.join('Faxes', 'outbound_confirmations')
try:
file_path = safe_path('Faxes/outbound', original_file_name)
os.makedirs(confirmations_dir, exist_ok=True)
new_file_path = safe_path(confirmations_dir, new_file_name)
shutil.copyfile(file_path, new_file_path) # data only; copystat fails on cross-mount volumes
os.remove(file_path)
logger.info(f"Successfully moved confirmed fax to {new_file_path}")
except Exception as e:
logger.error(f"Failed to move file for fax {confirmation_number}: {str(e)}")
if __name__ == "__main__":
telnyx_client = telnyx.Telnyx(
api_key=os.getenv("TELNYX_API_KEY"),
public_key=os.getenv("TELNYX_PUBLIC_KEY"),
)
# Set up the FaxEventHandler (watching is started by lifespan)
global event_handler
event_handler = FaxEventHandler()
# Start the FastAPI app
uvicorn.run(app, host=str(os.getenv("HOST")), port=int(os.getenv("PORT")), log_level=(os.getenv('LOG_LEVEL', 'ERROR').lower()), ssl_keyfile='certs/key.pem', ssl_certfile='certs/cert.pem', proxy_headers=False)