COSCUP-ap-demo/demo/utils/checker.py

57 lines
1.5 KiB
Python
Raw Normal View History

2023-06-13 08:14:28 +02:00
"""Request checker"""
2023-06-19 08:34:03 +02:00
import json
2023-06-13 08:11:29 +02:00
from flask import Request, abort
2023-06-19 08:34:03 +02:00
from demo.httpsig import HttpSignature, SignedData
from demo.actor import fetch_actor
2023-07-27 16:11:43 +02:00
from app import logger
2023-07-27 16:25:38 +02:00
from pprint import pformat
2023-06-13 08:11:29 +02:00
def inbox_prechecker(
request: Request,
) -> bool:
2023-06-13 08:14:28 +02:00
"""Inbox request prechecker"""
2023-07-27 16:25:38 +02:00
try:
json_payload = request.json
except json.JSONDecodeError:
abort(401, "no activity+json request!")
2023-07-27 16:11:43 +02:00
headers = request.headers
payload = request.data
2023-07-27 16:25:38 +02:00
logger.info(f"new request \n{pformat(json_payload)}\n{pformat({k: v for k, v in request.headers})}")
2023-06-13 08:11:29 +02:00
try:
parsed_signature = HttpSignature.parse_signature(
2023-07-27 16:11:43 +02:00
headers["signature"]
2023-06-13 08:11:29 +02:00
)
except KeyError:
abort(401, "Missing signature key!")
2023-06-19 08:34:03 +02:00
actor_id = request.get_json()["actor"]
actor = fetch_actor(actor_id)
try:
pub_key = actor["publicKey"]["publicKeyPem"]
2023-06-19 08:55:56 +02:00
except json.JSONDecodeError as exc:
raise ValueError from exc
except KeyError as exc:
2023-06-19 08:34:03 +02:00
print("actore gone?")
2023-06-19 08:55:56 +02:00
raise KeyError from exc
2023-06-19 08:34:03 +02:00
sigdate = SignedData(
method = request.method,
path = request.path,
signed_list = parsed_signature["headers"],
2023-07-27 16:11:43 +02:00
body_digest = HttpSignature.calculation_digest(payload),
2023-06-19 08:34:03 +02:00
headers = request.headers,
)
is_verify = HttpSignature.verify_signature(
HttpSignature.build_signature_string(sigdate),
parsed_signature["signature"],
2023-06-19 08:34:03 +02:00
pub_key,
)
return is_verify