"""HTTP Message Signatures for ActivityPub federation.
Supports:
- draft-cavage-http-signatures-12 (Mastodon, Misskey, Lemmy standard).
- RFC 9421 HTTP Message Signatures compatibility.
- Ed25519 and RSA-SHA256 signing and verification.
- In-band Digest validation (SHA-256).
"""
from __future__ import annotations
import base64
import email.utils
import hashlib
import re
import time
import urllib.parse
from typing import Any, Mapping, Optional, Sequence
from ..conformance.errors import FleetmeshError
__all__ = [
'HttpSignatureError',
'compute_digest',
'parse_signature_header',
'sign_http_request',
'verify_http_signature',
]
_SIG_PARAM_RE = re.compile(r'([a-zA-Z0-9]+)="([^"]*)"')
[docs]class HttpSignatureError(FleetmeshError):
"""Base error for HTTP Message Signature failures."""
[docs]def compute_digest(body: bytes) -> str:
"""Compute standard RFC 3230 / draft-cavage Digest header value for a request body."""
h = hashlib.sha256(body).digest()
b64 = base64.b64encode(h).decode('ascii')
return f"SHA-256={b64}"
[docs]def sign_http_request(
method: str,
url: str,
headers: Mapping[str, str],
body: bytes,
private_key: Any,
key_id: str,
algorithm: Optional[str] = None,
sign_headers: Sequence[str] = ("(request-target)", "host", "date", "digest"),
) -> dict[str, str]:
"""Sign an outbound HTTP request, returning updated headers with Signature, Date, and Digest."""
out_headers = dict(headers)
method_lower = method.lower()
parsed_url = urllib.parse.urlparse(url)
path = parsed_url.path or "/"
if parsed_url.query:
path += f"?{parsed_url.query}"
host = parsed_url.netloc
# Ensure Date header
if 'date' not in [k.lower() for k in out_headers]:
out_headers['Date'] = email.utils.formatdate(usegmt=True)
# Ensure Host header
if host and 'host' not in [k.lower() for k in out_headers]:
out_headers['Host'] = host
# Ensure Digest header for non-empty or POST/PUT requests
if body is not None and 'digest' not in [k.lower() for k in out_headers]:
out_headers['Digest'] = compute_digest(body)
# Build signature string
sig_lines = []
# Lowercase map for header lookup
hdr_lower = {k.lower(): v for k, v in out_headers.items()}
for h_name in sign_headers:
norm_name = h_name.lower()
if norm_name == "(request-target)":
sig_lines.append(f"(request-target): {method_lower} {path}")
else:
if norm_name not in hdr_lower:
raise HttpSignatureError(f"header {h_name} required for signing is missing")
sig_lines.append(f"{norm_name}: {hdr_lower[norm_name]}")
sig_string = "\n".join(sig_lines)
sig_bytes = sig_string.encode('utf-8')
# Sign with private key
raw_sig: bytes = b""
try:
from cryptography.hazmat.primitives.asymmetric import ed25519, padding, rsa
from cryptography.hazmat.primitives import hashes
if isinstance(private_key, ed25519.Ed25519PrivateKey):
raw_sig = private_key.sign(sig_bytes)
alg_str = "ed25519"
elif isinstance(private_key, rsa.RSAPrivateKey):
raw_sig = private_key.sign(
sig_bytes,
padding.PKCS1v15(),
hashes.SHA256(),
)
alg_str = "rsa-sha256"
elif isinstance(private_key, (bytes, bytearray)) and len(private_key) == 32:
# Raw Ed25519 seed
ed_key = ed25519.Ed25519PrivateKey.from_private_bytes(bytes(private_key))
raw_sig = ed_key.sign(sig_bytes)
alg_str = "ed25519"
else:
raise HttpSignatureError(f"unsupported private key type: {type(private_key)}")
# The algorithm is the key's. This parameter used to be accepted and
# ignored, so a caller asking for rsa-sha256 with an Ed25519 key got
# an Ed25519 signature labelled ed25519 and never knew (audit
# 2026-10-15, B12). Named, it must agree with the key.
if algorithm is not None and algorithm != alg_str:
raise HttpSignatureError(f"algorithm {algorithm!r} does not match the key, which signs {alg_str}")
except ImportError:
raise HttpSignatureError("cryptography library required for HTTP message signing")
b64_sig = base64.b64encode(raw_sig).decode('ascii')
header_list_str = " ".join(sign_headers)
sig_header = (
f'keyId="{key_id}",'
f'algorithm="{alg_str}",'
f'headers="{header_list_str}",'
f'signature="{b64_sig}"'
)
out_headers['Signature'] = sig_header
return out_headers
[docs]def verify_http_signature(
method: str,
path: str,
headers: Mapping[str, str],
body: bytes,
public_key: Any,
tolerance_seconds: float = 300.0,
) -> bool:
"""Verify an inbound HTTP message signature against public key."""
# Find Signature header
sig_val: Optional[str] = None
for k, v in headers.items():
if k.lower() == 'signature':
sig_val = v
break
if not sig_val:
return False
parsed_sig = parse_signature_header(sig_val)
if 'signature' not in parsed_sig or 'headers' not in parsed_sig:
return False
header_names = parsed_sig['headers'].split()
header_names_lower = [h.lower() for h in header_names]
if '(request-target)' not in header_names_lower:
return False
if body and 'digest' not in header_names_lower:
return False
b64_sig = parsed_sig['signature']
try:
raw_sig = base64.b64decode(b64_sig)
except Exception:
return False
# Lowercase lookup
hdr_lower = {k.lower(): v for k, v in headers.items()}
# 1. Digest check if digest was signed
if 'digest' in header_names_lower:
if 'digest' not in hdr_lower:
return False
expected_digest = compute_digest(body)
if hdr_lower['digest'].strip() != expected_digest:
return False
# 2. Date tolerance check if date was signed
if 'date' in header_names_lower:
if 'date' not in hdr_lower:
return False
try:
req_dt = email.utils.parsedate_to_datetime(hdr_lower['date'])
req_ts = req_dt.timestamp()
now_ts = time.time()
if abs(now_ts - req_ts) > tolerance_seconds:
return False
except Exception:
return False
# 3. Build signature string
method_lower = method.lower()
clean_path = path if path.startswith('/') else '/' + path
sig_lines = []
for h_name in header_names:
norm_name = h_name.lower()
if norm_name == "(request-target)":
sig_lines.append(f"(request-target): {method_lower} {clean_path}")
else:
if norm_name not in hdr_lower:
return False
sig_lines.append(f"{norm_name}: {hdr_lower[norm_name]}")
sig_string = "\n".join(sig_lines)
sig_bytes = sig_string.encode('utf-8')
# 4. Verify signature with public key
try:
from cryptography.hazmat.primitives.asymmetric import ed25519, padding, rsa
from cryptography.hazmat.primitives import hashes, serialization
pub = public_key
if isinstance(pub, str):
# Parse PEM
pub = serialization.load_pem_public_key(pub.encode('utf-8'))
elif isinstance(pub, (bytes, bytearray)):
if len(pub) == 32:
pub = ed25519.Ed25519PublicKey.from_public_bytes(bytes(pub))
else:
pub = serialization.load_pem_public_key(bytes(pub))
if isinstance(pub, ed25519.Ed25519PublicKey):
pub.verify(raw_sig, sig_bytes)
return True
elif isinstance(pub, rsa.RSAPublicKey):
pub.verify(
raw_sig,
sig_bytes,
padding.PKCS1v15(),
hashes.SHA256(),
)
return True
return False
except Exception:
return False