Add self-contained relay deployment project and operational guidance
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
"""Device registration with key possession proof; Work binding is separate."""
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
import httpx
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from .common import no_cache, peer, rate_limit
|
||||
from .crypto import verified, sign, raw_public, verify_device, fingerprint
|
||||
from .web_session import digest
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
def validate_enrollment(body):
|
||||
try:
|
||||
key = serialization.load_pem_public_key(body.public_key.encode())
|
||||
if not isinstance(key, Ed25519PublicKey):
|
||||
raise ValueError()
|
||||
proof = verified(body.proof, key)
|
||||
if (proof["host_id"] != body.host_id or proof["purpose"] != "device-enroll-v1"
|
||||
or abs(time.time() - proof["ts"]) > 90 or len(proof["nonce"]) != 32):
|
||||
raise ValueError()
|
||||
return key
|
||||
except Exception:
|
||||
raise HTTPException(403, "invalid enrollment proof") from None
|
||||
|
||||
|
||||
async def request_certificate(settings, body):
|
||||
async with httpx.AsyncClient(trust_env=False, timeout=15, follow_redirects=False) as http:
|
||||
response = await http.post(settings.enrollment_signer_url.rstrip("/") + "/issue",
|
||||
headers={"X-Internal-Secret": settings.internal_secret},
|
||||
json=body.model_dump())
|
||||
response.raise_for_status()
|
||||
return response.json()["cert"]
|
||||
|
||||
|
||||
class EnrollmentRequest(BaseModel):
|
||||
host_id: str = Field(pattern=r"^[a-f0-9]{32}$")
|
||||
public_key: str = Field(max_length=1024)
|
||||
proof: dict
|
||||
|
||||
|
||||
class EnrollmentApproval(BaseModel):
|
||||
cert: str = Field(max_length=10000)
|
||||
|
||||
|
||||
def enrollment_router(settings, redis, store, signer, admin):
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/device/register")
|
||||
async def automatic_registration(body: EnrollmentRequest, request: Request):
|
||||
# No human approval: eligibility follows intranet access plus Work app scope.
|
||||
# Proof/TLS/limits protect identity and resources, and do not add user approval.
|
||||
await rate_limit(redis, "auto-register-ip:" + peer(request), 120)
|
||||
key = validate_enrollment(body)
|
||||
await rate_limit(redis, "auto-register-host:" + body.host_id, 30)
|
||||
existing = store.device(body.host_id)
|
||||
|
||||
def check_existing(device):
|
||||
if device["revoked"]:
|
||||
raise HTTPException(403, "device revoked")
|
||||
try:
|
||||
registered = verify_device(device["cert"], settings.ca_cert.read_bytes(), body.host_id)
|
||||
if raw_public(registered) != raw_public(key):
|
||||
raise ValueError()
|
||||
except Exception:
|
||||
raise HTTPException(409, "existing device identity mismatch or certificate expired") from None
|
||||
return device["cert"]
|
||||
|
||||
if existing:
|
||||
cert = check_existing(existing)
|
||||
else:
|
||||
if not settings.enrollment_signer_url:
|
||||
raise HTTPException(503, "automatic registration is not enabled; update ECS first")
|
||||
if store.db.execute("SELECT COUNT(*) AS total FROM devices").fetchone()["total"] >= settings.max_devices:
|
||||
raise HTTPException(503, "device capacity reached")
|
||||
await rate_limit(redis, "auto-register-total", settings.max_pending, 3600)
|
||||
try:
|
||||
cert = await request_certificate(settings, body)
|
||||
issued = verify_device(cert, settings.ca_cert.read_bytes(), body.host_id)
|
||||
if raw_public(issued) != raw_public(key):
|
||||
raise ValueError()
|
||||
except Exception:
|
||||
raise HTTPException(503, "certificate issuer unavailable or invalid response") from None
|
||||
from .store import INTEGRITY_ERRORS
|
||||
try:
|
||||
store.add_device(body.host_id, cert, fingerprint(cert))
|
||||
except INTEGRITY_ERRORS:
|
||||
# A retry/concurrent request must return the original certificate.
|
||||
cert = check_existing(store.device(body.host_id))
|
||||
store.audit("device", "automatic_registration", body.host_id, "success")
|
||||
await redis.set("hn:device:" + body.host_id, fingerprint(cert))
|
||||
return no_cache(JSONResponse(sign({"status": "registered", "host_id": body.host_id,
|
||||
"cert": cert}, signer), status_code=201 if not existing else 200))
|
||||
|
||||
@router.post("/device/enroll")
|
||||
async def request_enrollment(body: EnrollmentRequest, request: Request):
|
||||
await rate_limit(redis, "enroll-ip:" + peer(request), 10)
|
||||
validate_enrollment(body)
|
||||
await rate_limit(redis, "enroll-host:" + body.host_id, 3, 3600)
|
||||
if store.device(body.host_id):
|
||||
raise HTTPException(409, "device already registered; recover its original certificate")
|
||||
# Global rolling capacity bound; prevents anonymous request-table exhaustion.
|
||||
await rate_limit(redis, "enroll-global", settings.max_pending, 1800)
|
||||
identifier, claim_secret = secrets.token_hex(16), secrets.token_urlsafe(32)
|
||||
record = {"host_id": body.host_id, "public_key": body.public_key,
|
||||
"claim_hash": digest(claim_secret), "created": time.time(), "status": "pending"}
|
||||
await redis.set("hn:enroll:" + identifier, json.dumps(record), ex=1800)
|
||||
return no_cache(JSONResponse(sign({"request_id": identifier, "claim_secret": claim_secret,
|
||||
"host_id": body.host_id, "expires_in": 1800}, signer), status_code=201))
|
||||
|
||||
@router.get("/device/enroll/{identifier}")
|
||||
async def claim(identifier: str, request: Request):
|
||||
await rate_limit(redis, "enroll-poll:" + peer(request), 60)
|
||||
data = await redis.get("hn:enroll:" + identifier)
|
||||
if not data:
|
||||
raise HTTPException(404, "request expired")
|
||||
record = json.loads(data)
|
||||
import hmac
|
||||
if not hmac.compare_digest(record["claim_hash"], digest(request.headers.get("X-Enrollment-Secret", ""))):
|
||||
raise HTTPException(404, "request unavailable")
|
||||
if record["status"] == "pending":
|
||||
return no_cache(JSONResponse({"status": "pending"}, status_code=202))
|
||||
device = store.device(record["host_id"])
|
||||
if not device or device["revoked"]:
|
||||
raise HTTPException(403, "device unavailable")
|
||||
# Recoverable for its original claimant for the request TTL; public certificate only.
|
||||
return no_cache(JSONResponse(sign({"status": "approved", "host_id": record["host_id"],
|
||||
"request_id": identifier, "cert": device["cert"]}, signer)))
|
||||
|
||||
@router.get("/admin/enrollments/{identifier}")
|
||||
async def inspect(identifier: str, request: Request):
|
||||
admin(request)
|
||||
encoded = await redis.get("hn:enroll:" + identifier)
|
||||
if not encoded:
|
||||
raise HTTPException(404, "request expired")
|
||||
record = json.loads(encoded)
|
||||
return {k: v for k, v in record.items() if k != "claim_hash"}
|
||||
|
||||
@router.post("/admin/enrollments/{identifier}/approve")
|
||||
async def approve(identifier: str, body: EnrollmentApproval, request: Request):
|
||||
admin(request)
|
||||
encoded = await redis.get("hn:enroll:" + identifier)
|
||||
if not encoded:
|
||||
raise HTTPException(404, "request expired")
|
||||
record = json.loads(encoded)
|
||||
try:
|
||||
public = verify_device(body.cert, settings.ca_cert.read_bytes(), record["host_id"])
|
||||
requested = serialization.load_pem_public_key(record["public_key"].encode())
|
||||
if raw_public(public) != raw_public(requested):
|
||||
raise ValueError()
|
||||
except Exception:
|
||||
raise HTTPException(400, "certificate does not match enrollment") from None
|
||||
if store.db.execute("SELECT COUNT(*) AS total FROM devices").fetchone()["total"] >= settings.max_devices:
|
||||
raise HTTPException(503, "device capacity reached")
|
||||
fp = fingerprint(body.cert)
|
||||
existing = store.device(record["host_id"])
|
||||
if existing and (existing["revoked"] or existing["fingerprint"] != fp):
|
||||
raise HTTPException(409, "device conflict")
|
||||
if not existing:
|
||||
from .store import INTEGRITY_ERRORS
|
||||
try:
|
||||
store.add_device(record["host_id"], body.cert, fp)
|
||||
except INTEGRITY_ERRORS:
|
||||
raise HTTPException(409, "concurrent device registration") from None
|
||||
await redis.set("hn:device:" + record["host_id"], fp)
|
||||
record["status"] = "approved"
|
||||
remaining = await redis.ttl("hn:enroll:" + identifier)
|
||||
if remaining < 1:
|
||||
raise HTTPException(409, "request expired during approval")
|
||||
await redis.set("hn:enroll:" + identifier, json.dumps(record), ex=remaining)
|
||||
store.audit("admin", "enrollment_approved", record["host_id"], "success")
|
||||
return {"status": "approved", "host_id": record["host_id"]}
|
||||
|
||||
return router
|
||||
Reference in New Issue
Block a user