Use load_public_key_and_check when adding new PGP key

This commit is contained in:
Son NK 2020-11-26 10:27:23 +01:00
parent 5b9eb8686a
commit adfbfe8026
3 changed files with 14 additions and 8 deletions

View File

@ -4,7 +4,7 @@ from flask_login import login_required, current_user
from app.dashboard.base import dashboard_bp
from app.extensions import db
from app.models import Contact
from app.pgp_utils import PGPException, load_public_key
from app.pgp_utils import PGPException, load_public_key, load_public_key_and_check
@dashboard_bp.route("/contact/<int:contact_id>/", methods=["GET", "POST"])
@ -28,7 +28,9 @@ def contact_detail_route(contact_id):
contact.pgp_public_key = request.form.get("pgp")
try:
contact.pgp_finger_print = load_public_key(contact.pgp_public_key)
contact.pgp_finger_print = load_public_key_and_check(
contact.pgp_public_key
)
except PGPException:
flash("Cannot add the public key, please verify it", "error")
else:

View File

@ -16,7 +16,7 @@ from app.extensions import db
from app.log import LOG
from app.models import Alias, AuthorizedAddress
from app.models import Mailbox
from app.pgp_utils import PGPException, load_public_key
from app.pgp_utils import PGPException, load_public_key, load_public_key_and_check
class ChangeEmailForm(FlaskForm):
@ -133,7 +133,9 @@ def mailbox_detail_route(mailbox_id):
mailbox.pgp_public_key = request.form.get("pgp")
try:
mailbox.pgp_finger_print = load_public_key(mailbox.pgp_public_key)
mailbox.pgp_finger_print = load_public_key_and_check(
mailbox.pgp_public_key
)
except PGPException:
flash("Cannot add the public key, please verify it", "error")
else:

View File

@ -33,18 +33,20 @@ def load_public_key_and_check(public_key: str) -> str:
If the encryption fails, remove the newly created fingerprint.
Return the fingerprint
"""
import_result = gpg.import_keys(public_key)
try:
import_result = gpg.import_keys(public_key)
fingerprint = import_result.fingerprints[0]
except Exception as e:
raise PGPException("Cannot load key") from e
else:
dummy_data = BytesIO(b"test")
r = gpg.encrypt_file(dummy_data, fingerprint)
if not r.ok:
try:
r = encrypt_file(dummy_data, fingerprint)
except Exception as e:
LOG.exception("Cannot encrypt using the imported key")
# remove the fingerprint
gpg.delete_keys([fingerprint])
raise PGPException("Encryption fails with the key")
raise PGPException("Encryption fails with the key") from e
return fingerprint