From 94b4eb08a2867a0c0a64187766cb327504ebfa43 Mon Sep 17 00:00:00 2001 From: gdm85 Date: Mon, 18 Apr 2022 21:06:44 +0200 Subject: [PATCH] Return 401 when token is invalid (#714) In some rare instances (a race condition perhaps?) a `cryptography.fernet.InvalidToken` exception is thrown resulting in a broken connection. This change gracefully returns a 401 error instead. --- app/routes.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/app/routes.py b/app/routes.py index b804602..fde13fe 100644 --- a/app/routes.py +++ b/app/routes.py @@ -28,7 +28,8 @@ from flask import jsonify, make_response, request, redirect, render_template, \ send_file, session, url_for, g from requests import exceptions, get from requests.models import PreparedRequest -from cryptography.fernet import Fernet +from cryptography.fernet import Fernet, InvalidToken +from cryptography.exceptions import InvalidSignature # Load DDG bang json files only on init bang_json = json.load(open(app.config['BANG_FILE'])) or {} @@ -460,8 +461,14 @@ def imgres(): def element(): element_url = src_url = request.args.get('url') if element_url.startswith('gAAAAA'): - cipher_suite = Fernet(g.session_key) - src_url = cipher_suite.decrypt(element_url.encode()).decode() + try: + cipher_suite = Fernet(g.session_key) + src_url = cipher_suite.decrypt(element_url.encode()).decode() + print(src_url) + except (InvalidSignature, InvalidToken) as e: + return render_template( + 'error.html', + error_message=str(e)), 401 src_type = request.args.get('type')