diff --git a/.bumpversion.toml b/.bumpversion.toml index b27017bc..bcc5d892 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.20.2+261121" +current_version = "1.21.1+261122" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/README.rst b/README.rst index 83e27bd8..2f005da9 100644 --- a/README.rst +++ b/README.rst @@ -87,6 +87,26 @@ RM_ENVIRONMENT="dev" You can read more about BaseSettings class here: https://pydantic-docs.helpmanual.io/usage/settings/ +Apple ACME enrollment +--------------------- + +The Apple profile uses ``https:///api/v1/acme/directory``, +with the hostname from the existing deployment manifest. Serve the directory +with a publicly trusted HTTPS certificate. Invite enrollment accepts ``"acme": true`` +with an OpenDefence callsign and no CSR. After operator approval, +``GET /api/v1/enrollment/status`` reports state ``3`` (awaiting ACME issuance). +Use the enrollment JWT to download the Apple configuration profile at +``GET /api/v1/enrollment/acme-profile``. The profile can be downloaded again +within 15 minutes of approval. + +The directory supports the Apple enrollment flow with ``device-attest-01``. +This pilot authorizes the order using the single-use enrollment identifier and +the ACME account key. The profile requests a hardware-bound key with Apple +attestation disabled. RMAPI validates the device CSR, signs it with the +configured client CA, and returns the certificate and chain. Revocation uses +the existing RMAPI user revocation flow. + + Backend services manifest ------------------------- Integration APIs are always https in port 4625. diff --git a/pyproject.toml b/pyproject.toml index a40b39ed..788f1422 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "rasenmaeher_api" -version = "1.20.2+261121" +version = "1.21.1+261122" description = "python-rasenmaeher-api" authors = [ { name = "Aciid", email = "703382+Aciid@users.noreply.github.com" }, diff --git a/src/rasenmaeher_api/__init__.py b/src/rasenmaeher_api/__init__.py index ad9f2f95..ef0c3f91 100644 --- a/src/rasenmaeher_api/__init__.py +++ b/src/rasenmaeher_api/__init__.py @@ -1,3 +1,3 @@ """python-rasenmaeher-api""" -__version__ = "1.20.2+261121" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.21.1+261122" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/src/rasenmaeher_api/cert/acme.py b/src/rasenmaeher_api/cert/acme.py new file mode 100644 index 00000000..732813bf --- /dev/null +++ b/src/rasenmaeher_api/cert/acme.py @@ -0,0 +1,72 @@ +"""Validation shared by the Apple ACME order and its certificate signer.""" + +import base64 +import re + +from cryptography import x509 +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + +from .usages import csr_usages + + +class ACMEError(Exception): + """An ACME problem response.""" + + def __init__(self, code: str, detail: str, status: int = 400) -> None: + super().__init__(detail) + self.code = code + self.status = status + + +def b64url(data: bytes) -> str: + """Encode an unpadded base64url value.""" + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def decode_b64url(value: str) -> bytes: + """Decode a canonical, unpadded base64url value.""" + if not re.fullmatch(r"[A-Za-z0-9_-]*", value): + raise ValueError("Invalid base64url") + data = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + if b64url(data) != value: + raise ValueError("Invalid base64url") + return data + + +def validate_device_csr(der: bytes, callsign: str, identifier: str) -> str: + """Validate the signed CSR and allow only the identity requested by the profile.""" + try: + csr = x509.load_der_x509_csr(der) + key = csr.public_key() + pem = csr.public_bytes(serialization.Encoding.PEM).decode("ascii") + if not ( + isinstance(key, ec.EllipticCurvePublicKey) + and isinstance(key.curve, ec.SECP256R1) + and isinstance(csr.signature_hash_algorithm, hashes.SHA256) + and csr.is_signature_valid + and csr.subject == x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, callsign)]) + and set(csr_usages(pem)) == {"digital signature", "client auth"} + ): + raise ValueError("CSR does not match the approved client certificate policy") + for extension in csr.extensions: + match extension.value: + case x509.KeyUsage() | x509.ExtendedKeyUsage(): + pass + case x509.BasicConstraints(ca=False, path_length=None): + pass + case x509.SubjectAlternativeName() as san: + # RFC 4043 permanentIdentifier with just the UTF8String identifierValue. + encoded = identifier.encode("ascii") + other_name = x509.OtherName( + x509.ObjectIdentifier("1.3.6.1.5.5.7.8.3"), + bytes((0x30, len(encoded) + 2, 0x0C, len(encoded))) + encoded, + ) + if list(san) != [other_name]: + raise ValueError("CSR SAN does not match the approved identifier") + case _: + raise ValueError("CSR contains an unsupported extension") + except (ValueError, UnsupportedAlgorithm, x509.DuplicateExtension, x509.UnsupportedGeneralNameType) as exc: + raise ACMEError("badCSR", "CSR does not match the approved client certificate policy") from exc + return pem diff --git a/src/rasenmaeher_api/db/acme.py b/src/rasenmaeher_api/db/acme.py new file mode 100644 index 00000000..837005ba --- /dev/null +++ b/src/rasenmaeher_api/db/acme.py @@ -0,0 +1,205 @@ +"""Persist ACME accounts, replay nonces, and the single order on each approved enrollment.""" + +import datetime +import hashlib +import logging +import secrets +import uuid +from typing import Any + +from sqlalchemy.dialects.postgresql import insert +from sqlalchemy.exc import OperationalError +from sqlmodel import Session, col, delete, select +from sqlmodel.sql.expression import SelectOfScalar + +from ..cert.acme import ACMEError, b64url, validate_device_csr +from .engine import EngineWrapper +from .enrollments import ACME_CLIENT_IDENTIFIER_KEY, ACME_ORDER_KEY, Enrollment, EnrollmentState +from .errors import BackendError, CallsignReserved +from .nonces import SeenToken +from .people import Person + +LOGGER = logging.getLogger(__name__) +NONCE_LIFETIME = datetime.timedelta(minutes=10) +NONCE_PREFIX = "acme-nonce:" +ACCOUNT_PREFIX = "acme-account:" + + +def issue_nonce() -> str: + """Mint a canonical nonce and discard expired ACME nonces, including on POST responses.""" + nonce = b64url(secrets.token_bytes(32)) + cutoff = datetime.datetime.now(datetime.UTC) - NONCE_LIFETIME + with EngineWrapper.get_session() as session: + session.exec( + delete(SeenToken).where(col(SeenToken.token).startswith(NONCE_PREFIX), col(SeenToken.created) <= cutoff) + ) + session.add(SeenToken(token=f"{NONCE_PREFIX}{nonce}")) + session.commit() + return nonce + + +def consume_nonce(nonce: str) -> None: + """Remove an unexpired nonce atomically, allowing its use just once.""" + cutoff = datetime.datetime.now(datetime.UTC) - NONCE_LIFETIME + with EngineWrapper.get_session() as session: + used = session.exec( + delete(SeenToken) + .where(col(SeenToken.token) == f"{NONCE_PREFIX}{nonce}", col(SeenToken.created) > cutoff) + .returning(col(SeenToken.pk)) + ).first() + session.commit() + if used is None: + raise ACMEError("badNonce", "Unknown, expired, or already used nonce") + + +def account_exists(account: str) -> bool: + """Check whether a public account key was registered.""" + with EngineWrapper.get_session() as session: + return ( + session.exec(select(SeenToken.pk).where(SeenToken.token == f"{ACCOUNT_PREFIX}{account}")).first() + is not None + ) + + +def register_account(account: str) -> bool: + """Register the public key once across concurrent requests.""" + with EngineWrapper.get_session() as session: + created = session.exec( + insert(SeenToken) + .values(pk=uuid.uuid4(), token=f"{ACCOUNT_PREFIX}{account}", auditmeta={}) + .on_conflict_do_nothing(index_elements=[col(SeenToken.token)]) + .returning(col(SeenToken.pk)) + ).first() + session.commit() + return created is not None + + +def order_data(enrollment: Enrollment) -> dict[str, Any]: + """Read ACME's metadata from the enrollment that owns the order.""" + data = enrollment.extra.get(ACME_ORDER_KEY) + return data if isinstance(data, dict) else {} + + +def _locked(session: Session, query: SelectOfScalar[Enrollment]) -> Enrollment | None: + # A concurrent finalization can hold the row while awaiting the signer. + # NOWAIT keeps a synchronous database call from blocking the event loop. + try: + return session.exec(query.with_for_update(nowait=True)).first() + except OperationalError as exc: + if getattr(exc.orig, "pgcode", None) != "55P03": # lock_not_available + raise + raise ACMEError("serverInternal", "Order is being updated. Retry shortly.", 503) from exc + + +def _check_approval(enrollment: Enrollment) -> None: + expires_at = enrollment.acme_authorization_expires_at + if enrollment.deleted is not None or expires_at is None or datetime.datetime.now(datetime.UTC) >= expires_at: + raise ACMEError("unauthorized", "Enrollment is no longer authorized for ACME issuance", 403) + + +def _check_order(enrollment: Enrollment | None, account: str) -> Enrollment: + if enrollment is None or order_data(enrollment).get("account") != account: + raise ACMEError("unauthorized", "Order is unavailable to this account", 403) + if enrollment.state != EnrollmentState.APPROVED or enrollment.person is None or enrollment.deleted is not None: + _check_approval(enrollment) + return enrollment + + +def new_order(identifier: str, account: str) -> Enrollment: + """Consume the enrollment identifier by binding it to exactly one account and order.""" + with EngineWrapper.get_session() as session: + enrollment = _locked( + session, + select(Enrollment).where(col(Enrollment.extra)[ACME_CLIENT_IDENTIFIER_KEY].as_string() == identifier), + ) + if enrollment is None: + raise ACMEError("rejectedIdentifier", "Identifier does not belong to an approved enrollment") + if order_data(enrollment): + return _check_order(enrollment, account) + _check_approval(enrollment) + enrollment.extra = { + **enrollment.extra, + ACME_ORDER_KEY: {"account": account, "token": secrets.token_urlsafe(32)}, + } + session.add(enrollment) + session.commit() + session.refresh(enrollment) + return enrollment + + +def list_orders(account: str) -> list[uuid.UUID]: + """List order IDs bound to this account.""" + with EngineWrapper.get_session() as session: + return list( + session.exec( + select(Enrollment.pk).where(col(Enrollment.extra)[ACME_ORDER_KEY]["account"].as_string() == account) + ) + ) + + +def get_order(order_id: uuid.UUID, account: str) -> Enrollment: + """Read an order for its owning account.""" + with EngineWrapper.get_session() as session: + return _check_order(session.get(Enrollment, order_id), account) + + +def accept_challenge(order_id: uuid.UUID, account: str) -> Enrollment: + """Record the bound account's acknowledgment in the enrollment-token pilot.""" + with EngineWrapper.get_session() as session: + enrollment = _check_order(_locked(session, select(Enrollment).where(Enrollment.pk == order_id)), account) + data = order_data(enrollment) + if "validated" not in data: + data = {**data, "validated": datetime.datetime.now(datetime.UTC).isoformat()} + enrollment.extra = {**enrollment.extra, ACME_ORDER_KEY: data} + session.add(enrollment) + session.commit() + session.refresh(enrollment) + return enrollment + + +async def finalize_order(order_id: uuid.UUID, account: str, csr_der: bytes) -> Enrollment: + """Pin the CSR before calling the signer and commit the certificate with its enrollment.""" + digest = hashlib.sha256(csr_der).hexdigest() + query = select(Enrollment).where(Enrollment.pk == order_id) + with EngineWrapper.get_session() as session: + enrollment = _check_order(_locked(session, query), account) + data = order_data(enrollment) + if "validated" not in data: + raise ACMEError("orderNotReady", "Complete the challenge before finalizing", 403) + if data.get("csr_digest", digest) != digest: + raise ACMEError("badCSR", "A different CSR was already submitted to this order") + if enrollment.person is not None: + return enrollment + csr_pem = validate_device_csr(csr_der, enrollment.callsign, enrollment.acme_client_identifier or "") + if "csr_digest" not in data: + enrollment.extra = {**enrollment.extra, ACME_ORDER_KEY: {**data, "csr_digest": digest}} + session.add(enrollment) + session.commit() + + with EngineWrapper.get_session() as session: + enrollment = _check_order(_locked(session, query), account) + if enrollment.person is not None: + return enrollment + person_extra = { + key: value + for key, value in enrollment.extra.items() + if key not in (ACME_ORDER_KEY, ACME_CLIENT_IDENTIFIER_KEY) + } + try: + async with Person.issue_cert(session, enrollment.callsign, person_extra, csr_pem) as person: + enrollment.csr = csr_pem + enrollment.person = person.pk + enrollment.state = EnrollmentState.APPROVED + session.add(enrollment) + session.commit() + except CallsignReserved as exc: + raise ACMEError("unauthorized", "Callsign is already in use", 403) from exc + except BackendError as exc: + raise ACMEError("serverInternal", "The certificate signer could not complete issuance", 503) from exc + session.refresh(enrollment) + session.refresh(person) + try: + await person.complete_provisioning() + except Exception: + LOGGER.exception("Post-issuance provisioning failed for ACME enrollment %s", order_id) + return enrollment diff --git a/src/rasenmaeher_api/db/enrollments.py b/src/rasenmaeher_api/db/enrollments.py index 795432f1..0986d307 100644 --- a/src/rasenmaeher_api/db/enrollments.py +++ b/src/rasenmaeher_api/db/enrollments.py @@ -11,8 +11,10 @@ from typing import Any from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.exc import OperationalError from sqlalchemy.sql import func -from sqlmodel import Field, select +from sqlmodel import Field, Session, select +from starlette.exceptions import HTTPException from ..rmsettings import RMSettings from ..web.api.utils.csr_utils import verify_csr @@ -24,6 +26,9 @@ LOGGER = logging.getLogger(__name__) CODE_ALPHABET = string.ascii_uppercase + string.digits CODE_MAX_ATTEMPTS = 100 +ACME_CLIENT_IDENTIFIER_KEY = "rmapi_acme_client_identifier" +ACME_ORDER_KEY = "rmapi_acme_order" +ACME_AUTHORIZATION_LIFETIME = datetime.timedelta(minutes=15) def generate_code() -> str: @@ -55,13 +60,13 @@ async def by_pk_or_invitecode(cls, inval: str | uuid.UUID, allow_deleted: bool = except ValueError: return await cls.by_invitecode(str(inval), allow_deleted) - async def create_enrollment(self, callsign: str, csr: str | None = None) -> "Enrollment": + async def create_enrollment(self, callsign: str, csr: str | None = None, *, acme: bool = False) -> "Enrollment": """Create enrollment from this pool""" if not self.active: raise PoolInactive() if self.deleted: raise Deleted("Can't create enrollments on deleted pools") - return await Enrollment.create_for_callsign(callsign, self, self.extra, csr) + return await Enrollment.create_for_callsign(callsign, self, self.extra, csr, acme=acme) async def set_active(self, state: bool) -> "EnrollmentPool": """Set active and return refreshed object""" @@ -149,6 +154,7 @@ class EnrollmentState(enum.IntEnum): PENDING = 0 APPROVED = 1 REJECTED = 2 + AWAITING_ACME = 3 class Enrollment(ORMBaseModel, table=True): @@ -174,6 +180,19 @@ class Enrollment(ORMBaseModel, table=True): ) csr: str | None = Field(default=None, nullable=True) + @property + def acme_client_identifier(self) -> str | None: + """Get the opaque identifier reserved for this device enrollment.""" + value = self.extra.get(ACME_CLIENT_IDENTIFIER_KEY) + return value if isinstance(value, str) else None + + @property + def acme_authorization_expires_at(self) -> datetime.datetime | None: + """Get the deadline for an approved ACME enrollment.""" + if self.state != EnrollmentState.AWAITING_ACME or self.decided_on is None: + return None + return self.decided_on + ACME_AUTHORIZATION_LIFETIME + @classmethod async def by_pk_or_callsign(cls, inval: str | uuid.UUID) -> "Enrollment": """Get enrollment by pk or by callsign""" @@ -184,6 +203,8 @@ async def by_pk_or_callsign(cls, inval: str | uuid.UUID) -> "Enrollment": async def approve(self, approver: Person) -> Person: """Creates the person record, their certs etc""" + if self.acme_client_identifier is not None: + raise ForbiddenOperation("ACME enrollment requires approval for a device CSR") with EngineWrapper.get_session() as session: person = await Person.create_with_cert(self.callsign, extra=self.extra, csrpem=self.csr) self.state = EnrollmentState.APPROVED @@ -195,13 +216,43 @@ async def approve(self, approver: Person) -> Person: session.refresh(self) return person + async def approve_for_acme(self, approver: Person, approvecode: str) -> bool: + """Reserve approval for ACME and start its expiry window without signing a certificate.""" + with EngineWrapper.get_session() as session: + session.add(self) + self._lock_acme(session) + if ( + self.deleted is not None + or self.state != EnrollmentState.PENDING + or self.acme_client_identifier is None + or self.approvecode != approvecode + ): + return False + self.state = EnrollmentState.AWAITING_ACME + self.decided_by = approver.pk + self.decided_on = datetime.datetime.now(datetime.UTC) + session.commit() + session.refresh(self) + return True + + def _lock_acme(self, session: Session) -> None: + # Finalization awaits the signer while holding this row. An operator request must not block the event loop. + try: + session.refresh(self, with_for_update={"nowait": True}) + except OperationalError as exc: + if getattr(exc.orig, "pgcode", None) != "55P03": # lock_not_available + raise + raise HTTPException(status_code=409, detail="ACME enrollment is being finalized. Retry shortly.") from exc + async def reject(self, decider: Person) -> None: """Reject""" with EngineWrapper.get_session() as session: + session.add(self) + if self.acme_client_identifier is not None: + self._lock_acme(session) self.state = EnrollmentState.REJECTED self.decided_by = decider.pk self.decided_on = datetime.datetime.now(datetime.UTC) - session.add(self) session.commit() session.refresh(self) @@ -254,9 +305,11 @@ async def reset_approvecode4callsign(cls, callsign: str) -> str: async def reset_approvecode(self) -> str: """Reset approvecode""" with EngineWrapper.get_session() as session: + session.add(self) + if self.acme_client_identifier is not None: + self._lock_acme(session) code = await Enrollment._generate_unused_code() self.approvecode = code - session.add(self) session.commit() return code @@ -283,18 +336,33 @@ async def create_for_callsign( pool: EnrollmentPool | None = None, extra: dict[str, Any] | None = None, csr: str | None = None, + *, + acme: bool = False, ) -> "Enrollment": """Create a new one with random code for the callsign""" if RMSettings.singleton().is_reserved_cn(callsign): raise CallsignReserved("Service CN used as callsign", detail="Callsign reserved") + if acme and csr is not None: + raise ForbiddenOperation("ACME enrollment receives its CSR from the device") if csr and not verify_csr(csr, callsign): raise CallsignReserved(detail="CSR subject or key usages not allowed for callsign") - with EngineWrapper.get_session() as session: + if acme: try: - await Enrollment.by_callsign(callsign) - raise CallsignReserved() + await Person.by_callsign(callsign, allow_deleted=True) + raise CallsignReserved(detail="Callsign already taken") except NotFound: pass + enrollment_extra = (extra or {}).copy() + enrollment_extra.pop(ACME_CLIENT_IDENTIFIER_KEY, None) + enrollment_extra.pop(ACME_ORDER_KEY, None) + if acme: + enrollment_extra[ACME_CLIENT_IDENTIFIER_KEY] = secrets.token_urlsafe(32) + with EngineWrapper.get_session() as session: + # The database's unique constraint compares exact strings. Serialize case variants too. + session.exec(select(func.pg_advisory_xact_lock(func.hashtext(func.lower(callsign))))).one() + existing = select(cls.pk).where(func.lower(cls.callsign) == func.lower(callsign)) + if session.exec(existing).first() is not None: + raise CallsignReserved(detail="Callsign already taken") code = await cls._generate_unused_code() poolpk = None if pool: @@ -303,7 +371,7 @@ async def create_for_callsign( approvecode=code, callsign=callsign, state=EnrollmentState.PENDING, - extra=extra or {}, + extra=enrollment_extra, pool=poolpk, csr=csr, ) diff --git a/src/rasenmaeher_api/db/people.py b/src/rasenmaeher_api/db/people.py index 87fd2737..dd9d6ea7 100644 --- a/src/rasenmaeher_api/db/people.py +++ b/src/rasenmaeher_api/db/people.py @@ -5,7 +5,8 @@ import logging import shutil import uuid -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, AsyncIterator +from contextlib import asynccontextmanager from pathlib import Path from typing import Any, Optional, Self @@ -18,7 +19,7 @@ from libpvarki.schemas.product import UserCRUDRequest from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.sql import func -from sqlmodel import Field, SQLModel, select +from sqlmodel import Field, Session, SQLModel, select from ..cert.backend import ReasonTypes, refresh_ocsp, revoke_pem, sign_csr, validate_reason from ..kchelpers import KCClient, KCUserData @@ -98,52 +99,59 @@ async def create_with_cert( cls, callsign: str, extra: dict[str, Any] | None = None, csrpem: str | None = None ) -> "Person": """Create the cert etc and save the person""" + with EngineWrapper.get_session() as session: + async with cls.issue_cert(session, callsign, extra, csrpem) as person: + session.commit() + session.refresh(person) + return await person.complete_provisioning() + + @classmethod + @asynccontextmanager + async def issue_cert( + cls, session: Session, callsign: str, extra: dict[str, Any] | None, csrpem: str | None + ) -> AsyncIterator["Person"]: + """Sign a certificate and let the caller commit it with related database changes.""" cnf = RMSettings.singleton() if cnf.is_reserved_cn(callsign): raise CallsignReserved("Service CN used as callsign", detail="Callsign reserved") if csrpem and not verify_csr(csrpem, callsign): raise CallsignReserved(detail="CSR subject or key usages not allowed for callsign") - try: - await Person.by_callsign(callsign) + locked = session.exec( + select(sa.func.pg_try_advisory_xact_lock(1, sa.func.hashtext(sa.func.lower(callsign)))) + ).one() + existing = select(cls.pk).where(sa.func.lower(cls.callsign) == sa.func.lower(callsign), cls.deleted == None) + if not locked or session.exec(existing).first() is not None: raise CallsignReserved() - except NotFound: - pass - with EngineWrapper.get_session() as session: - puuid = uuid.uuid4() - certspath = Path(cnf.persistent_data_dir) / "private" / "people" / str(puuid) - certspath.mkdir(parents=True) - certspath.chmod(PRIVDIR_MODE) - try: - newperson = Person(pk=puuid, callsign=callsign, certspath=str(certspath), extra=extra or {}) - session.add(newperson) - session.commit() - if csrpem: - newperson.csrfile.write_text(csrpem, encoding="utf-8") - else: - ckp = await async_create_keypair( - newperson.privkeyfile, newperson.pubkeyfile, ktype=cnf.cert_key_type - ) - csrpem = await async_create_client_csr(ckp, newperson.csrfile, newperson.certsubject) - certpem = (await sign_csr(csrpem)).replace("\\n", "\n") - newperson.certfile.write_text(certpem) - leaf = cryptography.x509.load_pem_x509_certificate(certpem.encode()) - newperson.cert_serial = str(leaf.serial_number) - session.add(newperson) - session.commit() - except Exception as exc: - LOGGER.exception("Something went wrong, doing cleanup") - shutil.rmtree(certspath) - remaining = list(certspath.rglob("*")) - LOGGER.debug(f"Remaining files: {remaining}") - session.rollback() - raise BackendError(str(exc)) from exc - # refresh object if everything went ok - session.refresh(newperson) - # Drop the DB transaction for rest of the actions - return await newperson._post_create() + puuid = uuid.uuid4() + certspath = Path(cnf.persistent_data_dir) / "private" / "people" / str(puuid) + certspath.mkdir(parents=True, mode=PRIVDIR_MODE) + try: + newperson = Person(pk=puuid, callsign=callsign, certspath=str(certspath), extra=extra or {}) + session.add(newperson) + session.flush() + if csrpem: + newperson.csrfile.write_text(csrpem, encoding="utf-8") + else: + ckp = await async_create_keypair(newperson.privkeyfile, newperson.pubkeyfile, ktype=cnf.cert_key_type) + csrpem = await async_create_client_csr(ckp, newperson.csrfile, newperson.certsubject) + certpem = (await sign_csr(csrpem)).replace("\\n", "\n") + newperson.certfile.write_text(certpem) + leaf = cryptography.x509.load_pem_x509_certificate(certpem.encode()) + newperson.cert_serial = str(leaf.serial_number) + except (Exception, asyncio.CancelledError) as exc: + shutil.rmtree(certspath) + if isinstance(exc, asyncio.CancelledError): + raise + LOGGER.exception("Certificate creation failed for %s", callsign) + raise BackendError(str(exc)) from exc + try: + yield newperson + except BaseException: + shutil.rmtree(certspath) + raise - async def _post_create(self) -> "Person": + async def complete_provisioning(self) -> "Person": """Post creation actions, in separate method for readability""" refresh = self kclient = KCClient.singleton() diff --git a/src/rasenmaeher_api/web/api/acme/__init__.py b/src/rasenmaeher_api/web/api/acme/__init__.py new file mode 100644 index 00000000..947b147a --- /dev/null +++ b/src/rasenmaeher_api/web/api/acme/__init__.py @@ -0,0 +1 @@ +"""Apple ACME certificate enrollment.""" diff --git a/src/rasenmaeher_api/web/api/acme/protocol.py b/src/rasenmaeher_api/web/api/acme/protocol.py new file mode 100644 index 00000000..430ee1a9 --- /dev/null +++ b/src/rasenmaeher_api/web/api/acme/protocol.py @@ -0,0 +1,159 @@ +"""RFC 8555 request authentication for the Apple enrollment client.""" + +import json +from collections.abc import Callable, Coroutine +from dataclasses import dataclass +from typing import Any + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, utils +from fastapi import Request, Response +from fastapi.responses import JSONResponse +from fastapi.routing import APIRoute + +from ....cert.acme import ACMEError, b64url, decode_b64url +from ....db.acme import account_exists, consume_nonce, issue_nonce +from ....rmsettings import RMSettings + +ACME_PREFIX = "/api/v1/acme" +MAX_JWS_BYTES = 32 * 1024 + + +def acme_url(path: str) -> str: + """Build the public URL from trusted deployment DNS.""" + settings = RMSettings.singleton() + settings.load_manifest() + dns = settings.kraftwerk_manifest_dict.get("dns") + if not isinstance(dns, str) or not dns: + raise ACMEError("serverInternal", "Deployment DNS is missing from the manifest", 503) + return f"https://{dns}{ACME_PREFIX}/{path}" + + +class ACMERoute(APIRoute): + """Return ACME problem documents and a fresh nonce for signed requests.""" + + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: + handler = super().get_route_handler() + + async def handle(request: Request) -> Response: + try: + response = await handler(request) + response.headers["Link"] = f'<{acme_url("directory")}>; rel="index"' + except ACMEError as exc: + response = JSONResponse( + {"type": f"urn:ietf:params:acme:error:{exc.code}", "detail": str(exc), "status": exc.status}, + status_code=exc.status, + media_type="application/problem+json", + ) + if exc.status == 503: + response.headers["Retry-After"] = "1" + response.headers["Cache-Control"] = "no-store" + if request.method == "POST": + response.headers["Replay-Nonce"] = issue_nonce() + return response + + return handle + + +@dataclass(frozen=True) +class SignedRequest: + """The verified account ID and JSON payload, or an empty POST-as-GET.""" + + account: str + payload: dict[str, Any] | None + + def json(self) -> dict[str, Any]: + """Require a JSON object for an operation that changes state.""" + if self.payload is None: + raise ACMEError("malformed", "Expected a JSON payload") + return self.payload + + def require_post_as_get(self) -> None: + """Require an empty payload for reading a private ACME resource.""" + if self.payload is not None: + raise ACMEError("malformed", "Expected an empty POST-as-GET payload") + + +def _json_object(encoded: bytes) -> dict[str, Any]: + parsed = json.loads(encoded) + if not isinstance(parsed, dict): + raise TypeError("Expected object") + return parsed + + +def _key_from_jwk(jwk: Any) -> ec.EllipticCurvePublicKey: + if not isinstance(jwk, dict) or jwk.get("kty") != "EC" or jwk.get("crv") != "P-256" or "d" in jwk: + raise ACMEError("badPublicKey", "Expected a public P-256 JWK") + x, y = decode_b64url(jwk["x"]), decode_b64url(jwk["y"]) + if len(x) != 32 or len(y) != 32: + raise ACMEError("badPublicKey", "Expected a public P-256 JWK") + return ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), b"\x04" + x + y) + + +async def _authenticate(request: Request, registration: bool = False) -> SignedRequest: + if request.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/jose+json": + raise ACMEError("malformed", "Expected application/jose+json", 415) + raw = bytearray() + async for chunk in request.stream(): + if len(raw) + len(chunk) > MAX_JWS_BYTES: + raise ACMEError("malformed", "JWS request body is too large", 413) + raw.extend(chunk) + try: + jws = _json_object(bytes(raw)) + if set(jws) != {"protected", "payload", "signature"} or not all( + isinstance(value, str) for value in jws.values() + ): + raise ValueError("Expected flattened JWS") + protected = _json_object(decode_b64url(jws["protected"])) + if protected["alg"] != "ES256": + raise ACMEError("badSignatureAlgorithm", "Use ES256") + if "crit" in protected or "b64" in protected: + raise ValueError("Unsupported JWS header") + url = acme_url(request.url.path.removeprefix(ACME_PREFIX + "/")) + if protected["url"] != url or request.url.query: + raise ACMEError("malformed", "JWS URL does not match this resource") + if registration: + if "kid" in protected: + raise ValueError("Unexpected kid") + key = _key_from_jwk(protected["jwk"]) + account = b64url(key.public_bytes(serialization.Encoding.X962, serialization.PublicFormat.CompressedPoint)) + else: + prefix = acme_url("account/") + kid = protected["kid"] + if "jwk" in protected or not isinstance(kid, str) or not kid.startswith(prefix): + raise ACMEError("accountDoesNotExist", "Unknown ACME account") + account = kid.removeprefix(prefix) + point = decode_b64url(account) + if len(point) != 33 or not account_exists(account): + raise ACMEError("accountDoesNotExist", "Unknown ACME account") + key = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), point) + signature = decode_b64url(jws["signature"]) + if len(signature) != 64: + raise ValueError("Invalid ES256 signature length") + r, s = int.from_bytes(signature[:32]), int.from_bytes(signature[32:]) + key.verify( + utils.encode_dss_signature(r, s), + f"{jws['protected']}.{jws['payload']}".encode("ascii"), + ec.ECDSA(hashes.SHA256()), + ) + nonce = protected.get("nonce") + if not isinstance(nonce, str) or len(nonce) != 43: + raise ACMEError("badNonce", "Missing or invalid replay nonce") + consume_nonce(nonce) + payload = _json_object(decode_b64url(jws["payload"])) if jws["payload"] else None + return SignedRequest(account, payload) + except InvalidSignature as exc: + raise ACMEError("unauthorized", "Invalid JWS signature", 403) from exc + except (KeyError, TypeError, ValueError, RecursionError) as exc: + raise ACMEError("malformed", "Invalid ACME JWS request") from exc + + +async def new_account_request(request: Request) -> SignedRequest: + """Verify possession of the account key supplied in the protected JWS header.""" + return await _authenticate(request, registration=True) + + +async def signed_request(request: Request) -> SignedRequest: + """Verify signature and consume a nonce for a registered account.""" + return await _authenticate(request) diff --git a/src/rasenmaeher_api/web/api/acme/views.py b/src/rasenmaeher_api/web/api/acme/views.py new file mode 100644 index 00000000..a6a20c9b --- /dev/null +++ b/src/rasenmaeher_api/web/api/acme/views.py @@ -0,0 +1,167 @@ +"""The public ACME endpoints used by the Apple configuration profile.""" + +import re +import uuid +from typing import Annotated, Any + +from fastapi import APIRouter, Depends, Response +from fastapi.responses import JSONResponse + +from ....cert.acme import ACMEError, decode_b64url +from ....db import acme +from ....db.enrollments import ACME_AUTHORIZATION_LIFETIME, Enrollment +from ....db.errors import NotFound +from ....db.people import Person +from .protocol import ACMERoute, SignedRequest, acme_url, new_account_request, signed_request + +router = APIRouter(route_class=ACMERoute) +Registration = Annotated[SignedRequest, Depends(new_account_request)] +Authenticated = Annotated[SignedRequest, Depends(signed_request)] + + +def _account_response(account: str, status: int = 200) -> JSONResponse: + url = acme_url(f"account/{account}") + return JSONResponse({"status": "valid", "orders": f"{url}/orders"}, status_code=status, headers={"Location": url}) + + +def _identifier(enrollment: Enrollment) -> dict[str, str | None]: + return {"type": "permanent-identifier", "value": enrollment.acme_client_identifier} + + +def _challenge(enrollment: Enrollment) -> dict[str, Any]: + data = acme.order_data(enrollment) + result = { + "type": "device-attest-01", + "status": "pending", + "url": acme_url(f"challenge/{enrollment.pk}"), + "token": data["token"], + } + if "validated" in data: + result.update(status="valid", validated=data["validated"]) + return result + + +def _order_response(enrollment: Enrollment, status: int = 200) -> JSONResponse: + order_id = enrollment.pk + result: dict[str, Any] = { + "status": "ready" if "validated" in acme.order_data(enrollment) else "pending", + "identifiers": [_identifier(enrollment)], + "authorizations": [acme_url(f"authorization/{order_id}")], + "finalize": acme_url(f"order/{order_id}/finalize"), + } + if enrollment.decided_on is not None: + result["expires"] = (enrollment.decided_on + ACME_AUTHORIZATION_LIFETIME).isoformat() + if enrollment.person is not None: + result.update(status="valid", certificate=acme_url(f"certificate/{order_id}")) + return JSONResponse(result, status_code=status, headers={"Location": acme_url(f"order/{order_id}")}) + + +@router.get("/directory") +async def directory() -> dict[str, str]: + """Discover the Apple pilot's supported ACME operations.""" + return {"newNonce": acme_url("new-nonce"), "newAccount": acme_url("new-account"), "newOrder": acme_url("new-order")} + + +@router.head("/new-nonce", status_code=200, response_class=Response) +@router.get("/new-nonce", status_code=204, response_class=Response) +async def new_nonce(response: Response) -> None: + """Issue the first replay nonce for an ACME request.""" + response.headers["Replay-Nonce"] = acme.issue_nonce() + + +@router.post("/new-account") +async def new_account(message: Registration) -> JSONResponse: + """Register the client's ACME public key or return its existing account.""" + payload = message.json() + if payload.get("onlyReturnExisting") is True: + if not acme.account_exists(message.account): + raise ACMEError("accountDoesNotExist", "Unknown ACME account") + return _account_response(message.account) + return _account_response(message.account, 201 if acme.register_account(message.account) else 200) + + +@router.post("/account/{account}") +async def fetch_account(account: str, message: Authenticated) -> JSONResponse: + """Retrieve the authenticated account.""" + message.require_post_as_get() + if account != message.account: + raise ACMEError("unauthorized", "Account is unavailable to this key", 403) + return _account_response(account) + + +@router.post("/account/{account}/orders") +async def account_orders(account: str, message: Authenticated) -> dict[str, list[str]]: + """List the authenticated account's orders.""" + message.require_post_as_get() + if account != message.account: + raise ACMEError("unauthorized", "Account is unavailable to this key", 403) + return {"orders": [acme_url(f"order/{order_id}") for order_id in acme.list_orders(account)]} + + +@router.post("/new-order") +async def new_order(message: Authenticated) -> JSONResponse: + """Bind the profile's permanent identifier to an approved enrollment and account.""" + payload = message.json() + identifiers = payload.get("identifiers") + if not isinstance(identifiers, list) or len(identifiers) != 1 or not isinstance(identifiers[0], dict): + raise ACMEError("malformed", "Expected one device identifier") + item = identifiers[0] + if item.get("type") != "permanent-identifier": + raise ACMEError("unsupportedIdentifier", "Use a permanent-identifier from the enrollment profile") + identifier = item.get("value") + if not isinstance(identifier, str) or not re.fullmatch(r"[A-Za-z0-9_-]{43}", identifier): + raise ACMEError("rejectedIdentifier", "Identifier does not belong to an approved enrollment") + return _order_response(acme.new_order(identifier, message.account), 201) + + +@router.post("/order/{order_id}") +async def fetch_order(order_id: uuid.UUID, message: Authenticated) -> JSONResponse: + """Return the current state of an order to its owner.""" + message.require_post_as_get() + return _order_response(acme.get_order(order_id, message.account)) + + +@router.post("/authorization/{order_id}") +async def authorization(order_id: uuid.UUID, message: Authenticated) -> dict[str, Any]: + """Return the device-identifier authorization and its challenge.""" + message.require_post_as_get() + enrollment = acme.get_order(order_id, message.account) + challenge = _challenge(enrollment) + result = {"status": challenge["status"], "identifier": _identifier(enrollment), "challenges": [challenge]} + if enrollment.decided_on is not None: + result["expires"] = (enrollment.decided_on + ACME_AUTHORIZATION_LIFETIME).isoformat() + return result + + +@router.post("/challenge/{order_id}") +async def challenge(order_id: uuid.UUID, message: Authenticated) -> dict[str, Any]: + """Acknowledge device-attest-01 using this pilot's one-time enrollment authorization.""" + if message.payload is None: + return _challenge(acme.get_order(order_id, message.account)) + if message.payload: + raise ACMEError("malformed", "This enrollment expects an empty challenge acknowledgment") + return _challenge(acme.accept_challenge(order_id, message.account)) + + +@router.post("/order/{order_id}/finalize") +async def finalize(order_id: uuid.UUID, message: Authenticated) -> JSONResponse: + """Validate the CSR and issue the client certificate through RMAPI's signer.""" + try: + csr = decode_b64url(message.json()["csr"]) + except (KeyError, TypeError, ValueError) as exc: + raise ACMEError("badCSR", "Expected a base64url-encoded DER CSR") from exc + return _order_response(await acme.finalize_order(order_id, message.account, csr)) + + +@router.post("/certificate/{order_id}") +async def certificate(order_id: uuid.UUID, message: Authenticated) -> Response: + """Return the persisted leaf and issuing chain to the owning account.""" + message.require_post_as_get() + enrollment = acme.get_order(order_id, message.account) + if enrollment.person is None: + raise ACMEError("orderNotReady", "Certificate has not yet issued", 403) + try: + person = await Person.by_pk(enrollment.person) + except NotFound as exc: + raise ACMEError("unauthorized", "Certificate is unavailable", 403) from exc + return Response(person.get_cert_pem(), media_type="application/pem-certificate-chain") diff --git a/src/rasenmaeher_api/web/api/enrollment/schema.py b/src/rasenmaeher_api/web/api/enrollment/schema.py index b1fd2d91..03f4b020 100644 --- a/src/rasenmaeher_api/web/api/enrollment/schema.py +++ b/src/rasenmaeher_api/web/api/enrollment/schema.py @@ -1,8 +1,9 @@ """Schema for enrollment.""" -from typing import Any +import re +from typing import Any, Self -from pydantic import BaseModel, ConfigDict, Field +from pydantic import BaseModel, ConfigDict, Field, model_validator class EnrollmentGenVerifiOut(BaseModel): @@ -418,6 +419,14 @@ class EnrollmentInviteCodeEnrollIn(BaseModel): invite_code: str callsign: str csr: str | None = Field(description="CSR for mTLS key in PEM format", default=None) + acme: bool = Field(description="Use an Apple ACME profile to request the certificate after approval", default=False) + + @model_validator(mode="after") + def validate_acme(self) -> Self: + """Apple ACME enrollment starts with an OpenDefence callsign and no CSR.""" + if self.acme and (self.csr is not None or not re.fullmatch(r"[a-z0-9]{3,30}", self.callsign)): + raise ValueError("ACME enrollment requires a lowercase alphanumeric callsign of 3–30 characters and no CSR") + return self class EnrollmentInviteCodeDeleteIn(BaseModel): diff --git a/src/rasenmaeher_api/web/api/enrollment/views.py b/src/rasenmaeher_api/web/api/enrollment/views.py index 2927fdcb..e359cbc3 100644 --- a/src/rasenmaeher_api/web/api/enrollment/views.py +++ b/src/rasenmaeher_api/web/api/enrollment/views.py @@ -1,17 +1,23 @@ """Enrollment API views.""" +import datetime import logging +import plistlib import uuid from typing import Any +from cryptography.x509.oid import ExtendedKeyUsageOID from fastapi import APIRouter, Body, Depends, HTTPException, Request, Response from libpvarki.schemas.generic import OperationResultResponse from multikeyjwt import Issuer from multikeyjwt import config as jwtconfig +from ....cert.acme import ACMEError from ....db import Enrollment, EnrollmentPool, Person from ....db.errors import CallsignReserved, NotFound from ....rmsettings import RMSettings +from ..acme.protocol import acme_url +from ..middleware.datatypes import MTLSorJWTPayload, MTLSorJWTPayloadType from ..middleware.mtls import MTLSorJWT from ..middleware.user import ValidUser from ..utils.auditcontext import build_audit_extra @@ -161,6 +167,71 @@ async def request_enrolment_status( return EnrollmentStatusOut(callsign="", status=-1) +@ENROLLMENT_ROUTER.get( + "/acme-profile", + response_class=Response, + responses={ + 200: {"content": {"application/x-apple-aspen-config": {"schema": {"type": "string", "format": "binary"}}}} + }, +) +async def get_acme_profile(request: Request) -> Response: + """Download the Apple configuration profile for an approved ACME enrollment.""" + settings = RMSettings.singleton() + + auth: MTLSorJWTPayload = request.state.mtls_or_jwt + enrollment_id = auth.payload.get("enrollment_id") + if auth.type != MTLSorJWTPayloadType.JWT or not auth.userid or not enrollment_id: + raise HTTPException(status_code=403, detail="Enrollment JWT required") + enrollment = await Enrollment.by_callsign(auth.userid) + if enrollment_id != str(enrollment.pk): + raise HTTPException(status_code=403, detail="Enrollment JWT does not match") + + client_identifier = enrollment.acme_client_identifier + expires_at = enrollment.acme_authorization_expires_at + if client_identifier is None or expires_at is None: + raise HTTPException(status_code=409, detail="Enrollment is not awaiting ACME issuance") + if datetime.datetime.now(datetime.UTC) >= expires_at: + raise HTTPException(status_code=410, detail="ACME enrollment authorization expired") + + try: + directory_url = acme_url("directory") + except ACMEError as exc: + raise HTTPException(status_code=exc.status, detail=str(exc)) from exc + profile_id = f"fi.pvarki.rasenmaeher.acme.{enrollment.pk}" + profile = { + "PayloadType": "Configuration", + "PayloadVersion": 1, + "PayloadIdentifier": profile_id, + "PayloadUUID": str(enrollment.pk), + "PayloadDisplayName": f"{settings.deployment_name} client certificate", + "PayloadContent": [ + { + "PayloadType": "com.apple.security.acme", + "PayloadVersion": 1, + "PayloadIdentifier": f"{profile_id}.identity", + "PayloadUUID": str(uuid.uuid5(enrollment.pk, "acme-identity")), + "DirectoryURL": directory_url, + "ClientIdentifier": client_identifier, + "Subject": [[["CN", enrollment.callsign]]], + "KeyType": "ECSECPrimeRandom", + "KeySize": 256, + "HardwareBound": True, + "Attest": False, + "UsageFlags": 1, + "ExtendedKeyUsage": [ExtendedKeyUsageOID.CLIENT_AUTH.dotted_string], + } + ], + } + return Response( + content=plistlib.dumps(profile), + media_type="application/x-apple-aspen-config", + headers={ + "Cache-Control": "no-store", + "Content-Disposition": 'attachment; filename="client-certificate.mobileconfig"', + }, + ) + + @ENROLLMENT_ROUTER.get( "/list", response_model=EnrollmentListOut, @@ -443,7 +514,11 @@ async def post_enrollment_accept( ) raise HTTPException(status_code=403, detail="Invalid approval code for this enrollment") - new_approved_user = await pending_enrollment.approve(approver=admin_user) + if pending_enrollment.acme_client_identifier is not None: + if not await pending_enrollment.approve_for_acme(approver=admin_user, approvecode=request_in.approvecode): + raise HTTPException(status_code=409, detail="ACME enrollment is no longer pending approval") + else: + await pending_enrollment.approve(approver=admin_user) LOGGER.audit( # type: ignore[attr-defined] "Enrollment approved", @@ -455,7 +530,7 @@ async def post_enrollment_accept( ), ) - return OperationResultResponse(success=True, extra=f"Approved {new_approved_user.callsign}") + return OperationResultResponse(success=True, extra=f"Approved {pending_enrollment.callsign}") @ENROLLMENT_ROUTER.post( @@ -720,7 +795,7 @@ async def post_enroll_invite_code( pass try: - enrollment = await obj.create_enrollment(callsign=callsign, csr=request_in.csr) + enrollment = await obj.create_enrollment(callsign=callsign, csr=request_in.csr, acme=request_in.acme) except CallsignReserved as exc: LOGGER.audit( # type: ignore[attr-defined] "Enrollment via invitecode failed - callsign not allowed", @@ -738,6 +813,8 @@ async def post_enroll_invite_code( # Create JWT token for user claims = {"sub": callsign} + if request_in.acme: + claims["enrollment_id"] = str(enrollment.pk) new_jwt = issue_enrollment_jwt(response, claims) LOGGER.audit( # type: ignore[attr-defined] diff --git a/src/rasenmaeher_api/web/api/router.py b/src/rasenmaeher_api/web/api/router.py index e7bd3cb4..c2346980 100644 --- a/src/rasenmaeher_api/web/api/router.py +++ b/src/rasenmaeher_api/web/api/router.py @@ -17,9 +17,11 @@ tokens, utils, ) +from rasenmaeher_api.web.api.acme.views import router as acme_router from rasenmaeher_api.web.api.federation.views import router as federation_router api_router = APIRouter() +api_router.include_router(acme_router, prefix="/acme", tags=["acme"]) api_router.include_router(healthcheck.router, prefix="/healthcheck", tags=["healthcheck"]) api_router.include_router(federation_router, prefix="/federation", tags=["federation"]) api_router.include_router(product.router, prefix="/product", tags=["product"]) diff --git a/tests/test_acme.py b/tests/test_acme.py new file mode 100644 index 00000000..511cd882 --- /dev/null +++ b/tests/test_acme.py @@ -0,0 +1,281 @@ +"""Exercise the Apple ACME flow through the public API and the configured CA.""" + +import datetime +import json +import plistlib +import secrets +import uuid +from typing import Any +from urllib.parse import urlsplit + +import httpx +import pytest +from async_asgi_testclient import TestClient # type: ignore[import-untyped] +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, utils +from cryptography.x509.oid import ExtendedKeyUsageOID +from fastapi import FastAPI + +from rasenmaeher_api.cert.acme import ACMEError, b64url, decode_b64url +from rasenmaeher_api.cert.backend import sign_csr +from rasenmaeher_api.cert.errors import CertError +from rasenmaeher_api.db import EngineWrapper, Enrollment, EnrollmentState, Person, acme +from rasenmaeher_api.db import people as people_db +from rasenmaeher_api.db.enrollments import ACME_AUTHORIZATION_LIFETIME +from rasenmaeher_api.db.errors import NotFound +from rasenmaeher_api.db.nonces import SeenToken + +ORIGIN = "https://localmaeher.dev.pvarki.fi" + + +class ACMEClient: + """Generate the same ES256 flattened JWS requests used by the Apple client.""" + + def __init__(self, client: httpx.AsyncClient, directory: dict[str, str], nonce: str) -> None: + self.client = client + self.directory = directory + self.key = ec.generate_private_key(ec.SECP256R1()) + self.nonce = nonce + self.account: str | None = None + + async def send( + self, + url: str, + payload: dict[str, Any] | None = None, + *, + nonce: str | None = None, + signed_url: str | None = None, + ) -> httpx.Response: + protected = {"alg": "ES256", "url": signed_url or url, "nonce": nonce or self.nonce} + public = self.key.public_key().public_numbers() + identity = ( + {"kid": self.account} + if self.account and url != self.directory["newAccount"] + else { + "jwk": { + "kty": "EC", + "crv": "P-256", + "x": b64url(public.x.to_bytes(32)), + "y": b64url(public.y.to_bytes(32)), + } + } + ) + encoded_header = b64url(json.dumps({**protected, **identity}).encode()) + encoded_payload = b64url(json.dumps(payload).encode()) if payload is not None else "" + signature = self.key.sign(f"{encoded_header}.{encoded_payload}".encode(), ec.ECDSA(hashes.SHA256())) + r, s = utils.decode_dss_signature(signature) + response = await self.client.post( + urlsplit(url).path, + json={ + "protected": encoded_header, + "payload": encoded_payload, + "signature": b64url(r.to_bytes(32) + s.to_bytes(32)), + }, + headers={"Content-Type": "application/jose+json"}, + ) + self.nonce = response.headers["Replay-Nonce"] + assert b64url(decode_b64url(self.nonce)) == self.nonce + return response + + async def register(self) -> httpx.Response: + response = await self.send(self.directory["newAccount"], {"termsOfServiceAgreed": True}) + response.raise_for_status() + self.account = response.headers["Location"] + return response + + +def csr(callsign: str, key: ec.EllipticCurvePrivateKey, san: x509.GeneralName | None = None) -> dict[str, str]: + """Build the profile's device CSR with an optional alternate name.""" + builder = ( + x509.CertificateSigningRequestBuilder() + .subject_name(x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, callsign)])) + .add_extension(x509.KeyUsage(True, False, False, False, False, False, False, False, False), critical=True) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False) + ) + if san is not None: + builder = builder.add_extension(x509.SubjectAlternativeName([san]), critical=False) + return {"csr": b64url(builder.sign(key, hashes.SHA256()).public_bytes(serialization.Encoding.DER))} + + +@pytest.mark.asyncio(loop_scope="session") +@pytest.mark.usefixtures("dbinit_sess") +@pytest.mark.parametrize("app_instance", ["RSA"], indirect=True) +async def test_acme_nonce_cleanup(app_instance: FastAPI, monkeypatch: pytest.MonkeyPatch) -> None: + """POST errors prune expired nonces without deleting accounts or other replay records.""" + expired = datetime.datetime.now(datetime.UTC) - acme.NONCE_LIFETIME - datetime.timedelta(seconds=1) + suffix = str(uuid.uuid4()) + expired_nonce = f"{acme.NONCE_PREFIX}expired-{suffix}" + remaining = (f"{acme.NONCE_PREFIX}live-{suffix}", f"{acme.ACCOUNT_PREFIX}{suffix}", f"other-{suffix}") + tokens = [ + SeenToken(token=expired_nonce, created=expired), + SeenToken(token=remaining[0]), + SeenToken(token=remaining[1], created=expired), + SeenToken(token=remaining[2], created=expired), + ] + with EngineWrapper.get_session() as session: + session.add_all(tokens) + session.commit() + + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app_instance), base_url=ORIGIN) as client: + # This suffix exposes the old concatenated nonce's nonzero base64 padding bits. + with monkeypatch.context() as patch: + patch.setattr(secrets, "token_urlsafe", lambda _: "B" * 32) + patch.setattr(secrets, "token_bytes", lambda _: b"\x01" * 32) + response = await client.post( + "/api/v1/acme/new-account", content=b"invalid", headers={"Content-Type": "application/jose+json"} + ) + assert response.status_code == 400 + nonce = response.headers["Replay-Nonce"] + assert b64url(decode_b64url(nonce)) == nonce + assert len(nonce) == 43 + with pytest.raises(NotFound): + await SeenToken.by_token(expired_nonce) + for token in remaining: + assert (await SeenToken.by_token(token)).token == token + + acme.consume_nonce(nonce) + with pytest.raises(ACMEError, match="Unknown, expired, or already used"): + acme.consume_nonce(nonce) + + for method in ("GET", "HEAD"): + response = await client.request(method, "/api/v1/acme/new-nonce") + nonce = response.headers["Replay-Nonce"] + assert b64url(decode_b64url(nonce)) == nonce + + +@pytest.mark.asyncio(loop_scope="session") +@pytest.mark.usefixtures("dbinit_sess") +@pytest.mark.parametrize("app_instance", ["RSA"], indirect=True) +async def test_apple_acme_issuance( + app_instance: FastAPI, tilauspalvelu_jwt_admin_client: TestClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """Issue once for the approved profile and recover from a signer failure with the same CSR.""" + admin = tilauspalvelu_jwt_admin_client + invite = await admin.post("/api/v1/enrollment/invitecode/create") + invite.raise_for_status() + invite_code = invite.json()["invite_code"] + callsign = f"acme{secrets.token_hex(4)}" + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app_instance), base_url=ORIGIN) as client: + directory_response = await client.get("/api/v1/acme/directory", headers={"Host": "other.example.test"}) + directory_response.raise_for_status() + directory = directory_response.json() + assert directory["newOrder"] == f"{ORIGIN}/api/v1/acme/new-order" + nonce_response = await client.head(urlsplit(directory["newNonce"]).path) + assert nonce_response.status_code == 200 + assert nonce_response.content == b"" + nonce = nonce_response.headers["Replay-Nonce"] + apple = ACMEClient(client, directory, nonce) + registered = await apple.register() + assert registered.status_code == 201 + assert apple.account is not None + assert (await apple.send(apple.account)).json() == registered.json() + replay = await apple.send(directory["newOrder"], {"identifiers": []}, nonce=nonce) + assert replay.status_code == 400 + assert replay.json()["type"].endswith(":badNonce") + mismatched = await apple.send(directory["newOrder"], {}, signed_url=directory["newAccount"]) + assert mismatched.status_code == 400 + second_nonce = await client.get(urlsplit(directory["newNonce"]).path) + assert second_nonce.status_code == 204 + other = ACMEClient(client, directory, second_nonce.headers["Replay-Nonce"]) + assert (await other.register()).status_code == 201 + second_account = other.account + other.account = apple.account + assert (await other.send(apple.account)).json()["type"].endswith(":unauthorized") + other.account = second_account + assert (await other.send(apple.account)).status_code == 403 + + invited = await client.post( + "/api/v1/enrollment/invitecode/enroll", + json={"invite_code": invite_code, "callsign": callsign, "acme": True}, + ) + invited.raise_for_status() + auth = {"Authorization": f"Bearer {invited.json()['jwt']}"} + approval = {"callsign": callsign, "approvecode": invited.json()["approvecode"]} + record = await Enrollment.by_callsign(callsign) + identifier = {"identifiers": [{"type": "permanent-identifier", "value": record.acme_client_identifier}]} + assert (await apple.send(directory["newOrder"], identifier)).status_code == 403 + (await admin.post("/api/v1/enrollment/accept", json=approval)).raise_for_status() + profile = await client.get("/api/v1/enrollment/acme-profile", headers=auth) + profile.raise_for_status() + identity = plistlib.loads(profile.content)["PayloadContent"][0] + assert identity["DirectoryURL"] == f"{ORIGIN}/api/v1/acme/directory" + assert identity["ClientIdentifier"] == record.acme_client_identifier + assert identity["Attest"] is False + + order = await apple.send(directory["newOrder"], identifier) + assert order.status_code == 201 + assert order.json()["status"] == "pending" + order_url = order.headers["Location"] + finalize = order.json()["finalize"] + assert (await apple.send(registered.json()["orders"])).json() == {"orders": [order_url]} + assert (await apple.send(directory["newOrder"], identifier)).headers["Location"] == order_url + assert (await other.send(directory["newOrder"], identifier)).status_code == 403 + assert (await other.send(order_url)).status_code == 403 + + device_key = ec.generate_private_key(ec.SECP256R1()) + request = csr(callsign, device_key) + assert (await apple.send(finalize, request)).json()["type"].endswith(":orderNotReady") + authorization = await apple.send(order.json()["authorizations"][0]) + assert authorization.json()["status"] == "pending" + challenge = authorization.json()["challenges"][0] + assert challenge["type"] == "device-attest-01" + assert (await apple.send(challenge["url"])).json() == challenge + assert (await apple.send(challenge["url"], {})).json()["status"] == "valid" + assert (await apple.send(order_url)).json()["status"] == "ready" + assert (await apple.send(finalize, csr("differentcallsign", device_key))).json()["type"].endswith(":badCSR") + assert (await apple.send(finalize, csr(callsign, device_key, x509.DNSName("other.example")))).status_code == 400 + + signing_calls = 0 + + async def fail_once(pem: str) -> str: + nonlocal signing_calls + signing_calls += 1 + if signing_calls == 1: + raise CertError("Signer temporarily unavailable") + return await sign_csr(pem) + + monkeypatch.setattr(people_db, "sign_csr", fail_once) + assert (await apple.send(finalize, request)).status_code == 503 + with pytest.raises(NotFound): + await Person.by_callsign(callsign) + replacement = csr(callsign, ec.generate_private_key(ec.SECP256R1())) + assert (await apple.send(finalize, replacement)).status_code == 400 + finalized = await apple.send(finalize, request) + finalized.raise_for_status() + assert finalized.json()["status"] == "valid" + assert (await apple.send(finalize, request)).json() == finalized.json() + assert signing_calls == 2 + + package = await apple.send(finalized.json()["certificate"]) + package.raise_for_status() + assert package.headers["Content-Type"] == "application/pem-certificate-chain" + leaf, issuer, *_ = x509.load_pem_x509_certificates(package.content) + leaf.verify_directly_issued_by(issuer) + assert leaf.subject == x509.Name([x509.NameAttribute(x509.NameOID.COMMON_NAME, callsign)]) + assert leaf.public_key() == device_key.public_key() + person = await Person.by_callsign(callsign) + assert person.cert_serial == str(leaf.serial_number) + assert not person.privkeyfile.exists() + assert (await other.send(finalized.json()["certificate"])).status_code == 403 + status = await client.get(f"/api/v1/enrollment/status?callsign={callsign}", headers=auth) + assert status.json()["status"] == EnrollmentState.APPROVED + + stale = f"acme{secrets.token_hex(4)}" + expired = await client.post( + "/api/v1/enrollment/invitecode/enroll", json={"invite_code": invite_code, "callsign": stale, "acme": True} + ) + expired.raise_for_status() + ( + await admin.post( + "/api/v1/enrollment/accept", json={"callsign": stale, "approvecode": expired.json()["approvecode"]} + ) + ).raise_for_status() + stale_record = await Enrollment.by_callsign(stale) + with EngineWrapper.get_session() as session: + stale_record.decided_on = datetime.datetime.now(datetime.UTC) - ACME_AUTHORIZATION_LIFETIME + session.add(stale_record) + session.commit() + session.refresh(stale_record) + stale_id = {"identifiers": [{"type": "permanent-identifier", "value": stale_record.acme_client_identifier}]} + assert (await apple.send(directory["newOrder"], stale_id)).status_code == 403 diff --git a/tests/test_enrollment.py b/tests/test_enrollment.py index f171a2c9..a9cb422f 100644 --- a/tests/test_enrollment.py +++ b/tests/test_enrollment.py @@ -1,6 +1,8 @@ """Test enrollment endpoint""" +import datetime import logging +import plistlib import secrets import uuid from pathlib import Path @@ -11,12 +13,16 @@ from async_asgi_testclient import TestClient # type: ignore[import-untyped] from cryptography import x509 from libpvarki.mtlshelp.csr import async_create_client_csr, async_create_keypair +from multikeyjwt import Issuer from rasenmaeher_api.db import ( EngineWrapper, + Enrollment, EnrollmentPool, + EnrollmentState, Person, ) +from rasenmaeher_api.db.enrollments import ACME_AUTHORIZATION_LIFETIME from rasenmaeher_api.rmsettings import RMSettings LOGGER = logging.getLogger(__name__) @@ -653,6 +659,71 @@ async def test_enroll_with_invite_code( del unauth_client_session.headers["Authorization"] +@pytest.mark.asyncio(loop_scope="session") +@pytest.mark.usefixtures("dbinit_sess") +@pytest.mark.parametrize("app_instance", ["RSA"], indirect=True) +async def test_acme_invite_enrollment(tilauspalvelu_jwt_admin_client: TestClient, unauth_client: TestClient) -> None: + """Approve a device enrollment and download the same profile until its authorization expires.""" + admin = tilauspalvelu_jwt_admin_client + invite = await admin.post("/api/v1/enrollment/invitecode/create") + invite.raise_for_status() + callsign = f"acme{secrets.token_hex(4)}" + enroll_url = "/api/v1/enrollment/invitecode/enroll" + profile_url = "/api/v1/enrollment/acme-profile" + enrollment_request = {"invite_code": invite.json()["invite_code"], "callsign": callsign, "acme": True} + + assert (await unauth_client.get(profile_url)).status_code == 403 + assert (await unauth_client.post(enroll_url, json={**enrollment_request, "csr": "device-csr"})).status_code == 422 + enrollment = await unauth_client.post(enroll_url, json=enrollment_request) + enrollment.raise_for_status() + assert (await unauth_client.post(enroll_url, json=enrollment_request)).status_code == 400 + + auth_header = {"Authorization": f"Bearer {enrollment.json()['jwt']}"} + accept_url = "/api/v1/enrollment/accept" + accept_request = {"callsign": callsign, "approvecode": enrollment.json()["approvecode"]} + assert (await unauth_client.get(profile_url, headers=auth_header)).status_code == 409 + assert (await admin.post(accept_url, json={**accept_request, "approvecode": "invalid"})).status_code == 403 + approved = await admin.post(accept_url, json=accept_request) + approved.raise_for_status() + assert (await admin.post(accept_url, json=accept_request)).status_code == 409 + + status = await unauth_client.get(f"/api/v1/enrollment/status?callsign={callsign}", headers=auth_header) + assert status.json() == {"callsign": callsign, "status": EnrollmentState.AWAITING_ACME} + record = await Enrollment.by_callsign(callsign) + assert record.person is None + assert record.csr is None + + assert (await admin.get(profile_url)).status_code == 403 + other_jwt = Issuer().issue({"sub": callsign, "enrollment_id": str(uuid.uuid4())}) + assert (await unauth_client.get(profile_url, headers={"Authorization": f"Bearer {other_jwt}"})).status_code == 403 + profile = await unauth_client.get(profile_url, headers={**auth_header, "Host": "other.example.test:8443"}) + profile.raise_for_status() + assert profile.headers["content-type"] == "application/x-apple-aspen-config" + assert profile.headers["cache-control"] == "no-store" + payload = plistlib.loads(profile.content)["PayloadContent"][0] + assert payload["PayloadType"] == "com.apple.security.acme" + assert payload["DirectoryURL"] == "https://localmaeher.dev.pvarki.fi/api/v1/acme/directory" + assert payload["Subject"] == [[["CN", callsign]]] + assert payload["ClientIdentifier"] == record.acme_client_identifier + assert payload["ClientIdentifier"] != callsign + assert payload["HardwareBound"] is True + assert payload["KeySize"] == 256 + assert payload["UsageFlags"] == 1 + assert payload["ExtendedKeyUsage"] == ["1.3.6.1.5.5.7.3.2"] + assert (await unauth_client.get(profile_url, headers=auth_header)).content == profile.content + + with EngineWrapper.get_session() as session: + record.decided_on = datetime.datetime.now(datetime.UTC) - ACME_AUTHORIZATION_LIFETIME + session.add(record) + session.commit() + assert (await unauth_client.get(profile_url, headers=auth_header)).status_code == 410 + + locked = await admin.post("/api/v1/enrollment/lock", json={"callsign": callsign, "lock_reason": "Revoked approval"}) + locked.raise_for_status() + assert (await admin.post(accept_url, json=accept_request)).status_code == 409 + assert (await unauth_client.get(profile_url, headers=auth_header)).status_code == 409 + + # ENROLL WITH CSR (and invite-code @pytest.mark.asyncio(loop_scope="session") async def test_enroll_with_csr( diff --git a/tests/test_rasenmaeher_api.py b/tests/test_rasenmaeher_api.py index 850b3bea..d4fd84c7 100644 --- a/tests/test_rasenmaeher_api.py +++ b/tests/test_rasenmaeher_api.py @@ -15,7 +15,7 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.20.2+261121" + assert __version__ == "1.21.1+261122" @pytest.mark.asyncio(loop_scope="session") diff --git a/uv.lock b/uv.lock index eaa8c0d1..9daaaba9 100644 --- a/uv.lock +++ b/uv.lock @@ -2366,7 +2366,7 @@ wheels = [ [[package]] name = "rasenmaeher-api" -version = "1.20.2+261121" +version = "1.21.1+261122" source = { editable = "." } dependencies = [ { name = "aiodns" },