2023-03-19 05:51:20 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
import fastapi
|
|
|
|
import json
|
|
|
|
import httpx
|
|
|
|
|
|
|
|
from loguru import logger
|
|
|
|
from app.httpsig import HttpSignature
|
|
|
|
from app.config import AP_CONTENT_TYPE, USER_AGENT
|
|
|
|
|
|
|
|
from app.database import AsyncSession
|
|
|
|
from app.database import get_db_session
|
|
|
|
from sqlalchemy import select
|
|
|
|
|
|
|
|
|
|
|
|
async def inbox_prechecker(
|
|
|
|
request : fastapi.Request,
|
|
|
|
db_session : AsyncSession = fastapi.Depends(get_db_session)
|
|
|
|
) -> bool :
|
|
|
|
"""
|
|
|
|
Check http request
|
|
|
|
"""
|
|
|
|
payload = await request.json()
|
|
|
|
|
|
|
|
try:
|
|
|
|
logger.info(f"headers={request.headers}")
|
|
|
|
logger.info(f"{payload=}")
|
|
|
|
|
|
|
|
parsec_signature = HttpSignature.parse_signature(
|
|
|
|
request.headers.get("signature")
|
|
|
|
)
|
|
|
|
except KeyError:
|
|
|
|
logger.warning("Not signature headers")
|
|
|
|
raise KeyError
|
|
|
|
|
|
|
|
try:
|
|
|
|
if request.method == "POST" and request.url.path.endswith("/inbox"):
|
|
|
|
from app import models
|
|
|
|
|
|
|
|
if (
|
|
|
|
payload["type"] == "Delete"
|
|
|
|
and payload["actor"] == payload["object"]
|
|
|
|
and not (
|
|
|
|
await db_session.scalars(
|
|
|
|
select(models.Actor).where(
|
2023-03-19 06:05:16 +01:00
|
|
|
models.Actor.ap_id == payload["actor"],
|
2023-03-19 05:51:20 +01:00
|
|
|
)
|
|
|
|
)
|
|
|
|
).one_or_none()
|
|
|
|
):
|
|
|
|
|
2023-03-19 09:43:33 +01:00
|
|
|
logger.info(f"Dropping unnecessary delete activity " +
|
|
|
|
payload["actor"])
|
2023-03-19 05:51:20 +01:00
|
|
|
raise fastapi.HTTPException(status_code=202)
|
|
|
|
except fastapi.HTTPException as http_exc:
|
|
|
|
raise http_exc
|
|
|
|
except Exception:
|
|
|
|
logger.exception("Failed to precheck delete activity")
|
|
|
|
|
|
|
|
actor_url = payload["actor"]
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
resp = await client.get(
|
|
|
|
actor_url,
|
|
|
|
headers={
|
|
|
|
"User-Agent": USER_AGENT,
|
|
|
|
"Accept": AP_CONTENT_TYPE,
|
|
|
|
},
|
|
|
|
follow_redirects=True,
|
|
|
|
)
|
|
|
|
|
|
|
|
try:
|
|
|
|
_actor = resp.json()
|
|
|
|
pubkey = _actor["publicKey"]["publicKeyPem"]
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
raise ValueError
|
|
|
|
except KeyError:
|
|
|
|
logger.warning("actor gone? ")
|
|
|
|
raise KeyError
|
|
|
|
|
|
|
|
body = await request.body()
|
|
|
|
signture_string = HttpSignature.build_signature_string(
|
|
|
|
request.method,
|
|
|
|
request.url.path,
|
|
|
|
parsec_signature["headers"],
|
|
|
|
HttpSignature.calculation_digest(body),
|
|
|
|
request.headers,
|
|
|
|
)
|
|
|
|
is_verify = HttpSignature.verify_signature(
|
|
|
|
signture_string,
|
|
|
|
parsec_signature["signature"],
|
|
|
|
pubkey)
|
|
|
|
|
|
|
|
logger.info(signture_string)
|
|
|
|
logger.info(f"verify? {is_verify}")
|
|
|
|
|
|
|
|
return is_verify
|