2022-11-06 20:48:04 +00:00
|
|
|
import base64
|
2022-11-07 04:30:07 +00:00
|
|
|
import json
|
2022-11-11 06:42:43 +00:00
|
|
|
from typing import TYPE_CHECKING, Dict, List, Literal, TypedDict
|
2022-11-07 04:30:07 +00:00
|
|
|
from urllib.parse import urlparse
|
2022-11-06 20:48:04 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
import httpx
|
2022-11-06 20:48:04 +00:00
|
|
|
from cryptography.hazmat.primitives import hashes
|
|
|
|
from django.http import HttpRequest
|
2022-11-07 04:30:07 +00:00
|
|
|
from django.utils.http import http_date
|
|
|
|
|
2022-11-11 06:42:43 +00:00
|
|
|
# Prevent a circular import
|
|
|
|
if TYPE_CHECKING:
|
|
|
|
from users.models import Identity
|
2022-11-06 20:48:04 +00:00
|
|
|
|
|
|
|
|
|
|
|
class HttpSignature:
|
|
|
|
"""
|
|
|
|
Allows for calculation and verification of HTTP signatures
|
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def calculate_digest(cls, data, algorithm="sha-256") -> str:
|
|
|
|
"""
|
|
|
|
Calculates the digest header value for a given HTTP body
|
|
|
|
"""
|
|
|
|
if algorithm == "sha-256":
|
|
|
|
digest = hashes.Hash(hashes.SHA256())
|
|
|
|
digest.update(data)
|
|
|
|
return "SHA-256=" + base64.b64encode(digest.finalize()).decode("ascii")
|
|
|
|
else:
|
|
|
|
raise ValueError(f"Unknown digest algorithm {algorithm}")
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def headers_from_request(cls, request: HttpRequest, header_names: List[str]) -> str:
|
|
|
|
"""
|
2022-11-07 04:30:07 +00:00
|
|
|
Creates the to-be-signed header payload from a Django request
|
|
|
|
"""
|
2022-11-06 20:48:04 +00:00
|
|
|
headers = {}
|
|
|
|
for header_name in header_names:
|
|
|
|
if header_name == "(request-target)":
|
|
|
|
value = f"post {request.path}"
|
|
|
|
elif header_name == "content-type":
|
|
|
|
value = request.META["CONTENT_TYPE"]
|
|
|
|
else:
|
|
|
|
value = request.META[f"HTTP_{header_name.upper()}"]
|
|
|
|
headers[header_name] = value
|
|
|
|
return "\n".join(f"{name.lower()}: {value}" for name, value in headers.items())
|
|
|
|
|
|
|
|
@classmethod
|
2022-11-07 04:30:07 +00:00
|
|
|
def parse_signature(cls, signature: str) -> "SignatureDetails":
|
2022-11-06 21:14:08 +00:00
|
|
|
bits = {}
|
2022-11-06 20:48:04 +00:00
|
|
|
for item in signature.split(","):
|
|
|
|
name, value = item.split("=", 1)
|
|
|
|
value = value.strip('"')
|
2022-11-06 21:14:08 +00:00
|
|
|
bits[name.lower()] = value
|
|
|
|
signature_details: SignatureDetails = {
|
|
|
|
"headers": bits["headers"].split(),
|
|
|
|
"signature": base64.b64decode(bits["signature"]),
|
|
|
|
"algorithm": bits["algorithm"],
|
|
|
|
"keyid": bits["keyid"],
|
|
|
|
}
|
2022-11-06 20:48:04 +00:00
|
|
|
return signature_details
|
2022-11-06 21:14:08 +00:00
|
|
|
|
2022-11-07 04:30:07 +00:00
|
|
|
@classmethod
|
|
|
|
def compile_signature(cls, details: "SignatureDetails") -> str:
|
|
|
|
value = f'keyId="{details["keyid"]}",headers="'
|
|
|
|
value += " ".join(h.lower() for h in details["headers"])
|
|
|
|
value += '",signature="'
|
|
|
|
value += base64.b64encode(details["signature"]).decode("ascii")
|
|
|
|
value += f'",algorithm="{details["algorithm"]}"'
|
|
|
|
return value
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
async def signed_request(
|
|
|
|
self,
|
|
|
|
uri: str,
|
|
|
|
body: Dict,
|
2022-11-11 06:42:43 +00:00
|
|
|
identity: "Identity",
|
2022-11-07 04:30:07 +00:00
|
|
|
content_type: str = "application/json",
|
|
|
|
method: Literal["post"] = "post",
|
|
|
|
):
|
|
|
|
"""
|
|
|
|
Performs an async request to the given path, with a document, signed
|
|
|
|
as an identity.
|
|
|
|
"""
|
|
|
|
uri_parts = urlparse(uri)
|
|
|
|
date_string = http_date()
|
|
|
|
body_bytes = json.dumps(body).encode("utf8")
|
|
|
|
headers = {
|
|
|
|
"(request-target)": f"{method} {uri_parts.path}",
|
|
|
|
"Host": uri_parts.hostname,
|
|
|
|
"Date": date_string,
|
|
|
|
"Digest": self.calculate_digest(body_bytes),
|
|
|
|
"Content-Type": content_type,
|
|
|
|
}
|
|
|
|
signed_string = "\n".join(
|
|
|
|
f"{name.lower()}: {value}" for name, value in headers.items()
|
|
|
|
)
|
|
|
|
headers["Signature"] = self.compile_signature(
|
|
|
|
{
|
2022-11-07 07:19:00 +00:00
|
|
|
"keyid": identity.key_id,
|
2022-11-07 04:30:07 +00:00
|
|
|
"headers": list(headers.keys()),
|
|
|
|
"signature": identity.sign(signed_string),
|
|
|
|
"algorithm": "rsa-sha256",
|
|
|
|
}
|
|
|
|
)
|
|
|
|
del headers["(request-target)"]
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
print(f"Calling {method} {uri}")
|
2022-11-11 06:42:43 +00:00
|
|
|
response = await client.request(
|
2022-11-07 04:30:07 +00:00
|
|
|
method,
|
|
|
|
uri,
|
|
|
|
headers=headers,
|
|
|
|
content=body_bytes,
|
|
|
|
)
|
2022-11-11 06:42:43 +00:00
|
|
|
if response.status_code >= 400:
|
|
|
|
raise ValueError(
|
|
|
|
f"Request error: {response.status_code} {response.content}"
|
|
|
|
)
|
|
|
|
return response
|
2022-11-07 04:30:07 +00:00
|
|
|
|
2022-11-06 21:14:08 +00:00
|
|
|
|
|
|
|
class SignatureDetails(TypedDict):
|
|
|
|
algorithm: str
|
|
|
|
headers: List[str]
|
|
|
|
signature: bytes
|
|
|
|
keyid: str
|