Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
34b8eaf
fix: verify_csr compared a rendered string, so a crafted subject slip…
benjamsf Sep 12, 2026
641c136
chore: bump version
benjamsf Sep 12, 2026
92bcd8a
fix: verify_csr matched the callsign as a substring
benjamsf Sep 12, 2026
78def9a
chore: bump version
benjamsf Sep 12, 2026
9eb21b6
chore: remove useless comments
benjamsf Sep 12, 2026
959ae22
Merge branch 'fix/verify-csr-exact-subject' of github.com:pvarki/pyth…
benjamsf Sep 12, 2026
d6c368d
feat: let an MDM agent complete device enrollments an admin planned
benjamsf Sep 12, 2026
099cc62
chore: bump version
benjamsf Sep 12, 2026
ebd05aa
fix: reserve MDM agent CNs against being taken as callsigns
benjamsf Sep 13, 2026
8908ab6
feat: mark devices planned for MDM in the enrollment list
benjamsf Sep 13, 2026
e79d633
test: two devices cannot both claim one planned callsign
benjamsf Sep 13, 2026
f0b009f
fix: a device request may not choose what it is issued
benjamsf Sep 14, 2026
19727eb
fix: require the per-enrolment code, not just the callsign
benjamsf Sep 15, 2026
d6d0df8
feat: list the approval code for devices, not for people
benjamsf Sep 18, 2026
8ece58a
feat: tell the admin UI what to configure the MDM with
benjamsf Sep 19, 2026
0a4a89f
Merge branch 'main' into feat/mdm-list-codes
benjamsf Oct 9, 2026
4646a5e
style: let ruff format decide the wrapping
benjamsf Oct 9, 2026
8b7a927
fix: install the locked versions in the production image
benjamsf Oct 9, 2026
f502565
test: carry the enrolment proof the way an MDM does
benjamsf Oct 9, 2026
e420c3b
test: give the CLI subprocess tests a realistic timeout
benjamsf Oct 9, 2026
cb4e01e
fix: name the postgres DBAPI instead of inheriting the default
benjamsf Oct 10, 2026
6cd96de
fix: drop the MDM settings endpoint
benjamsf Oct 27, 2026
57cf766
fix: refuse MDM callsigns the proof cannot carry
benjamsf Oct 27, 2026
aee8046
Merge branch 'main' into feat/mdm-list-codes
benjamsf Oct 28, 2026
80ea0a4
feat: let an admin open MDM enrolment for a while
benjamsf Oct 28, 2026
3662b2a
fix: accept the enrolment proof from exactly one attribute
benjamsf Oct 28, 2026
676d476
feat: let the MDM name the devices it enrols
benjamsf Oct 29, 2026
eb04ade
feat: take hyphens and 32 characters in MDM device names
benjamsf Oct 29, 2026
7daa723
fix: reserve service names in any case
benjamsf Oct 31, 2026
deabfd7
fix: refuse device keys anybody could recover
benjamsf Oct 31, 2026
39d772f
style: format the weak key test
benjamsf Oct 31, 2026
6d8d4e6
feat: give every MDM enrolment window a new challenge
benjamsf Oct 31, 2026
7fe53c1
fix: refuse to promote an MDM enrolled device to admin
benjamsf Nov 21, 2026
6322f1e
fix: delete the CertificateRequest once its certificate is read and s…
benjamsf Nov 21, 2026
491585e
fix: keep no request file for an MDM enrolled device
benjamsf Nov 21, 2026
bfec2cb
fix: hold the two-hour limit of the MDM enrolment window on the server
benjamsf Nov 22, 2026
54484a6
feat(people): say when each person's certificate ends in the people list
benjamsf Nov 22, 2026
d4308b4
Merge branch 'main' into feat/mdm-list-codes
benjamsf Nov 23, 2026
6b41876
fix(enrollment): require the CSR to be signed by its own key
benjamsf Nov 21, 2026
1715514
test: the MDM path under main's rule for a certificate request
benjamsf Nov 23, 2026
0bd725d
chore: drop a setting that main removed and nothing reads
benjamsf Nov 23, 2026
b8889eb
docs: say what the MDM agent does since devices are named by their MDM
benjamsf Nov 23, 2026
05900cb
chore: bump version to 1.21.0+261123
benjamsf Nov 23, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .bumpversion.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "1.20.2+261121"
current_version = "1.21.0+261123"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)\\+(?P<build>\\d+)"
serialize = ["{major}.{minor}.{patch}+{build}"]
search = "{current_version}"
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "rasenmaeher_api"
version = "1.20.2+261121"
version = "1.21.0+261123"
description = "python-rasenmaeher-api"
authors = [
{ name = "Aciid", email = "703382+Aciid@users.noreply.github.com" },
Expand Down
2 changes: 1 addition & 1 deletion src/rasenmaeher_api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""python-rasenmaeher-api"""

__version__ = "1.20.2+261121" # NOTE Use `bump-my-version` to bump versions correctly
__version__ = "1.21.0+261123" # NOTE Use `bump-my-version` to bump versions correctly
56 changes: 37 additions & 19 deletions src/rasenmaeher_api/cert/cert_manager/private.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Private APIs for cert-manager backend.

The signing flow creates a cert-manager ``CertificateRequest`` CR carrying the
caller-provided CSR, waits until cert-manager issues the certificate, and returns
the issued certificate as PEM. Revocation is DB-driven (served to clients by
the OCSP responder), so the revoke functions only best-effort clean up the CR.
caller-provided CSR, waits until cert-manager issues the certificate, deletes the
CR, and returns the issued certificate as PEM. Revocation is DB-driven (served to
clients by the OCSP responder), so the revoke functions only best-effort clean up the CR.
"""

import base64
Expand Down Expand Up @@ -77,7 +77,6 @@ async def _create_cr(name: str, namespace: str, csr_pem: str, csr_b64: str, sett
).build()

LOGGER.info("Creating CertificateRequest %s/%s", namespace, name)
LOGGER.debug("CertificateRequest: %s", certificate_request.model_dump_json())

return await certificate_request.async_create()
except ResourceConflict:
Expand Down Expand Up @@ -109,22 +108,19 @@ async def _delete_cr(name: str, namespace: str) -> bool:
return False


async def sign_csr(csr: str, bundle: bool = True) -> str:
"""
Sign CSR via cert-manager by submitting a CertificateRequest CR.
params: csr, whether to return cert or full bundle
returns: certificate as PEM (with bundle appended if requested)
"""
settings = RMSettings.singleton()
cn = _csr_common_name(csr)
if extra := disallowed_usages(csr, cn):
raise ValueError(f"CSR for {cn} requests usages not allowed for it: {sorted(extra)}")
name = cr_name(csr, cn)
namespace = settings.cert_manager_namespace
csr_b64 = _csr_pem_to_b64(csr)
async def _discard_cr(name: str, namespace: str) -> None:
"""Delete a CertificateRequest that has served its purpose, without failing the caller"""
try:
await _delete_cr(name, namespace)
except Exception: # pylint: disable=broad-except
# Cleaning up must not replace the outcome of the signing itself.
LOGGER.warning("Could not delete CertificateRequest %s/%s", namespace, name, exc_info=True)

certificate_request = await _upsert_cr(name, namespace, csr, csr_b64, settings)

async def _issued_certificate(
certificate_request: CertificateRequest, name: str, namespace: str, settings: RMSettings
) -> str:
"""Wait for cert-manager to issue the certificate and return it as PEM"""
try:
await certificate_request.async_wait_for(
lambda _, cr: (
Expand All @@ -142,8 +138,30 @@ async def sign_csr(csr: str, bundle: bool = True) -> str:
raise RuntimeError("certificate request has no status")
if certificate_request.status.certificate is None:
raise RuntimeError("certificate request status has no certificate")
return base64.b64decode(certificate_request.status.certificate).decode("utf-8")


cert_pem = base64.b64decode(certificate_request.status.certificate).decode("utf-8")
async def sign_csr(csr: str, bundle: bool = True) -> str:
"""
Sign CSR via cert-manager by submitting a CertificateRequest CR.
params: csr, whether to return cert or full bundle
returns: certificate as PEM (with bundle appended if requested)
"""
settings = RMSettings.singleton()
cn = _csr_common_name(csr)
if extra := disallowed_usages(csr, cn):
raise ValueError(f"CSR for {cn} requests usages not allowed for it: {sorted(extra)}")
name = cr_name(csr, cn)
namespace = settings.cert_manager_namespace
csr_b64 = _csr_pem_to_b64(csr)

certificate_request = await _upsert_cr(name, namespace, csr, csr_b64, settings)
try:
cert_pem = await _issued_certificate(certificate_request, name, namespace, settings)
finally:
# The request is the client's own, an enrolment challenge included, and nothing reads it
# once the certificate has been read or the wait has failed.
await _discard_cr(name, namespace)

if bundle:
cert_pem = lean_chain(cert_pem, await get_ca())
Expand Down
2 changes: 2 additions & 0 deletions src/rasenmaeher_api/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .engine import EngineWrapper
from .enrollments import Enrollment, EnrollmentPool, EnrollmentState
from .logincodes import LoginCode
from .mdmenrolment import MdmEnrolment
from .nonces import SeenToken
from .people import Person, Role

Expand All @@ -15,6 +16,7 @@
"EnrollmentPool",
"EnrollmentState",
"LoginCode",
"MdmEnrolment",
"Person",
"Role",
"SeenToken",
Expand Down
3 changes: 3 additions & 0 deletions src/rasenmaeher_api/db/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
class DBConfig:
"""DB config dataclass, functools etc used to avoid import-time side-effects"""

# Name the DBAPI rather than leaving it to SQLAlchemy's default for postgresql://, which moved
# from psycopg2 to psycopg3 in SQLAlchemy 2.1. We ship psycopg2, so the bare name stops
# resolving the moment anything builds us against 2.1.
driver: str = field(
default_factory=cast(
Callable[..., str], functools.partial(config, "RM_DATABASE_DRIVER", default="postgresql+psycopg2")
Expand Down
3 changes: 2 additions & 1 deletion src/rasenmaeher_api/db/dbinit.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
from .enrollments import Enrollment, EnrollmentPool
from .issuedcerts import IssuedCert
from .logincodes import LoginCode
from .mdmenrolment import MdmEnrolment
from .nonces import SeenToken
from .people import Person, Role

_ = (Person, Role, EnrollmentPool, Enrollment, SeenToken, LoginCode, IssuedCert)
_ = (Person, Role, EnrollmentPool, Enrollment, SeenToken, LoginCode, IssuedCert, MdmEnrolment)
LOGGER = logging.getLogger(__name__)


Expand Down
7 changes: 4 additions & 3 deletions src/rasenmaeher_api/db/enrollments.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from .base import ORMBaseModel
from .engine import EngineWrapper
from .errors import CallsignReserved, Deleted, ForbiddenOperation, NotFound, PoolInactive
from .people import Person
from .people import Person, reserved_callsign

LOGGER = logging.getLogger(__name__)
CODE_ALPHABET = string.ascii_uppercase + string.digits
Expand Down Expand Up @@ -285,8 +285,9 @@ async def create_for_callsign(
csr: str | None = None,
) -> "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")
reason = reserved_callsign(callsign)
if reason:
raise CallsignReserved(reason, detail="Callsign reserved")
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:
Expand Down
98 changes: 98 additions & 0 deletions src/rasenmaeher_api/db/mdmenrolment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Whether devices may enrol through an MDM right now, and the challenge they must bring"""

import datetime
import hmac
import logging
import secrets

import sqlalchemy as sa
from sqlalchemy.exc import IntegrityError
from sqlmodel import Field, select

from .base import ORMBaseModel
from .engine import EngineWrapper
from .errors import ForbiddenOperation

LOGGER = logging.getLogger(__name__)

#: The longest the window opens for in one go. While it is open the challenge is all that stands
#: between the public SCEP endpoint and a new identity, so the limit is held here and not by a page.
MAX_OPEN_HOURS = 2


def new_challenge() -> str:
"""Hex, because the challenge travels as an X.509 attribute and some clients encode it as a
PrintableString, which has no room for "_"."""
return secrets.token_hex(16)


class MdmEnrolment(ORMBaseModel, table=True):
"""The one row saying when the MDM enrolment window closes

Closed until an admin opens it, and it closes itself when the window runs out, so a deployment
nobody is watching does not go on taking enrolments. Every window gets a new challenge: while
it is open the challenge is all that stands between the public SCEP endpoint and a new
identity, and every device enrolled so far holds the old one. So opening means putting the new
challenge in the MDM.
"""

__tablename__ = "mdmenrolment"

# One row, and the unique key makes the database refuse a second one when workers race to
# create it.
slot: str = Field(default="mdm", nullable=False, unique=True)
challenge: str = Field(nullable=False)
open_until: datetime.datetime | None = Field(
default=None, sa_column=sa.Column(sa.DateTime(timezone=True), nullable=True)
)

@classmethod
async def current(cls) -> "MdmEnrolment":
"""The row, made with a fresh challenge and closed the first time anybody asks"""
with EngineWrapper.get_session() as session:
obj = session.exec(select(cls)).first()
if obj:
return obj
obj = cls(challenge=new_challenge())
session.add(obj)
try:
session.commit()
except IntegrityError:
session.rollback()
return session.exec(select(cls)).one()
session.refresh(obj)
return obj

@property
def is_open(self) -> bool:
"""Is the window open right now"""
return self.open_until is not None and self.open_until > datetime.datetime.now(datetime.UTC)

def accepts(self, challenge: str | None) -> bool:
"""Is this the challenge, compared without leaking how much of it matched"""
if not challenge:
return False
return hmac.compare_digest(challenge.encode("utf-8"), self.challenge.encode("utf-8"))

async def open_for(self, hours: int) -> "MdmEnrolment":
"""Open the window for this many hours from now, or close it with 0

Opening a closed window makes a new challenge. Extending an open one keeps it, because the
devices the MDM is enrolling at that moment were handed it. More than MAX_OPEN_HOURS from
now is refused, whoever asks.
"""
if not 0 <= hours <= MAX_OPEN_HOURS:
raise ValueError(f"The enrolment window opens for 0 to {MAX_OPEN_HOURS} hours, not {hours}")
until = datetime.datetime.now(datetime.UTC) + datetime.timedelta(hours=hours) if hours else None
with EngineWrapper.get_session() as session:
if until and not self.is_open:
self.challenge = new_challenge()
self.open_until = until
session.add(self)
session.commit()
session.refresh(self)
return self

async def delete(self) -> bool:
"""The row is the setting; closing the window is what turns enrolment off"""
raise ForbiddenOperation("Deletion of the MDM enrolment setting is not allowed")
38 changes: 35 additions & 3 deletions src/rasenmaeher_api/db/people.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@
LOGGER = logging.getLogger(__name__)


def reserved_callsign(callsign: str) -> str | None:
"""Why this callsign belongs to a service rather than a person, or None if it does not

Compared without case: lookups fold it, and Keycloak and Matrix lowercase the name, so
RASENMAEHER is the same account as rasenmaeher everywhere downstream.
"""
cnf = RMSettings.singleton()
if cnf.is_reserved_cn(callsign):
return "Service CN used as callsign"
if callsign.lower() in {cnname.lower() for cnname in cnf.mdm_agent_cn_set}:
# A certificate with this CN is accepted as the MDM enrolment agent on sight, so issuing
# one to a person would let them enrol devices.
return "Using MDM agent CNs as callsigns is forbidden"
return None


class Person(ORMBaseModel, table=True):
"""People, pk is UUID and comes from basemodel

Expand Down Expand Up @@ -99,8 +115,9 @@ async def create_with_cert(
) -> "Person":
"""Create the cert etc and save the person"""
cnf = RMSettings.singleton()
if cnf.is_reserved_cn(callsign):
raise CallsignReserved("Service CN used as callsign", detail="Callsign reserved")
reason = reserved_callsign(callsign)
if reason:
raise CallsignReserved(reason, detail="Callsign reserved")
if csrpem and not verify_csr(csrpem, callsign):
raise CallsignReserved(detail="CSR subject or key usages not allowed for callsign")
try:
Expand All @@ -119,7 +136,10 @@ async def create_with_cert(
session.add(newperson)
session.commit()
if csrpem:
newperson.csrfile.write_text(csrpem, encoding="utf-8")
# A device's request carries the MDM enrolment challenge, and nothing reads it
# back: a repeated enrolment is matched on the certificate's key.
if not (extra or {}).get("mdm"):
newperson.csrfile.write_text(csrpem, encoding="utf-8")
else:
ckp = await async_create_keypair(
newperson.privkeyfile, newperson.pubkeyfile, ktype=cnf.cert_key_type
Expand Down Expand Up @@ -257,6 +277,18 @@ def pubkeyfile(self) -> Path:
"""Path to the public key"""
return Path(self.certspath) / "mtls.pub"

def cert_ends(self) -> datetime.datetime | None:
"""When the certificate stops being valid, from the certificate itself; None without a readable one

Read from the file on every call: nothing else here records it. A listing of very many people
reads as many files, and a column filled in when the certificate is issued would spare that.
"""
try:
return cryptography.x509.load_pem_x509_certificate(self.certfile.read_bytes()).not_valid_after_utc
except (OSError, ValueError):
# ValueError also for a date no calendar has: one certificate must not take the whole list down
return None

@classmethod
async def list(cls, include_deleted: bool = False, *, only_deleted: bool = False) -> AsyncGenerator["Person", None]:
"""List people"""
Expand Down
12 changes: 12 additions & 0 deletions src/rasenmaeher_api/rmsettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,13 @@ def log_level_int(self) -> int:
ocsp_ca_secret_namespace: str = "cert-manager"
ocsp_response_validity: int = 3600 # seconds from now until nextUpdate

# Service identities allowed to enrol devices under the names their MDM gave them, while an
# admin has enrolment open, comma separated. Empty by default: until a deployment names its
# MDM agent here, the agent path in POST /enrollment/accept does not exist. Deliberately NOT
# the kraftwerk product CNs: those are exempt from role checks, can have any CSR signed and
# cannot be revoked at the edge, which is far more than enrolling a device needs.
mdm_agent_cns: str = ""

persistent_data_dir: str = "/data/persistent"

# mtls
Expand Down Expand Up @@ -177,6 +184,11 @@ def deployment_name(self) -> str:
LOGGER.warning("DNS name not defined")
return "undefined"

@property
def mdm_agent_cn_set(self) -> set[str]:
"""CNs allowed to act as an MDM enrolment agent"""
return {cnname.strip() for cnname in self.mdm_agent_cns.split(",") if cnname.strip()}

@property
def valid_product_cns(self) -> list[str]:
"""Get valid CNs for productapi certs"""
Expand Down
Loading
Loading