From ae7339928c621d80c18acc036e5b101ce1f9ae49 Mon Sep 17 00:00:00 2001 From: Adam Kelly Date: Fri, 22 May 2020 13:53:56 +0100 Subject: [PATCH] Move signature checking logic out of shared_inbox. --- fedireads/incoming.py | 42 ++++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/fedireads/incoming.py b/fedireads/incoming.py index d20258927..ceefebc97 100644 --- a/fedireads/incoming.py +++ b/fedireads/incoming.py @@ -44,24 +44,7 @@ def shared_inbox(request): if not activity.get('object'): return HttpResponseBadRequest() - try: - signature = Signature.parse(request) - - key_actor = urldefrag(signature.key_id).url - if key_actor != activity.get('actor'): - raise ValueError("Wrong actor created signature.") - - remote_user = get_or_create_remote_user(key_actor) - - try: - signature.verify(remote_user.public_key, request) - except ValueError: - old_key = remote_user.public_key - refresh_remote_user(remote_user) - if remote_user.public_key == old_key: - raise # Key unchanged. - signature.verify(remote_user.public_key, request) - except (ValueError, requests.exceptions.HTTPError): + if not has_valid_signature(request, activity): return HttpResponse(status=401) handlers = { @@ -96,6 +79,29 @@ def shared_inbox(request): return HttpResponse() +def has_valid_signature(request, activity): + try: + signature = Signature.parse(request) + + key_actor = urldefrag(signature.key_id).url + if key_actor != activity.get('actor'): + raise ValueError("Wrong actor created signature.") + + remote_user = get_or_create_remote_user(key_actor) + + try: + signature.verify(remote_user.public_key, request) + except ValueError: + old_key = remote_user.public_key + refresh_remote_user(remote_user) + if remote_user.public_key == old_key: + raise # Key unchanged. + signature.verify(remote_user.public_key, request) + except (ValueError, requests.exceptions.HTTPError): + return False + return True + + @app.task def handle_follow(activity): ''' someone wants to follow a local user '''