From 2c2aa818ba3eb314d3c7379bdfbca09f02da732b Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 00:02:36 +0200 Subject: [PATCH 001/104] feat: move the Fleet driver and template loader from rmscep --- src/odmdm_fleet/fleet.py | 479 ++++++++++++++++++++++++++++++++ src/odmdm_fleet/icon.py | 31 +++ src/odmdm_fleet/template.py | 162 +++++++++++ tests/test_fleet.py | 525 ++++++++++++++++++++++++++++++++++++ tests/test_template.py | 101 +++++++ 5 files changed, 1298 insertions(+) create mode 100644 src/odmdm_fleet/fleet.py create mode 100644 src/odmdm_fleet/icon.py create mode 100644 src/odmdm_fleet/template.py create mode 100644 tests/test_fleet.py create mode 100644 tests/test_template.py diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py new file mode 100644 index 0000000..07eec2f --- /dev/null +++ b/src/odmdm_fleet/fleet.py @@ -0,0 +1,479 @@ +"""What a deployment needs, said to FleetDM + +Every request shape and every wait in here was measured against a live Fleet, and the comments +say which. None of it mentions a product: what to install arrives in the template. +""" + +import dataclasses +import hashlib +import json +import logging +import time +from typing import Any +from urllib.parse import urlencode, urlparse + +import httpx + +from .icon import launcher_icon +from .template import MdmTemplate + +LOGGER = logging.getLogger(__name__) + +#: A web app is not installable until managed Play has published it, which is not synchronous +WEB_APP_PUBLISH_ATTEMPTS = 12 +WEB_APP_PUBLISH_WAIT = 10.0 + + +class FleetError(RuntimeError): + """Fleet refused, or answered something we cannot use""" + + +#: Google refuses a managed web app title of 30 characters or more +MAX_WEB_APP_TITLE = 29 + +#: Named after the responder this was first applied from, and kept: Fleet knows a profile by its +#: name, so a new name would sit next to the old profile on every team instead of replacing it. +POLICY_NAME = "rmscep-policy" + + +class FleetMdm: + """What this feature needs an MDM to be able to do, in Fleet's words""" + + def __init__(self, base_url: str, token: str, timeout: float = 60.0) -> None: + self.base_url = base_url.rstrip("/") + self._token = token + self.timeout = timeout + #: What we last uploaded, so an unchanged policy is not rewritten. Re-pushing on every + #: pass is not merely wasteful: a policy rewritten repeatedly never settles long enough + #: for Play to finish an install, and the device comes up with nothing on it. + self._pushed: dict[str, str] = {} + + def _call(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]: + url = f"{self.base_url}{path}" + try: + response = httpx.request( + method, + url, + json=body, + headers={"Authorization": f"Bearer {self._token}"}, + timeout=self.timeout, + ) + except httpx.HTTPError as exc: + raise FleetError(f"could not reach the MDM: {exc}") from exc + if response.status_code >= 400: + # Enough of the body to keep the reason intact: the retry below matches on it, and + # truncating to a couple of hundred characters cut the phrase off mid-word. + raise FleetError(f"{method} {path} answered {response.status_code}: {response.text[:800]}") + if not response.content: + return {} + try: + payload: dict[str, Any] = response.json() + except ValueError as exc: + raise FleetError(f"{method} {path} did not answer JSON") from exc + return payload + + def _upload( + self, + path: str, + fields: dict[str, str], + filename: str, + payload: bytes, + file_field: str, + content_type: str = "application/json", + ) -> dict[str, Any]: + url = f"{self.base_url}{path}" + try: + response = httpx.post( + url, + data=fields, + files={file_field: (filename, payload, content_type)}, + headers={"Authorization": f"Bearer {self._token}"}, + timeout=self.timeout, + ) + except httpx.HTTPError as exc: + raise FleetError(f"could not reach the MDM: {exc}") from exc + if response.status_code >= 400: + raise FleetError(f"upload to {path} answered {response.status_code}: {response.text[:200]}") + return response.json() if response.content else {} + + # --- scopes --------------------------------------------------------------- + + def team_id(self, name: str) -> int: + """The team by name, created if it is not there yet""" + for team in self._call("GET", "/api/latest/fleet/teams").get("teams", []): + if team.get("name") == name: + return int(team["id"]) + created = self._call("POST", "/api/latest/fleet/teams", {"name": name}) + team = created.get("team", created) + LOGGER.info("Created team %s", name) + return int(team["id"]) + + # --- what a device gets --------------------------------------------------- + + def _title_id(self, team: int, package: str) -> int | None: + query = urlencode({"team_id": team, "available_for_install": "true"}) + titles = self._call("GET", f"/api/latest/fleet/software/titles?{query}").get("software_titles", []) + for title in titles: + if (title.get("app_store_app") or {}).get("app_store_id") == package: + return int(title["id"]) + return None + + def assign_apps(self, team: int, packages: list[str], preinstall: list[str]) -> dict[str, int]: + """Make the apps available, and install them at enrolment where that is possible + + Fleet hardcodes AVAILABLE for user-added Android apps -- FORCE_INSTALLED is reserved for + its own agent -- so the setup experience is the only automatic path, and it applies at + ENROLMENT. A host that has already joined will never auto-install; it has to enrol again. + """ + ids: dict[str, int] = {} + for package in packages: + existing = self._title_id(team, package) + if existing: + ids[package] = existing + continue + body = {"app_store_id": package, "platform": "android", "team_id": team} + for attempt in range(WEB_APP_PUBLISH_ATTEMPTS): + try: + created = self._call("POST", "/api/latest/fleet/software/app_store_apps", body) + ids[package] = int(created["software_title_id"]) + break + except FleetError as exc: + # Apostrophes vary; match the part that does not. + if "available in Play Store" not in str(exc) or attempt == WEB_APP_PUBLISH_ATTEMPTS - 1: + raise + LOGGER.info("Waiting for managed Play to publish %s", package) + time.sleep(WEB_APP_PUBLISH_WAIT) + chosen = sorted(ids[p] for p in preinstall if p in ids) + digest = hashlib.sha256(repr(chosen).encode()).hexdigest() + if chosen and self._pushed.get(f"{team}:setup") != digest: + self._call( + "PUT", + "/api/latest/fleet/setup_experience/software", + {"platform": "android", "team_id": team, "software_title_ids": chosen}, + ) + self._pushed[f"{team}:setup"] = digest + return ids + + def set_app_config(self, team: int, package: str, config: dict[str, Any]) -> None: + title = self._title_id(team, package) + if not title: + raise FleetError(f"{package} is not assigned to team {team}; assign it before configuring it") + self._call( + "PATCH", + f"/api/latest/fleet/software/titles/{title}/app_store_app", + {"team_id": team, "configuration": {"managedConfiguration": config}}, + ) + + def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_NAME, force: bool = False) -> None: + """Android configuration profiles carry raw policy JSON + + There is no update in place, so changing one is delete then upload, and the single + profile GET returns metadata only, so there is nothing to compare against -- remember the + digest instead. Re-uploading an unchanged profile is not free: a policy rewritten on every + pass never settles long enough for Play to finish an install. + + force exists because a profile is delivered when the PROFILE changes, not when a host + arrives, so one created before a device joined is never sent to it. + """ + profiles = self._call("GET", f"/api/latest/fleet/configuration_profiles?team_id={team}").get("profiles", []) + wanted = json.dumps(fragment, indent=2, sort_keys=True).encode("utf-8") + digest = hashlib.sha256(wanted).hexdigest() + here = [p for p in profiles if p.get("name") == name] + if here and not force and self._pushed.get(f"{team}:{name}") == digest: + return + for existing in here: + self._call("DELETE", f"/api/latest/fleet/configuration_profiles/{existing['profile_uuid']}") + self._upload( + "/api/latest/fleet/configuration_profiles", + {"team_id": str(team)}, + f"{name}.json", + wanted, + file_field="profile", + ) + self._pushed[f"{team}:{name}"] = digest + LOGGER.info("Uploaded policy %s to team %s", name, team) + + def ensure_link_app(self, team: int, title: str, url: str) -> str: + """A managed web app, so the deployment has an icon on the launcher + + Looked up before publishing, because publishing twice does not yield one app. Google was + expected to derive the package name from the url and so dedupe a repeat of the same url; + it does not. One url published twice gave two package names, so every re-run left another + launcher on the team and another permanent app in the enterprise, Fleet offering no way + to delete one. + + So the deployment goes in the published title and the title is the identity -- its first + DNS label rather than the whole host, because Google refuses a title of 30 characters or + more; see _published_title. Fleet never hands a web app's url back, and the team does not + identify a deployment either -- the original bug was a new deployment reusing the team + name of the one it replaced, finding "Deploy App" already there, and handing every device + an icon for the decommissioned host. Naming the deployment makes a re-run match and a + move not match, which is exactly the distinction we cannot otherwise draw. + + Fleet lists a web app under its package name until a device reports the title, so apply() + sets the display name straight after assigning it. A run that stops in between leaves an + app this lookup cannot see; the conflict below says how to recover it. + + The icon is required rather than decorative -- without one Google never publishes the app + and every device reports the install as NOT_FOUND. + """ + title = self._published_title(title, url) + published = self._link_app_in_team(team, title) + if published: + LOGGER.info("Launcher web app %s already published to team %s, reusing it", published, team) + return published + try: + created = self._upload( + "/api/latest/fleet/software/web_apps", + {"title": title, "url": url}, + "icon.png", + launcher_icon(), + file_field="icon", + content_type="image/png", + ) + except FleetError as exc: + # A conflict means the name is already published to the enterprise. Re-read the team, + # because publishing is asynchronous and the lookup above can lose that race. + # + # There is nothing else to try. Checked against Fleet 4.90: a web app whose team was + # deleted appears in no listing at all -- not unscoped, not under team_id=0 -- while + # remaining published, because a web app cannot be deleted. So a recreated team + # cannot get its launcher back and the name stays spent. Say so rather than retrying + # somewhere it provably is not. + if "409" not in str(exc) and "already exists" not in str(exc).lower(): + raise + found = self._link_app_in_team(team, title) + if not found: + raise FleetError( + f"the MDM already has a web app named {title!r} but will not show it. A web app cannot be " + "deleted, and it outlives the team it was assigned to, so a team that was deleted and " + "recreated leaves the name taken. First look in this team for a web app with an empty " + "display name: a run that stopped between publishing and naming leaves one, and giving it " + f"the display name {title!r} in the MDM lets this run reuse it. If there is none, the name " + "is spent -- give this deployment a different launcher title, or a host of its own." + ) from exc + LOGGER.info("Launcher web app %s is already published as %r, reusing it", found, title) + return found + + package = str(created.get("app_store_id") or created.get("package_name") or "") + if not package: + raise FleetError(f"the MDM did not name the web app it created: {created}") + LOGGER.info("Launcher web app %s points at %s", package, url) + return package + + @staticmethod + def _published_title(title: str, url: str) -> str: + """The title this deployment publishes under, carrying the deployment's name + + This is what the launcher icon reads on the device, so it is the deployment's name and + not an identifier: one instance per unit means the deployment is the useful half of it. + Its first DNS label, not the whole host, because Google refuses a web app title of 30 + characters or more and a full host rarely fits. + """ + name = (urlparse(url).hostname or "").removeprefix("mtls.").split(".")[0] + room = MAX_WEB_APP_TITLE - len(title) - len(" ()") + if not name or room <= 0: + return title[:MAX_WEB_APP_TITLE] + return f"{title} ({name[:room]})" + + def _link_app_in_team(self, team: int, title: str) -> str: + """This team's published web app of that name, or empty if it has none + + Scoped to the one team on purpose. Searching every team returns another deployment's app, + whose url points at another deployment and cannot be read to find that out. + """ + query = urlencode({"team_id": team, "available_for_install": "true"}) + for existing in self._call("GET", f"/api/latest/fleet/software/titles?{query}").get("software_titles", []): + package = (existing.get("app_store_app") or {}).get("app_store_id", "") + named = title in (existing.get("display_name"), existing.get("name")) + if package.startswith("com.google.enterprise.webapp.") and named: + return str(package) + return "" + + def ensure_authority(self, name: str, scep_url: str, challenge: str) -> int: + """The SCEP CA this deployment is, created if the MDM does not have it yet + + Pointing the MDM at a SCEP server is MDM configuration, not protocol, so there is no + standard for it and every MDM words it differently. Fleet happens to expose it, so here + it is one less thing for an operator to get wrong by hand. + + An existing one is repointed rather than left alone: the name is ours, so a drifted URL + means this deployment moved, not that somebody else owns it. And a challenge is always + sent when there is one: RASENMAEHER makes a new one for every enrolment window, and Fleet + never hands the old one back to compare against. + """ + authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) + match = [a for a in authorities if a.get("name") == name] + if match: + authority_id = int(match[0]["id"]) + # The listing does not carry the url, only the detail does, so compare against the + # detail. Reading the url off the listing leaves it None forever, which turns every + # run into a repoint of something already pointing at us. + detail = self._call("GET", f"/api/latest/fleet/certificate_authorities/{authority_id}") + if detail.get("url") == scep_url and not challenge: + return authority_id + # The challenge is never logged. No name in the body: Fleet reads a name on a PATCH as + # a rename and then refuses it as a conflict with the authority's own existing name, + # so sending it turns every update into a 409. + LOGGER.info("Updating certificate authority %s at %s", name, scep_url) + proxy = {"url": scep_url, "challenge": challenge} if challenge else {"url": scep_url} + self._call( + "PATCH", f"/api/latest/fleet/certificate_authorities/{authority_id}", {"custom_scep_proxy": proxy} + ) + return authority_id + + LOGGER.info("Creating certificate authority %s -> %s", name, scep_url) + created = self._call( + "POST", + "/api/latest/fleet/certificate_authorities", + {"custom_scep_proxy": {"name": name, "url": scep_url, "challenge": challenge}}, + ) + body = created.get("certificate_authority") or created + return int(body["id"]) + + def ensure_certificate(self, team: int, name: str, subject: str, authority: str, force: bool = False) -> int: + """The template the MDM fills in per device, and asks us to sign + + There is no update in place, so a changed subject is delete then create. The name is kept + because it becomes the Android keystore alias, and a device already holding a key under one + alias will not accept a second. + + force exists because the subject is filled in when a device ENROLS, and a device enrols + before anyone has named it -- the host does not exist to be named until then. That first + attempt fails, and Fleet never retries a failed certificate on its own. Recreating the + template is what asks again, so it is how a named host finally gets its certificate. + """ + authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) + match = [a for a in authorities if a.get("name") == authority] + if not match: + known = ", ".join(sorted(str(a.get("name")) for a in authorities)) or "none" + raise FleetError(f"no certificate authority named {authority!r}; the MDM has: {known}") + authority_id = int(match[0]["id"]) + + existing = self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []) + for template in existing: + if template.get("name") != name: + continue + if ( + not force + and template.get("subject_name") == subject + and int(template.get("certificate_authority_id", 0)) == authority_id + ): + return int(template["id"]) + self._call("DELETE", f"/api/latest/fleet/certificates/{template['id']}?team_id={team}") + LOGGER.info("Replacing certificate template %s, so it is asked for again", name) + + created = self._call( + "POST", + "/api/latest/fleet/certificates", + {"name": name, "team_id": team, "certificate_authority_id": authority_id, "subject_name": subject}, + ) + LOGGER.info("Certificate template %s asks for %s", name, subject) + return int(created["id"]) + + def hosts_awaiting_certificate(self, team: int, name: str) -> list[int]: + """Hosts that were named after they enrolled, and so have no certificate + + The subject is filled in when a device ENROLS, and a device enrols before anyone has named + it -- there is no host to name until it does. That first attempt fails, and nothing retries + it. These are the hosts for which asking again would now work: named, and still refused. + + Asking again is not free, because it re-asks every device in the group, so this exists to + keep that to the occasions when it would change something. + """ + hosts = self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] + waiting = [] + for host in hosts: + host_id = int(host["id"]) + detail = self._call("GET", f"/api/latest/fleet/hosts/{host_id}").get("host") or {} + profiles = (detail.get("mdm") or {}).get("profiles") or [] + if not any(p.get("name") == name and p.get("status") == "failed" for p in profiles): + continue + mapping = self._call("GET", f"/api/latest/fleet/hosts/{host_id}/device_mapping").get("device_mapping") or [] + if any(entry.get("email") for entry in mapping): + waiting.append(host_id) + return waiting + + # --- the whole statement -------------------------------------------------- + + def apply( + self, + team_name: str, + template: MdmTemplate, + force_policy: bool = False, + force_certificate: bool = False, + scep_url: str = "", + challenge: str = "", + link_package: str = "", + ) -> dict[str, Any]: + """State everything the template says, in the order that actually works + + The policy goes in BEFORE the apps: a permission grant only applies to an app that + installs while it is already in force, and the key selection rules are what make the + certificate visible to anything at all. Both have to be true before a device joins, + because that is the only moment apps install. + + Given scep_url, the certificate authority is created too, so a fresh deployment needs + nothing typed into Fleet by hand. Without it the authority must already be there, which + is the case for an MDM we cannot create one in. + + Given link_package, that launcher is assigned instead of looking one up or publishing one. + """ + team = self.team_id(team_name) + if template.certificate: + if scep_url: + self.ensure_authority(template.certificate.authority, scep_url, challenge) + self.ensure_certificate( + team, + template.certificate.name, + template.certificate.subject, + template.certificate.authority, + force=force_certificate, + ) + self.ensure_policy(team, template.policy, force=force_policy) + + packages = [app.package for app in template.apps] + preinstall = list(template.preinstall_packages) + if template.link_app: + link = link_package or self.ensure_link_app(team, template.link_app.title, template.link_app.url) + packages.append(link) + preinstall.append(link) + + assigned = self.assign_apps(team, packages, preinstall) + if template.link_app: + # Fleet lists a new web app under its package name until a device reports it, and the + # lookup that keeps a re-run from publishing another permanent app goes by title. + self._call( + "PATCH", + f"/api/latest/fleet/software/titles/{assigned[link]}/app_store_app", + { + "team_id": team, + "display_name": self._published_title(template.link_app.title, template.link_app.url), + }, + ) + for app in template.apps: + if app.config: + self.set_app_config(team, app.package, app.config) + return { + "team_id": team, + "assigned": sorted(assigned), + "preinstall": sorted(preinstall), + "link": link if template.link_app else "", + } + + def apply_preparation( + self, team_name: str, template: MdmTemplate, link_package: str, force_policy: bool = False + ) -> dict[str, Any]: + """The team devices enrol into and get named in, before they move to the certificate team + + Everything but the certificate, so nothing is asked for before the device has its name. + The launcher has to be the very package the certificate team holds: apps install only at + enrolment, so a device moving to a team with another launcher package has it uninstalled + and never gets the other one. + """ + return self.apply( + team_name, + dataclasses.replace(template, certificate=None), + force_policy=force_policy, + link_package=link_package, + ) diff --git a/src/odmdm_fleet/icon.py b/src/odmdm_fleet/icon.py new file mode 100644 index 0000000..7584ff8 --- /dev/null +++ b/src/odmdm_fleet/icon.py @@ -0,0 +1,31 @@ +"""A launcher icon, generated rather than shipped + +Google will not publish a managed web app without one, and a web app it has not published is +accepted by the MDM but reports NOT_FOUND on every device that tries to install it. Square and at +least 512x512 are enforced. Generating it avoids carrying a binary in the repository for something +no one will look at twice. +""" + +import struct +import zlib + + +def launcher_icon(size: int = 512) -> bytes: + """A plain square PNG, no dependencies""" + + def chunk(tag: bytes, data: bytes) -> bytes: + return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) + + rows = [] + for y in range(size): + pixels = bytearray() + for x in range(size): + inside = abs(x - size // 2) < size // 3 and size // 6 < y < size * 5 // 6 + pixels += bytes((0x0D, 0x47, 0xA1) if inside else (0x10, 0x1A, 0x24)) + rows.append(b"\x00" + bytes(pixels)) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + + chunk(b"IEND", b"") + ) diff --git a/src/odmdm_fleet/template.py b/src/odmdm_fleet/template.py new file mode 100644 index 0000000..9a7a469 --- /dev/null +++ b/src/odmdm_fleet/template.py @@ -0,0 +1,162 @@ +"""What a deployment's devices need, read from a file rather than known here + +This module deliberately contains no package name, no managed-configuration key and no product +of any kind. What a deployment installs is a property of that deployment, not of the connector, +so the whole answer arrives as a document an operator supplies and this module only validates it +and fills in the deployment's own values. + +The placeholders are the only vocabulary shared with the document: + +``{domain}`` the deployment's DNS name +``{mtls_url}`` where a client certificate is expected, ``https://mtls.`` +``{key_alias}`` the Android keystore alias the certificate lands under, which is the name of the + MDM certificate template, because installing a second key under an existing alias + fails +""" + +import json +import logging +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +LOGGER = logging.getLogger(__name__) + + +class TemplateError(ValueError): + """The document is not something we can act on""" + + +@dataclass(frozen=True) +class App: + """One application the deployment wants on its devices""" + + package: str + #: Install it as part of enrolment rather than leaving it available on demand. On managed + #: Android this is the only automatic path, and it applies at enrolment only. + preinstall: bool = True + #: Managed configuration for the app, already substituted + config: dict[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class Certificate: + """The certificate the MDM asks us for on a device's behalf + + ``subject`` is identity configuration, not cosmetics: its common name becomes the device's + callsign. It lives here so it is reviewed and deployed like everything else, rather than typed + into a console once and forgotten. + + ``name`` becomes the Android keystore alias, and installing a second key under an existing + alias fails, so it is per deployment rather than per device. + """ + + name: str + subject: str + authority: str + + +@dataclass(frozen=True) +class LinkApp: + """A managed web app, so the deployment has an icon on the launcher""" + + title: str + url: str + + +@dataclass(frozen=True) +class MdmTemplate: + """Everything to state to an MDM about one deployment""" + + apps: tuple[App, ...] + policy: dict[str, Any] + link_app: LinkApp | None = None + certificate: Certificate | None = None + + @property + def preinstall_packages(self) -> tuple[str, ...]: + return tuple(app.package for app in self.apps if app.preinstall) + + +def _strip_comments(value: Any) -> Any: + """Drop keys beginning with an underscore, at any depth + + The document carries the reasoning for what it asks for, because the reasoning is the part + that was expensive to learn. None of it is for the MDM: an annotation left in an app's + configuration would be pushed to the device as a real setting. + """ + if isinstance(value, dict): + return {key: _strip_comments(item) for key, item in value.items() if not str(key).startswith("_")} + if isinstance(value, list): + return [_strip_comments(item) for item in value] + return value + + +def _substitute(value: Any, values: dict[str, str]) -> Any: + """Fill the placeholders wherever they appear, at any depth""" + if isinstance(value, str): + for key, replacement in values.items(): + value = value.replace("{" + key + "}", replacement) + return value + if isinstance(value, dict): + return {key: _substitute(item, values) for key, item in value.items()} + if isinstance(value, list): + return [_substitute(item, values) for item in value] + return value + + +def load(path: Path, domain: str, key_alias: str) -> MdmTemplate: + """Read the document and fill in this deployment's values + + Raises TemplateError rather than letting a malformed document reach the MDM, because a half + applied template is worse than none: apps install at enrolment only, so a device that joins + against a broken one has to be enrolled again. + """ + try: + raw = json.loads(path.read_text(encoding="utf-8")) + except OSError as exc: + raise TemplateError(f"cannot read {path}: {exc}") from exc + except ValueError as exc: + raise TemplateError(f"{path} is not valid JSON: {exc}") from exc + if not isinstance(raw, dict): + raise TemplateError(f"{path} must contain an object") + + values = {"domain": domain, "mtls_url": f"https://mtls.{domain}", "key_alias": key_alias} + raw = _strip_comments(_substitute(raw, values)) + + apps: list[App] = [] + for entry in raw.get("apps", []): + if not isinstance(entry, dict) or not entry.get("package"): + raise TemplateError(f"every app needs a package, got {entry!r}") + config = entry.get("config", {}) + if not isinstance(config, dict): + raise TemplateError(f"config for {entry['package']} must be an object") + apps.append(App(package=str(entry["package"]), preinstall=bool(entry.get("preinstall", True)), config=config)) + if not apps: + raise TemplateError("the template installs nothing; at least one app is required") + + policy = raw.get("policy", {}) + if not isinstance(policy, dict): + raise TemplateError("policy must be an object") + + link = None + if raw.get("link_app"): + entry = raw["link_app"] + if not isinstance(entry, dict) or not entry.get("title") or not entry.get("url"): + raise TemplateError("link_app needs a title and a url") + link = LinkApp(title=str(entry["title"]), url=str(entry["url"])) + + LOGGER.info( + "Template names %s apps, %s of them installed at enrolment", len(apps), len([a for a in apps if a.preinstall]) + ) + certificate = None + if raw.get("certificate"): + entry = raw["certificate"] + missing = [key for key in ("name", "subject", "authority") if not entry.get(key)] + if not isinstance(entry, dict) or missing: + raise TemplateError(f"certificate needs name, subject and authority; missing {missing}") + certificate = Certificate( + name=str(entry["name"]), subject=str(entry["subject"]), authority=str(entry["authority"]) + ) + + return MdmTemplate(apps=tuple(apps), policy=policy, link_app=link, certificate=certificate) diff --git a/tests/test_fleet.py b/tests/test_fleet.py new file mode 100644 index 0000000..d0982c9 --- /dev/null +++ b/tests/test_fleet.py @@ -0,0 +1,525 @@ +"""The MDM dialect, against a stubbed transport + +What matters here is the ORDER and the restraint: the policy has to be in force before anything +installs, and an unchanged policy must not be re-uploaded, because a policy rewritten on every +pass never settles long enough for the device to finish installing anything. +""" + +import json +import re +from typing import Any + +import httpx +import pytest + +from odmdm_fleet.fleet import FleetError, FleetMdm +from odmdm_fleet.icon import launcher_icon +from odmdm_fleet.template import App, Certificate, LinkApp, MdmTemplate + +TEMPLATE = MdmTemplate( + apps=( + App(package="com.example.one", preinstall=True, config={"k": "v"}), + App(package="com.example.two", preinstall=False), + ), + policy={"defaultPermissionPolicy": "GRANT"}, +) + + +class _Fleet: + """A Fleet that records what it was told, in order""" + + def __init__(self) -> None: + self.calls: list[tuple[str, str]] = [] + self.titles: list[dict[str, Any]] = [] + self.profiles: list[dict[str, Any]] = [] + self.certificates: list[dict[str, Any]] = [] + self.hosts: list[dict[str, Any]] = [] + self.web_apps: list[dict[str, Any]] = [] + self.authorities: list[dict[str, Any]] = [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + self._next_id = 100 + + def handler(self, request: httpx.Request) -> httpx.Response: + path = request.url.path + self.calls.append((request.method, path)) + if path.endswith("/hosts") and request.method == "GET": + return httpx.Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts]}) + if path.endswith("/device_mapping"): + which = int(path.split("/hosts/")[1].split("/")[0]) + found = next(h for h in self.hosts if h["id"] == which) + return httpx.Response(200, json={"device_mapping": found.get("device_mapping") or []}) + if "/hosts/" in path and request.method == "GET": + which = int(path.rsplit("/", 1)[-1]) + found = next(h for h in self.hosts if h["id"] == which) + return httpx.Response(200, json={"host": {"mdm": {"profiles": found.get("profiles") or []}}}) + if path.endswith("/certificate_authorities") and request.method == "GET": + # Fleet's listing omits the url; only the detail carries it. Mirrored so a check + # that reads the url off the listing fails here too. + return httpx.Response( + 200, + json={ + "certificate_authorities": [{k: v for k, v in a.items() if k != "url"} for a in self.authorities] + }, + ) + if "/certificate_authorities/" in path and request.method == "GET": + which = int(path.rsplit("/", 1)[-1]) + matching = [a for a in self.authorities if a["id"] == which] + return httpx.Response(200, json=matching[0] if matching else {}) + if path.endswith("/certificate_authorities") and request.method == "POST": + body = json.loads(request.content)["custom_scep_proxy"] + made = {"id": 55, "name": body["name"], "url": body["url"]} + self.authorities.append(made) + return httpx.Response(200, json={"certificate_authority": made}) + if "/certificate_authorities/" in path and request.method == "PATCH": + which = int(path.rsplit("/", 1)[-1]) + body = json.loads(request.content)["custom_scep_proxy"] + if "name" in body: + # Fleet reads a name on a PATCH as a rename and refuses it as a conflict with + # the authority's own name. Measured against a live Fleet 4.90.1. + return httpx.Response(409, json={"message": "Conflict"}) + for authority in self.authorities: + if authority["id"] == which: + authority.update(body) + return httpx.Response(200, json={}) + if path.endswith("/certificates") and request.method == "GET": + return httpx.Response(200, json={"certificates": self.certificates}) + if path.endswith("/certificates") and request.method == "POST": + body = json.loads(request.content) + made = { + "id": 27, + "name": body["name"], + "subject_name": body["subject_name"], + "certificate_authority_id": body["certificate_authority_id"], + } + self.certificates.append(made) + return httpx.Response(200, json=made) + if "/certificates/" in path and request.method == "DELETE": + gone = int(path.rsplit("/", 1)[-1]) + self.certificates = [c for c in self.certificates if c["id"] != gone] + return httpx.Response(200, json={}) + if path == "/api/latest/fleet/teams" and request.method == "GET": + return httpx.Response(200, json={"teams": [{"id": 7, "name": "rmscep"}, {"id": 8, "name": "prep"}]}) + if path.endswith("/software/titles"): + # Fleet scopes the listing to one team. A stub that ignored team_id would let a + # lookup find another team's app and call that a pass. + wanted_team = request.url.params.get("team_id") + listed = [t for t in self.titles if wanted_team is None or str(t.get("team_id")) == str(wanted_team)] + return httpx.Response(200, json={"software_titles": listed}) + if path.endswith("/software/web_apps"): + # Publishing the SAME url twice yields TWO package names: observed against the real + # Fleet, where one url gave x023e... and then xb017.... Google does not dedupe by + # url, which is what makes every re-run leave a permanent orphan behind. + body = request.content.decode("utf-8", "replace") + url_match = re.search(r'name="url"\r?\n\r?\n([^\r\n]+)', body) + title_match = re.search(r'name="title"\r?\n\r?\n([^\r\n]+)', body) + wanted = url_match.group(1) if url_match else "" + asked = title_match.group(1) if title_match else "" + if len(asked) >= 30: + # Google refuses a web app title of 30 characters or more, as a bare 400. + return httpx.Response(400, json={"message": "Couldn't create. Please check the provided data"}) + if any(a["title"] == asked for a in self.web_apps): + # Fleet refuses a name already published to the enterprise, whatever team it is + # in and even if its team is gone. Publishing cannot be undone. + return httpx.Response(409, json={"message": "Web app with this name already exists in this fleet"}) + self._next_id += 1 + pkg = f"com.google.enterprise.webapp.x{self._next_id:08x}" + self.web_apps.append( + {"app_store_id": pkg, "url": wanted, "title": title_match.group(1) if title_match else ""} + ) + return httpx.Response(200, json={"app_store_id": pkg}) + if path.endswith("/app_store_app") and request.method == "PATCH": + body = json.loads(request.read()) + title_id = int(path.split("/")[-2]) + for title in self.titles: + if title["id"] == title_id and "display_name" in body: + title["display_name"] = body["display_name"] + return httpx.Response(200, json={"app_store_app": {}}) + if path.endswith("/software/app_store_apps"): + # This is what puts an app in a team. A new web app is listed under its package name, + # not its title, until a device reports it: seen on the real Fleet. + body = json.loads(request.read()) + self._next_id += 1 + self.titles.append( + { + "id": self._next_id, + "name": body["app_store_id"], + "display_name": "", + "team_id": body.get("team_id"), + "app_store_app": {"app_store_id": body["app_store_id"]}, + } + ) + return httpx.Response(200, json={"software_title_id": self._next_id}) + if path.endswith("/configuration_profiles"): + if request.method == "GET": + return httpx.Response(200, json={"profiles": list(self.profiles)}) + # An upload the MDM keeps, so a second pass can see it is already there. Without + # this the adapter is right to upload again: a profile that has gone missing must + # be restored whatever we remember pushing. + self.profiles.append({"name": "rmscep-policy", "profile_uuid": f"uuid-{len(self.profiles)}"}) + return httpx.Response(200, json={}) + if "/configuration_profiles/" in path and request.method == "DELETE": + self.profiles.clear() + return httpx.Response(200, json={}) + if "/app_store_app" in path or path.endswith("/setup_experience/software"): + return httpx.Response(200, json={}) + return httpx.Response(200, json={}) + + +def _mdm(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> FleetMdm: + transport = httpx.MockTransport(fleet.handler) + monkeypatch.setattr(httpx, "request", lambda m, u, **kw: httpx.Client(transport=transport).request(m, u, **kw)) + monkeypatch.setattr(httpx, "post", lambda u, **kw: httpx.Client(transport=transport).post(u, **kw)) + return FleetMdm("https://mdm.test", "token") + + +def test_the_policy_lands_before_anything_installs(monkeypatch: pytest.MonkeyPatch) -> None: + """A permission grant only applies to an app that installs while it is already in force + + Land it late and the device comes up facing a permission wizard, with a certificate no app + is allowed to see. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + + paths = [p for _, p in fleet.calls] + profile = next(i for i, p in enumerate(paths) if p.endswith("/configuration_profiles")) + install = next(i for i, p in enumerate(paths) if p.endswith("/software/app_store_apps")) + assert profile < install, f"policy must precede installs, got {paths}" + + +def test_only_the_chosen_apps_install_at_enrolment(monkeypatch: pytest.MonkeyPatch) -> None: + """The rest stay available on demand rather than lengthening the enrolment burst""" + fleet = _Fleet() + result = _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + assert result["preinstall"] == ["com.example.one"] + assert len(result["assigned"]) == 2 + + +def test_an_unchanged_policy_is_not_rewritten(monkeypatch: pytest.MonkeyPatch) -> None: + """Measured: a policy rewritten every pass never settles and nothing ever installs""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", TEMPLATE) + uploads_after_first = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + mdm.apply("rmscep", TEMPLATE) + uploads_after_second = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + assert uploads_after_second == uploads_after_first, "the same policy must not be uploaded twice" + + +def test_force_reaches_a_host_that_just_joined(monkeypatch: pytest.MonkeyPatch) -> None: + """A profile is delivered when the PROFILE changes, not when a host arrives""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", TEMPLATE) + before = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + mdm.apply("rmscep", TEMPLATE, force_policy=True) + after = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + assert after == before + 1 + + +def test_a_refusal_is_reported_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None: + """Applying half a template is worse than applying none""" + transport = httpx.MockTransport(lambda request: httpx.Response(403, text="nope")) + monkeypatch.setattr(httpx, "request", lambda m, u, **kw: httpx.Client(transport=transport).request(m, u, **kw)) + with pytest.raises(FleetError): + FleetMdm("https://mdm.test", "token").apply("rmscep", TEMPLATE) + + +def test_the_launcher_icon_is_a_valid_png() -> None: + """Without one the web app is accepted and then never published, and every install says NOT_FOUND""" + png = launcher_icon() + assert png[:8] == b"\x89PNG\r\n\x1a\n" + width = int.from_bytes(png[16:20], "big") + height = int.from_bytes(png[20:24], "big") + assert width == height == 512, "square and at least 512x512 is enforced" + + +def test_the_link_app_is_offered_alongside_the_others(monkeypatch: pytest.MonkeyPatch) -> None: + """It is a browser shortcut, so it only works if the browser is installed too""" + fleet = _Fleet() + monkeypatch.setattr(FleetMdm, "ensure_link_app", lambda self, team, title, url: "com.google.enterprise.webapp.test") + with_link = MdmTemplate(apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp("Deploy App", "https://x/")) + result = _mdm(fleet, monkeypatch).apply("rmscep", with_link) + assert "com.google.enterprise.webapp.test" in result["preinstall"] + + +def test_the_certificate_template_is_stated_before_anything_else(monkeypatch: pytest.MonkeyPatch) -> None: + """Its subject names the device, which becomes its callsign + + So it is configuration that gets reviewed and deployed, not something typed into a console. + """ + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority="RMSCEP"), + ) + _mdm(fleet, monkeypatch).apply("rmscep", with_cert) + paths = [p for _, p in fleet.calls] + assert any(p.endswith("/certificates") for p in paths), "the template must be stated" + cert = next(i for i, p in enumerate(paths) if p.endswith("/certificates")) + install = next(i for i, p in enumerate(paths) if p.endswith("/software/app_store_apps")) + assert cert < install + + +def test_an_unknown_authority_is_named_rather_than_guessed(monkeypatch: pytest.MonkeyPatch) -> None: + """A template pointing at an authority that is not there would issue nothing, silently""" + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR", authority="NOT-THERE"), + ) + with pytest.raises(FleetError, match="NOT-THERE"): + _mdm(fleet, monkeypatch).apply("rmscep", with_cert) + + +def test_an_unchanged_certificate_template_is_left_alone(monkeypatch: pytest.MonkeyPatch) -> None: + """Recreating it re-asks every device in the team, so it is not done for nothing""" + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority="RMSCEP"), + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", with_cert) + before = len([1 for method, path in fleet.calls if path.endswith("/certificates") and method == "POST"]) + mdm.apply("rmscep", with_cert) + after = len([1 for method, path in fleet.calls if path.endswith("/certificates") and method == "POST"]) + assert after == before, "an unchanged template must not be recreated" + + +def test_forcing_the_certificate_asks_again(monkeypatch: pytest.MonkeyPatch) -> None: + """The ordinary recovery: a device enrols before anyone can name it, so the first ask fails + + Fleet never retries a failed certificate, and the template is what asks. Recreating it is the + only way a host named after it enrolled ever gets one. + """ + fleet = _Fleet() + with_cert = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority="RMSCEP"), + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", with_cert) + fleet.calls.clear() + mdm.apply("rmscep", with_cert, force_certificate=True) + + assert any(method == "DELETE" and "/certificates/" in path for method, path in fleet.calls) + assert any(method == "POST" and path.endswith("/certificates") for method, path in fleet.calls) + assert len(fleet.certificates) == 1, "the template is replaced, not duplicated" + assert fleet.certificates[0]["name"] == "rmscep", "the keystore alias has to stay the same" + + +def _host(host_id: int, status: str, named: bool) -> dict[str, Any]: + return { + "id": host_id, + "profiles": [{"name": "rmscep", "status": status}], + "device_mapping": [{"email": "OTTER1@CODE", "source": "mdm_idp_accounts"}] if named else [], + } + + +def test_a_host_named_after_enrolment_is_waiting(monkeypatch: pytest.MonkeyPatch) -> None: + """Named, and still refused: asking again would now work""" + fleet = _Fleet() + fleet.hosts = [_host(1, "failed", named=True)] + assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [1] + + +def test_a_host_nobody_has_named_is_not_waiting(monkeypatch: pytest.MonkeyPatch) -> None: + """Asking again changes nothing until somebody names it, and re-asking is not free""" + fleet = _Fleet() + fleet.hosts = [_host(2, "failed", named=False)] + assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [] + + +def test_a_host_that_already_has_its_certificate_is_not_waiting(monkeypatch: pytest.MonkeyPatch) -> None: + """Otherwise every pass would re-ask the whole group forever""" + fleet = _Fleet() + fleet.hosts = [_host(3, "verified", named=True)] + assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [] + + +def _with_cert(authority: str = "RMSCEP") -> MdmTemplate: + """A template that asks for a certificate, which is what drags the authority in""" + return MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority=authority), + ) + + +def test_a_fresh_mdm_gets_the_authority_created(monkeypatch: pytest.MonkeyPatch) -> None: + """Pointing the MDM at us is configuration, and Fleet lets us do it, so nobody should type it + + Without this a deployment is not set up by running one command: it is one command plus a + console, and the console step is the one people get wrong. + """ + fleet = _Fleet() + fleet.authorities = [] + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://new.test/scep", challenge="not-a-secret") + created = [c for c in fleet.calls if c == ("POST", "/api/latest/fleet/certificate_authorities")] + assert created, "the authority should have been created" + assert fleet.authorities[0]["url"] == "https://new.test/scep" + + +def test_an_authority_already_pointing_at_us_is_left_alone(monkeypatch: pytest.MonkeyPatch) -> None: + """Without a challenge to hand over, rewriting it is churn on something every device depends on""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://deployment.test/scep") + touched = [c for c in fleet.calls if c[0] in ("POST", "PATCH") and "certificate_authorities" in c[1]] + assert not touched, "an authority already pointing at us must not be rewritten" + + +def test_a_new_windows_challenge_reaches_an_authority_already_pointing_at_us( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Every enrolment window has a new challenge, and Fleet never shows the old one to compare""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply( + "rmscep", _with_cert(), scep_url="https://deployment.test/scep", challenge="new-window" + ) + assert len(fleet.authorities) == 1 + assert fleet.authorities[0]["challenge"] == "new-window" + assert fleet.authorities[0]["url"] == "https://deployment.test/scep" + + +def test_a_drifted_authority_is_repointed_not_duplicated(monkeypatch: pytest.MonkeyPatch) -> None: + """The name is ours, so a different URL means the deployment moved + + Creating a second one would leave the certificate template pointing at whichever the lookup + happened to find first. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") + assert len(fleet.authorities) == 1, "a drifted authority must be repointed, not duplicated" + assert fleet.authorities[0]["url"] == "https://moved.test/scep" + + +def test_without_a_scep_url_the_authority_must_already_exist(monkeypatch: pytest.MonkeyPatch) -> None: + """The path for an MDM we cannot create one in: state what is there, or say what is missing""" + fleet = _Fleet() + fleet.authorities = [] + with pytest.raises(FleetError, match="RMSCEP"): + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + + +def test_repointing_does_not_try_to_rename(monkeypatch: pytest.MonkeyPatch) -> None: + """Fleet refuses a PATCH that carries a name, as a conflict with the name already there + + Found against a live Fleet: every repoint answered 409 and no deployment could be moved to + a new responder without deleting the authority by hand. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") + assert fleet.authorities[0]["url"] == "https://moved.test/scep", "the repoint must have gone through" + + +def test_applying_twice_publishes_one_web_app(monkeypatch: pytest.MonkeyPatch) -> None: + """A re-run reuses the launcher instead of leaving another permanent one behind + + Google does not dedupe by url: the same url published twice came back as two package names, + so every mdm-apply added another launcher to the team. Fleet cannot delete a web app, so each + one is permanent, and the third publish of a name is refused outright. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://same.test/") + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", template) + mdm.apply("rmscep", template) + + assert len(fleet.web_apps) == 1, f"the re-run must not publish again, got {[a['title'] for a in fleet.web_apps]}" + launchers = [t for t in fleet.titles if t["display_name"].startswith("Deploy App")] + assert len(launchers) == 1, "the team must end up with one launcher, not one per run" + + +def test_the_preparation_team_holds_the_same_launcher_and_no_certificate(monkeypatch: pytest.MonkeyPatch) -> None: + """A device moving from the preparation team keeps the apps it enrolled with, and only those + + So the launcher has to be the same package in both teams. One of its own is another package, + which the move uninstalls and nothing installs again: the phone loses its Deploy App icon. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + link_app=LinkApp(title="Deploy App", url="https://same.test/"), + certificate=Certificate(name="rmscep", subject="CN=$VAR", authority="RMSCEP"), + ) + mdm = _mdm(fleet, monkeypatch) + main = mdm.apply("rmscep", template) + fleet.calls.clear() + prep = mdm.apply_preparation("prep", template, main["link"]) + + assert len(fleet.web_apps) == 1, "the preparation team must not publish a launcher of its own" + assert main["link"] in prep["assigned"] + assert prep["assigned"] == main["assigned"] + assert not [p for _, p in fleet.calls if p.endswith("/certificates")], "nothing is asked for before the name" + + +def test_a_wiped_team_says_what_is_wrong_instead_of_just_409(monkeypatch: pytest.MonkeyPatch) -> None: + """A name published to a team that no longer exists must fail legibly + + A full fresh run deletes the team and makes it again. The web app outlives it, because Fleet + cannot delete one, so publishing the same name answers 409. Whether Fleet still lists an app + whose team is gone is not something this stub can decide, so the contract tested here is the + one that holds either way: when it cannot be found, the operator is told the name is taken + and what to do about it, rather than being handed a bare conflict. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://same.test/") + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", template) + published = fleet.web_apps[-1]["app_store_id"] + + # The team is deleted and recreated: its software titles go with it, the web app does not. + fleet.titles = [t for t in fleet.titles if (t.get("app_store_app") or {}).get("app_store_id") != published] + + with pytest.raises(FleetError) as caught: + mdm.apply("rmscep", template) + said = str(caught.value) + assert "Deploy App (same)" in said, f"it must name the title that is taken, said: {said}" + assert "deleted" in said.lower() or "cannot be deleted" in said.lower(), f"it must say why: {said}" + assert "display name" in said.lower(), f"it must offer the recoverable case before giving up: {said}" + assert len(fleet.web_apps) == 1, "it must not have published a second app before failing" + + +def test_the_launcher_points_at_this_deployment_not_the_last_one(monkeypatch: pytest.MonkeyPatch) -> None: + """The web app is identified by the host it serves, never by a bare title + + Fleet cannot read, change or delete a web app's url, so reusing one because the title matched + kept a decommissioned deployment's link and handed every device an icon that opened a host + which no longer existed. Everything else about the apply was correct, which is what made it + so quiet. The deployment that replaced it reused the team name too, so the team is no help: + the host in the title is what tells the two apart. + """ + fleet = _Fleet() + template = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://old.test/") + ) + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", template) + first = fleet.web_apps[-1]["app_store_id"] + + moved = MdmTemplate( + apps=TEMPLATE.apps, policy=TEMPLATE.policy, link_app=LinkApp(title="Deploy App", url="https://new.test/") + ) + mdm.apply("rmscep", moved) + second = fleet.web_apps[-1]["app_store_id"] + + assert fleet.web_apps[-1]["url"] == "https://new.test/", "the moved deployment must publish its own url" + assert second != first, "same title, different url: it must not reuse the old app" + + +def test_the_launcher_title_names_the_deployment_and_fits() -> None: + """Google refuses a web app title of 30 characters or more, and a full host rarely fits""" + title = FleetMdm._published_title("Deploy App", "https://mtls.quiet-otter.example.fi/") + assert title == "Deploy App (quiet-otter)" + long_name = FleetMdm._published_title("Deploy App", "https://mtls.thoughtful-hippopotamus.example.org/") + assert len(long_name) < 30 + assert long_name.startswith("Deploy App (thoughtful") diff --git a/tests/test_template.py b/tests/test_template.py new file mode 100644 index 0000000..9ce0ad0 --- /dev/null +++ b/tests/test_template.py @@ -0,0 +1,101 @@ +"""The template document + +What a deployment installs is data, not code. These tests pin that the connector stays ignorant +of it and that a malformed document is refused before it can reach an MDM. +""" + +import json +from pathlib import Path + +import pytest + +from odmdm_fleet.template import TemplateError, load + +GOOD = { + "apps": [ + {"package": "com.example.one", "preinstall": True}, + { + "package": "com.example.two", + "preinstall": False, + "config": {"AutoSelectCertificateForUrls": ['{"pattern":"{mtls_url}","filter":{}}']}, + }, + ], + "link_app": {"title": "Deploy App", "url": "{mtls_url}/"}, + "policy": { + "choosePrivateKeyRules": [{"urlPattern": "{mtls_url}", "privateKeyAlias": "{key_alias}"}], + "defaultPermissionPolicy": "GRANT", + }, +} + + +def _write(tmp_path: Path, body: object) -> Path: + path = tmp_path / "template.json" + path.write_text(json.dumps(body), encoding="utf-8") + return path + + +def test_placeholders_are_filled_at_every_depth(tmp_path: Path) -> None: + """The document is written once and used against whatever deployment it is pointed at""" + template = load(_write(tmp_path, GOOD), domain="example.fi", key_alias="rmscep") + + assert template.preinstall_packages == ("com.example.one",) + inside_a_list = template.apps[1].config["AutoSelectCertificateForUrls"][0] + assert json.loads(inside_a_list)["pattern"] == "https://mtls.example.fi" + assert template.policy["choosePrivateKeyRules"][0]["urlPattern"] == "https://mtls.example.fi" + assert template.policy["choosePrivateKeyRules"][0]["privateKeyAlias"] == "rmscep" + assert template.link_app is not None + assert template.link_app.url == "https://mtls.example.fi/" + + +@pytest.mark.parametrize( + ("body", "because"), + [ + ({"apps": []}, "a template that installs nothing is a mistake, not a choice"), + ({"apps": [{"preinstall": True}]}, "an app with no package cannot be acted on"), + ({"apps": [{"package": "x", "config": []}]}, "config must be an object"), + ({"apps": [{"package": "x"}], "policy": []}, "policy must be an object"), + ({"apps": [{"package": "x"}], "link_app": {"title": "t"}}, "a link with no url is useless"), + ([], "the document must be an object"), + ], +) +def test_a_malformed_document_is_refused(tmp_path: Path, body: object, because: str) -> None: + """A half applied template is worse than none: apps install at enrolment only, so a device + that joined against a broken one has to be enrolled again, and its callsign is spent.""" + with pytest.raises(TemplateError): + load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") + + +def test_a_missing_file_is_refused(tmp_path: Path) -> None: + with pytest.raises(TemplateError): + load(tmp_path / "nope.json", domain="example.fi", key_alias="rmscep") + + +def test_not_json_is_refused(tmp_path: Path) -> None: + path = tmp_path / "template.json" + path.write_text("this is not json", encoding="utf-8") + with pytest.raises(TemplateError): + load(path, domain="example.fi", key_alias="rmscep") + + +def test_annotations_never_reach_the_device(tmp_path: Path) -> None: + """The document explains itself, and none of that explanation is a setting + + An annotation left in an app's configuration would be pushed to the phone as a real managed + configuration key. + """ + body = { + "_comment": "why this file exists", + "apps": [ + { + "_comment": "why this app", + "package": "com.example.one", + "config": {"_comment": "why this key", "real": "value", "nested": {"_x": 1, "keep": 2}}, + } + ], + "policy": {"_comment": "why this policy", "defaultPermissionPolicy": "GRANT"}, + "link_app": {"_comment": "why a link", "title": "Deploy App", "url": "{mtls_url}/"}, + } + template = load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") + assert template.apps[0].config == {"real": "value", "nested": {"keep": 2}} + assert template.policy == {"defaultPermissionPolicy": "GRANT"} + assert template.link_app is not None and template.link_app.title == "Deploy App" From 27bb4279694aad29d17dd63d0fe58b35d3670da7 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 00:02:36 +0200 Subject: [PATCH 002/104] feat: name the one phone waiting to be named --- src/odmdm_fleet/fleet.py | 28 ++++++++++++++++++++++++++-- tests/test_fleet.py | 25 +++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 07eec2f..9aa1b70 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -389,11 +389,35 @@ def hosts_awaiting_certificate(self, team: int, name: str) -> list[int]: profiles = (detail.get("mdm") or {}).get("profiles") or [] if not any(p.get("name") == name and p.get("status") == "failed" for p in profiles): continue - mapping = self._call("GET", f"/api/latest/fleet/hosts/{host_id}/device_mapping").get("device_mapping") or [] - if any(entry.get("email") for entry in mapping): + if self._name_of(host_id): waiting.append(host_id) return waiting + # --- naming --------------------------------------------------------------- + + def _name_of(self, host_id: int) -> str: + """The name a host was given, or empty if nobody has named it""" + mapping = self._call("GET", f"/api/latest/fleet/hosts/{host_id}/device_mapping").get("device_mapping") or [] + return next((str(entry["email"]) for entry in mapping if entry.get("email")), "") + + def name_the_waiting_host(self, team: int, callsign: str) -> int: + """Give the one unnamed host in the team its callsign + + Identical phones look identical here: brand and model, and an enrolment ID that nothing on + the phone shows. So the only host that can be named safely is the only one waiting. With + two waiting nobody can tell which is the phone in hand, and guessing puts the callsign on + somebody else's phone, so that is refused rather than picked. + """ + hosts = self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] + waiting = [int(host["id"]) for host in hosts if not self._name_of(int(host["id"]))] + if not waiting: + raise FleetError(f"no device in team {team} is waiting for a name: enrol the phone first") + if len(waiting) > 1: + raise FleetError(f"{len(waiting)} devices in team {team} wait for a name, so none was: enrol one at a time") + self._call("PUT", f"/api/latest/fleet/hosts/{waiting[0]}/device_mapping", {"email": callsign, "source": "idp"}) + LOGGER.info("Named host %s %s", waiting[0], callsign) + return waiting[0] + # --- the whole statement -------------------------------------------------- def apply( diff --git a/tests/test_fleet.py b/tests/test_fleet.py index d0982c9..d94fcd8 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -46,6 +46,8 @@ def handler(self, request: httpx.Request) -> httpx.Response: if path.endswith("/device_mapping"): which = int(path.split("/hosts/")[1].split("/")[0]) found = next(h for h in self.hosts if h["id"] == which) + if request.method == "PUT": + found["device_mapping"] = [json.loads(request.content)] return httpx.Response(200, json={"device_mapping": found.get("device_mapping") or []}) if "/hosts/" in path and request.method == "GET": which = int(path.rsplit("/", 1)[-1]) @@ -341,6 +343,29 @@ def test_a_host_that_already_has_its_certificate_is_not_waiting(monkeypatch: pyt assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [] +def test_the_only_waiting_phone_is_named(monkeypatch: pytest.MonkeyPatch) -> None: + """Enrol one, name it, enrol the next: phones already named are left alone""" + fleet = _Fleet() + fleet.hosts = [_host(1, "verified", named=True), _host(2, "failed", named=False)] + + assert _mdm(fleet, monkeypatch).name_the_waiting_host(8, "OTTER2") == 2 + + assert fleet.hosts[1]["device_mapping"] == [{"email": "OTTER2", "source": "idp"}] + assert fleet.hosts[0]["device_mapping"][0]["email"] == "OTTER1@CODE" + + +@pytest.mark.parametrize(("unnamed", "says"), [(0, "enrol the phone first"), (2, "one at a time")]) +def test_no_phone_is_named_unless_exactly_one_waits(monkeypatch: pytest.MonkeyPatch, unnamed: int, says: str) -> None: + """Identical phones are identical rows, and a guess names somebody else's phone""" + fleet = _Fleet() + fleet.hosts = [_host(1, "verified", named=True)] + [_host(10 + i, "failed", named=False) for i in range(unnamed)] + + with pytest.raises(FleetError, match=says): + _mdm(fleet, monkeypatch).name_the_waiting_host(8, "OTTER2") + + assert not [call for call in fleet.calls if call[0] == "PUT"] + + def _with_cert(authority: str = "RMSCEP") -> MdmTemplate: """A template that asks for a certificate, which is what drags the authority in""" return MdmTemplate( From f78632093d4cc79dffd807f74895dff7e1d3d3c0 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 00:02:36 +0200 Subject: [PATCH 003/104] feat: apply, plan and reconcile commands --- src/odmdm_fleet/config.py | 41 +++++++ src/odmdm_fleet/console.py | 228 +++++++++++++++++++++++++++++++++++++ tests/test_console.py | 150 ++++++++++++++++++++++++ 3 files changed, 419 insertions(+) create mode 100644 src/odmdm_fleet/config.py create mode 100644 src/odmdm_fleet/console.py create mode 100644 tests/test_console.py diff --git a/src/odmdm_fleet/config.py b/src/odmdm_fleet/config.py new file mode 100644 index 0000000..f022246 --- /dev/null +++ b/src/odmdm_fleet/config.py @@ -0,0 +1,41 @@ +"""Configuration, from the environment + +Every setting is prefixed ODMDM_FLEET_. +""" + +import os +from pathlib import Path + + +def _env(name: str, default: str = "") -> str: + return os.environ.get(f"ODMDM_FLEET_{name}", default) + + +LOG_LEVEL: int = int(_env("LOG_LEVEL", "20")) + +#: Where Fleet's API answers +URL: str = _env("URL") + +#: A file holding the Fleet API token. A path rather than the value, so it can be a mounted secret +#: and never appears in a process environment. +TOKEN_FILE: Path | None = Path(_env("TOKEN_FILE")) if _env("TOKEN_FILE") else None + +#: The team whose devices get the deployment's certificate +TEAM: str = _env("TEAM", "Deploy App") + +#: The team devices enrol into and are named in before they move to TEAM. Empty for none. +PREP_TEAM: str = _env("PREP_TEAM") + +#: What this deployment wants installed, as a document. See odmdm_fleet.template. +TEMPLATE: Path | None = Path(_env("TEMPLATE")) if _env("TEMPLATE") else None + +#: The deployment's DNS name, which the template substitutes into URLs +DOMAIN: str = _env("DOMAIN") + +#: The challenge shown on Deploy App's MDM page. It is new for every enrolment window. +CHALLENGE: str = _env("CHALLENGE") + +#: The certificate template name, which becomes the Android keystore alias the certificate lands +#: under. Installing a second key under an existing alias fails, so it never changes for a +#: deployment; the default is what the first deployments were set up with. +KEY_ALIAS: str = _env("KEY_ALIAS", "rmscep") diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py new file mode 100644 index 0000000..2625b87 --- /dev/null +++ b/src/odmdm_fleet/console.py @@ -0,0 +1,228 @@ +"""CLI entrypoints for odmdm-fleet""" + +import logging +import re +from pathlib import Path + +import click +from libadvian.logging import init_logging + +from odmdm_fleet import __version__ + +from . import config, template +from .fleet import FleetError, FleetMdm + +LOGGER = logging.getLogger(__name__) + +#: The deployment's rule for a device callsign, checked here only so a typo is refused now rather +#: than as a failed certificate twenty minutes later. The deployment still decides. +CALLSIGN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{1,30}[A-Za-z0-9]") + + +@click.group() +@click.version_option(version=__version__) +@click.pass_context +@click.option("-v", "--verbose", count=True, help="Shorthand for info/debug loglevel (-v/-vv)") +def cli_group(ctx: click.Context, verbose: int) -> None: + """Connect FleetDM to an OpenDefence deployment's device enrolment""" + _ = ctx + loglevel = config.LOG_LEVEL + if verbose == 1: + loglevel = 20 + if verbose >= 2: + loglevel = 10 + init_logging(loglevel) + LOGGER.setLevel(loglevel) + + +def odmdm_fleet_cli() -> None: + """CLI entrypoint""" + cli_group() # pylint: disable=no-value-for-parameter + + +def _fleet(ctx: click.Context, url: str | None) -> FleetMdm | None: + """Fleet's API, or None after saying what is missing""" + the_url = url or config.URL + if not the_url: + click.echo("Give --fleet-url or set ODMDM_FLEET_URL", err=True) + ctx.exit(1) + return None + if not config.TOKEN_FILE or not config.TOKEN_FILE.is_file(): + click.echo("Set ODMDM_FLEET_TOKEN_FILE to a file holding the Fleet API token", err=True) + ctx.exit(1) + return None + return FleetMdm(the_url, config.TOKEN_FILE.read_text(encoding="utf-8").strip()) + + +def _template(ctx: click.Context, path: str | None, domain: str | None) -> template.MdmTemplate | None: + """The deployment's template with its values filled in, or None after saying why not""" + the_path = Path(path) if path else config.TEMPLATE + the_domain = domain or config.DOMAIN + if not the_path or not the_domain: + click.echo("Give --template and --domain or set ODMDM_FLEET_TEMPLATE and ODMDM_FLEET_DOMAIN", err=True) + ctx.exit(1) + return None + try: + return template.load(the_path, domain=the_domain, key_alias=config.KEY_ALIAS) + except template.TemplateError as exc: + click.echo(f"Template refused: {exc}", err=True) + ctx.exit(1) + return None + + +@cli_group.command(name="apply") +@click.pass_context +@click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_FLEET_TEAM)") +@click.option( + "--prep-team", + default=None, + help="Also set up this team, where devices enrol and are named first (default: ODMDM_FLEET_PREP_TEAM)", +) +@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") +@click.option( + "--force-policy", is_flag=True, help="Re-upload the policy even if unchanged, to reach a host that just joined" +) +@click.option( + "--force-certificate", + is_flag=True, + help="Ask again for the certificate of a host that was named after it enrolled", +) +@click.option("--dry-run", is_flag=True, help="Read and validate the template, then stop") +def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments + ctx: click.Context, + path: str | None, + fleet_url: str | None, + team: str | None, + prep_team: str | None, + domain: str | None, + force_policy: bool, + force_certificate: bool, + dry_run: bool, +) -> None: + """Tell Fleet what this deployment's devices need + + Run it when a deployment is set up, when its template changes, and every time enrolment is + opened: each opening makes a new challenge, and Fleet has to hand that one to the devices. + + Order matters and is handled for you. Apps install at ENROLMENT and at no other time, so a + device that has already joined will not pick up a template applied afterwards -- it has to + enrol again, under a callsign that has not been spent. + """ + wanted = _template(ctx, path, domain) + if not wanted: + return + click.echo(f"Template names {len(wanted.apps)} apps, {len(wanted.preinstall_packages)} installed at enrolment") + for app in wanted.apps: + click.echo(f" {app.package}{' (at enrolment)' if app.preinstall else ' (on demand)'}") + if wanted.link_app: + click.echo(f" launcher link {wanted.link_app.title!r} -> {wanted.link_app.url}") + if dry_run: + ctx.exit(0) + return + + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + the_prep_team = prep_team or config.PREP_TEAM + try: + result = fleet.apply( + team or config.TEAM, + wanted, + force_policy=force_policy, + force_certificate=force_certificate, + scep_url=f"https://{domain or config.DOMAIN}/scep", + challenge=config.CHALLENGE, + ) + if the_prep_team: + prep = fleet.apply_preparation(the_prep_team, wanted, result["link"], force_policy=force_policy) + except FleetError as exc: + click.echo(f"Fleet refused: {exc}", err=True) + ctx.exit(1) + return + click.echo(f"Applied to team {result['team_id']}: {len(result['assigned'])} apps assigned") + if the_prep_team: + click.echo(f"Applied to preparation team {prep['team_id']}: the same apps and launcher, no certificate") + ctx.exit(0) + + +@cli_group.command(name="plan") +@click.pass_context +@click.argument("callsign") +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option( + "--team", + default=None, + help="The team the device waits in (default: ODMDM_FLEET_PREP_TEAM, else ODMDM_FLEET_TEAM)", +) +def plan(ctx: click.Context, callsign: str, fleet_url: str | None, team: str | None) -> None: + """Name the one device waiting to be named + + Enrol a phone, run this, then the next phone. With more than one phone waiting nothing is + named: Fleet shows identical phones as identical rows, so the one in your hand cannot be told + apart from the others. + """ + if not CALLSIGN.fullmatch(callsign): + click.echo("A callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen", err=True) + ctx.exit(1) + return + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + try: + host = fleet.name_the_waiting_host(fleet.team_id(team or config.PREP_TEAM or config.TEAM), callsign) + except FleetError as exc: + click.echo(f"Not named: {exc}", err=True) + ctx.exit(1) + return + click.echo(f"Host {host} is {callsign}") + ctx.exit(0) + + +@cli_group.command(name="reconcile") +@click.pass_context +@click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_FLEET_TEAM)") +@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") +def reconcile( # pylint: disable=too-many-arguments,too-many-positional-arguments + ctx: click.Context, + path: str | None, + fleet_url: str | None, + team: str | None, + domain: str | None, +) -> None: + """Give a certificate to any device that was named after it enrolled + + Run this on a timer. A device enrolled straight into the certificate team asks before anyone + has named it, so that first attempt fails, and Fleet stops retrying after three. + + It only asks again when asking would change something: re-asking reaches every device in the + team, and a template rewritten for nothing is rewritten while somebody else is still installing. + """ + wanted = _template(ctx, path, domain) + if not wanted: + return + if not wanted.certificate: + click.echo("The template states no certificate, so there is nothing to reconcile") + ctx.exit(0) + return + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + the_team = team or config.TEAM + try: + waiting = fleet.hosts_awaiting_certificate(fleet.team_id(the_team), wanted.certificate.name) + if not waiting: + click.echo("Nothing waiting") + ctx.exit(0) + return + click.echo(f"{len(waiting)} device(s) named after enrolment and still without a certificate: {waiting}") + fleet.apply(the_team, wanted, force_certificate=True) + except FleetError as exc: + click.echo(f"Fleet refused: {exc}", err=True) + ctx.exit(1) + return + click.echo("Asked again") + ctx.exit(0) diff --git a/tests/test_console.py b/tests/test_console.py new file mode 100644 index 0000000..7e21ceb --- /dev/null +++ b/tests/test_console.py @@ -0,0 +1,150 @@ +"""The CLI + +An operator runs these by hand, so a missing setting has to say what is missing and a refusal has +to say why, rather than end in a traceback. +""" + +import json +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from odmdm_fleet import config +from odmdm_fleet.console import cli_group + +from .test_fleet import _Fleet, _host, _mdm + + +@pytest.fixture +def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: + """A configured connector talking to a stubbed Fleet whose preparation team is "prep" """ + token = tmp_path / "token" + token.write_text("token\n", encoding="utf-8") + monkeypatch.setattr(config, "URL", "https://mdm.test") + monkeypatch.setattr(config, "TOKEN_FILE", token) + monkeypatch.setattr(config, "PREP_TEAM", "prep") + stub = _Fleet() + _mdm(stub, monkeypatch) + return stub + + +@pytest.mark.parametrize("callsign", ["OT", "OTTER-", "OTTER_1", "X" * 33]) +def test_plan_refuses_a_callsign_the_deployment_would(callsign: str) -> None: + """Now, rather than as a failed certificate twenty minutes later, and before Fleet is touched""" + result = CliRunner().invoke(cli_group, ["plan", callsign]) + + assert result.exit_code == 1 + assert "3-32 letters" in result.output + + +def test_plan_names_the_waiting_phone(fleet: _Fleet) -> None: + """The one in your hand is the only one waiting""" + fleet.hosts = [_host(4, "failed", named=False)] + + result = CliRunner().invoke(cli_group, ["plan", "OTTER4"]) + + assert result.exit_code == 0, result.output + assert "Host 4 is OTTER4" in result.output + assert fleet.hosts[0]["device_mapping"][0]["email"] == "OTTER4" + + +def test_plan_says_why_it_named_nobody(fleet: _Fleet) -> None: + """Two phones waiting: the operator learns to enrol them one at a time""" + fleet.hosts = [_host(4, "failed", named=False), _host(5, "failed", named=False)] + + result = CliRunner().invoke(cli_group, ["plan", "OTTER4"]) + + assert result.exit_code == 1 + assert "one at a time" in result.output + + +def test_plan_needs_somewhere_to_send_it(monkeypatch: pytest.MonkeyPatch) -> None: + """No Fleet configured is a sentence, not a traceback""" + monkeypatch.setattr(config, "URL", "") + + result = CliRunner().invoke(cli_group, ["plan", "OTTER4"]) + + assert result.exit_code == 1 + assert "ODMDM_FLEET_URL" in result.output + + +@pytest.mark.parametrize("command", ["apply", "reconcile"]) +def test_a_template_and_domain_are_required(command: str, monkeypatch: pytest.MonkeyPatch) -> None: + """Without them there is nothing to state to Fleet""" + monkeypatch.setattr(config, "TEMPLATE", None) + + result = CliRunner().invoke(cli_group, [command]) + + assert result.exit_code == 1 + assert "ODMDM_FLEET_TEMPLATE" in result.output + + +def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + path = tmp_path / "template.json" + path.write_text( + json.dumps( + { + "apps": [{"package": "com.example.one"}], + "policy": {"defaultPermissionPolicy": "GRANT"}, + "certificate": {"name": "{key_alias}", "subject": "CN=$VAR", "authority": "RMSCEP"}, + } + ), + encoding="utf-8", + ) + monkeypatch.setattr(config, "TEMPLATE", path) + monkeypatch.setattr(config, "DOMAIN", "example.fi") + + +def test_apply_states_the_template_to_both_teams( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The certificate team gets the certificate, the preparation team everything else""" + _template(tmp_path, monkeypatch) + monkeypatch.setattr(config, "CHALLENGE", "new-window") + + result = CliRunner().invoke(cli_group, ["apply", "--team", "rmscep"]) + + assert result.exit_code == 0, result.output + assert "Applied to team 7" in result.output + assert "Applied to preparation team 8" in result.output + assert fleet.authorities[0]["challenge"] == "new-window" + assert fleet.authorities[0]["url"] == "https://example.fi/scep" + + +def test_a_dry_run_never_reaches_fleet(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Checking an edited template must not change the estate""" + _template(tmp_path, monkeypatch) + + result = CliRunner().invoke(cli_group, ["apply", "--dry-run"]) + + assert result.exit_code == 0, result.output + assert not fleet.calls + + +def test_reconcile_leaves_fleet_alone_when_nobody_waits( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Re-asking reaches every phone in the team, so it happens only when it changes something""" + _template(tmp_path, monkeypatch) + fleet.hosts = [_host(4, "verified", named=True)] + + result = CliRunner().invoke(cli_group, ["reconcile", "--team", "rmscep"]) + + assert result.exit_code == 0, result.output + assert "Nothing waiting" in result.output + assert not [call for call in fleet.calls if call[0] != "GET"] + + +def test_reconcile_asks_again_for_a_phone_named_late( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Named after its first request failed: recreating the template is what asks again""" + _template(tmp_path, monkeypatch) + fleet.hosts = [_host(4, "failed", named=True)] + + result = CliRunner().invoke(cli_group, ["reconcile", "--team", "rmscep"]) + + assert result.exit_code == 0, result.output + assert "Asked again" in result.output + assert ("POST", "/api/latest/fleet/certificates") in fleet.calls From a0e7b10bdea3dbbf4449a938b3fe26485ecd412d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 00:22:21 +0200 Subject: [PATCH 004/104] docs: an example template for Deploy App --- README.rst | 3 +- examples/template.json | 77 ++++++++++++++++++++++++++++++++++++++++++ tests/test_template.py | 11 ++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 examples/template.json diff --git a/README.rst b/README.rst index 8b48ab0..74ac3ff 100644 --- a/README.rst +++ b/README.rst @@ -95,7 +95,8 @@ The template What to install is a property of the deployment, so it is a document rather than code: the apps, their managed configuration, the Android Management API device policy, a launcher link, and the certificate template. ``{domain}``, ``{mtls_url}`` and ``{key_alias}`` are filled in. Keys -beginning with ``_`` are comments and never reach Fleet. +beginning with ``_`` are comments and never reach Fleet. ``examples/template.json`` is a working one +for Deploy App, with its reasoning in the comments. The certificate subject is the contract with the deployment. Its common name becomes the callsign: 3 to 32 letters, digits or hyphens, no hyphen at either end. For named phones:: diff --git a/examples/template.json b/examples/template.json new file mode 100644 index 0000000..0348296 --- /dev/null +++ b/examples/template.json @@ -0,0 +1,77 @@ +{ + "_comment": [ + "What a Deploy App deployment's phones need. Copy it, change what to install, and apply it with", + " odmdm-fleet apply --template template.json --domain ", + "", + "Placeholders filled in at apply time: {domain}, {mtls_url}, {key_alias}.", + "", + "APPS INSTALL AT ENROLMENT AND AT NO OTHER TIME on managed Android. A phone that has already", + "joined will not pick up a change here; it has to enrol again, under a callsign that has not", + "been spent." + ], + "apps": [ + { + "_comment": "The browser is installed, not assumed: a work profile does not inherit the personal profile's copy, and the launcher link below is a browser shortcut, so without it that install fails and takes the rest of the enrolment burst with it.", + "config": { + "AutoSelectCertificateForUrls": [ + "{\"pattern\":\"{mtls_url}\",\"filter\":{}}" + ], + "_comment": "choosePrivateKeyRules in the policy settles WHICH key may be used. The browser still decides whether to send one at all, and with no matching entry here it declines rather than prompting, which the server answers as mtls_fail and looks exactly like a missing certificate. Both halves are needed. The value is a list of JSON strings, which is the schema, not a mistake." + }, + "package": "com.android.chrome", + "preinstall": true + }, + { + "_comment": "ATAK-CIV. Large, and Play unpacks the enrolment set together, so on a device short of space the whole burst can fail.", + "package": "com.atakmap.app.civ", + "preinstall": true + }, + { + "_comment": "Element Classic rather than Element X: X accepts no managed configuration at all, so its homeserver cannot be pushed and the user would type it once per device.", + "config": { + "im.vector.app.serverConfigDefaultHomeserverUrlString": "https://synapse.{domain}" + }, + "package": "im.vector.app", + "preinstall": true + } + ], + "certificate": { + "_comment": [ + "The template Fleet fills in per phone. Its common name becomes the phone's callsign: 3-32", + "letters, digits or inner hyphens. This is the name `odmdm-fleet plan` gives a phone. To skip", + "naming, CN=$FLEET_VAR_HOST_HARDWARE_SERIAL works for company-owned phones only.", + "The name becomes the Android keystore alias, so it is per deployment, not per phone." + ], + "authority": "RMSCEP", + "name": "{key_alias}", + "subject": "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" + }, + "link_app": { + "_comment": "A launcher icon so nobody has to know where the server lives. It is a browser shortcut, so it only works alongside the browser and the certificate.", + "title": "Deploy App", + "url": "{mtls_url}/" + }, + "policy": { + "_comment_key": "urlPattern is a java.util.regex pattern matched against the WHOLE string the app passes. Chrome passes host:port with no scheme (mtls.example.fi:443), so a pattern starting https:// matches nothing, the device offers no key, and the server answers mtls_fail exactly as if no certificate existed. This one takes both forms and still only the mTLS host.", + "advancedSecurityOverrides": { + "untrustedAppsPolicy": "ALLOW_INSTALL_DEVICE_WIDE" + }, + "choosePrivateKeyRules": [ + { + "privateKeyAlias": "{key_alias}", + "urlPattern": "(https://)?mtls\\.{domain}(:443)?(/.*)?" + }, + { + "packageNames": [ + "com.android.chrome", + "com.atakmap.app.civ", + "im.vector.app" + ], + "privateKeyAlias": "{key_alias}", + "urlPattern": "(https://)?mtls\\.{domain}(:443)?(/.*)?" + } + ], + "defaultPermissionPolicy": "GRANT", + "privateKeySelectionEnabled": true + } +} diff --git a/tests/test_template.py b/tests/test_template.py index 9ce0ad0..fc7b553 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -99,3 +99,14 @@ def test_annotations_never_reach_the_device(tmp_path: Path) -> None: assert template.apps[0].config == {"real": "value", "nested": {"keep": 2}} assert template.policy == {"defaultPermissionPolicy": "GRANT"} assert template.link_app is not None and template.link_app.title == "Deploy App" + + +def test_the_example_is_a_template_we_accept() -> None: + """Operators start from it, so it must never drift out of what load() takes""" + example = Path(__file__).resolve().parent.parent / "examples" / "template.json" + + template = load(example, domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None + assert template.certificate.name == "rmscep", "the keystore alias comes from the setting" + assert not [p for p in ("{domain}", "{mtls_url}", "{key_alias}") if p in json.dumps(template.policy)] From b28e6c565313ded45279722c85ec88af2f83f795 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 01:00:03 +0200 Subject: [PATCH 005/104] feat: hand Fleet a new window's challenge and nothing else --- README.rst | 9 +++++--- src/odmdm_fleet/console.py | 47 ++++++++++++++++++++++++++++++++++++-- tests/test_console.py | 15 ++++++++++++ 3 files changed, 66 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 74ac3ff..163ca0f 100644 --- a/README.rst +++ b/README.rst @@ -33,9 +33,10 @@ callsign. names neither, because Fleet shows identical phones as identical rows and nothing tells you which is the one in your hand. Enrol, plan, next phone. -3. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge:: +3. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge. It + asks for it, and changes nothing else:: - ODMDM_FLEET_CHALLENGE= odmdm-fleet apply --team "Deploy App" + odmdm-fleet challenge 4. In Fleet, transfer the named phones to the ``Deploy App`` team. Each gets its certificate 7 to 20 minutes later and greets its callsign in Deploy App. @@ -50,6 +51,7 @@ Commands odmdm-fleet apply # state what devices need; --force-policy after one joins odmdm-fleet apply --dry-run # validate the template without touching Fleet + odmdm-fleet challenge # give Fleet a new enrolment window's challenge, nothing else odmdm-fleet plan CALLSIGN # name the one phone waiting to be named odmdm-fleet reconcile # ask again for phones named after they enrolled; run on a timer @@ -82,7 +84,8 @@ All configuration is via environment variables: The deployment's DNS name. ``ODMDM_FLEET_CHALLENGE`` - The challenge on Deploy App's MDM page. New for every enrolment window. + The challenge on Deploy App's MDM page, for ``challenge`` and a first ``apply``. New for every + enrolment window. ``ODMDM_FLEET_KEY_ALIAS`` The certificate template's name, which becomes the Android keystore alias. Default ``rmscep``, diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 2625b87..961b464 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -103,8 +103,9 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ) -> None: """Tell Fleet what this deployment's devices need - Run it when a deployment is set up, when its template changes, and every time enrolment is - opened: each opening makes a new challenge, and Fleet has to hand that one to the devices. + Run it when a deployment is set up and whenever its template changes. It rewrites the policy, + which stops apps installing on phones that are enrolling at that moment, so a new enrolment + window is `challenge`, not this. Order matters and is handled for you. Apps install at ENROLMENT and at no other time, so a device that has already joined will not pick up a template applied afterwards -- it has to @@ -147,6 +148,48 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx.exit(0) +@cli_group.command(name="challenge") +@click.pass_context +@click.option( + "--challenge", + "value", + envvar="ODMDM_FLEET_CHALLENGE", + prompt="Challenge from Deploy App's MDM page", + hide_input=True, + help="The new window's challenge (default: ODMDM_FLEET_CHALLENGE, else asked for)", +) +@click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") +def challenge( # pylint: disable=too-many-arguments,too-many-positional-arguments + ctx: click.Context, value: str, path: str | None, fleet_url: str | None, domain: str | None +) -> None: + """Give Fleet the challenge of the enrolment window just opened + + Every opening makes a new one. Only the certificate authority changes, so phones still + installing apps are left alone. Asked for rather than taken as an argument, so it stays out of + shell history. + """ + wanted = _template(ctx, path, domain) + if not wanted: + return + if not wanted.certificate: + click.echo("The template states no certificate, so there is no authority to give it to", err=True) + ctx.exit(1) + return + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + try: + fleet.ensure_authority(wanted.certificate.authority, f"https://{domain or config.DOMAIN}/scep", value) + except FleetError as exc: + click.echo(f"Fleet refused: {exc}", err=True) + ctx.exit(1) + return + click.echo(f"{wanted.certificate.authority} has the new challenge") + ctx.exit(0) + + @cli_group.command(name="plan") @click.pass_context @click.argument("callsign") diff --git a/tests/test_console.py b/tests/test_console.py index 7e21ceb..5dc7f09 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -148,3 +148,18 @@ def test_reconcile_asks_again_for_a_phone_named_late( assert result.exit_code == 0, result.output assert "Asked again" in result.output assert ("POST", "/api/latest/fleet/certificates") in fleet.calls + + +def test_a_new_window_touches_only_the_authority( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A rewritten policy stops apps installing on phones enrolling right now""" + _template(tmp_path, monkeypatch) + + result = CliRunner().invoke(cli_group, ["challenge"], input="new-window\n") + + assert result.exit_code == 0, result.output + assert "new-window" not in result.output, "asked for without echoing it" + assert fleet.authorities[0]["challenge"] == "new-window" + changed = {path for method, path in fleet.calls if method != "GET"} + assert changed == {"/api/latest/fleet/certificate_authorities/3"} From a902b8599c4939f84c0741a7b201ae11fa1d57be Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 10:06:19 +0200 Subject: [PATCH 006/104] feat: rename a returning phone by its old name --- README.rst | 3 ++- src/odmdm_fleet/console.py | 14 ++++++++++++-- src/odmdm_fleet/fleet.py | 15 +++++++++++++++ tests/test_console.py | 10 ++++++++++ tests/test_fleet.py | 22 ++++++++++++++++++++++ 5 files changed, 61 insertions(+), 3 deletions(-) diff --git a/README.rst b/README.rst index 163ca0f..876b895 100644 --- a/README.rst +++ b/README.rst @@ -128,7 +128,8 @@ What Fleet does that you would not guess - **A web app's display name is unique within a team** (409). A title in a team's setup experience has to be removed there before it can be removed from the team. - **A returning phone keeps its old team and its old name.** Transfer it to the preparation team - and name it again, or it asks for a name that is already taken. + and rename it with ``odmdm-fleet plan NEWNAME --instead-of OLDNAME``, or it asks for a name that + is already taken. - **Renaming a phone that has its certificate gives it a second callsign.** Revoke the old one in Deploy App. - **A refusal shows only as** ``SCEP enrollment failed ... failInfo: badMessageCheck`` on the diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 961b464..65bf6eb 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -199,12 +199,18 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen default=None, help="The team the device waits in (default: ODMDM_FLEET_PREP_TEAM, else ODMDM_FLEET_TEAM)", ) -def plan(ctx: click.Context, callsign: str, fleet_url: str | None, team: str | None) -> None: +@click.option("--instead-of", "old", default=None, help="Rename the device now called this, such as a returning phone") +def plan( # pylint: disable=too-many-arguments,too-many-positional-arguments + ctx: click.Context, callsign: str, fleet_url: str | None, team: str | None, old: str | None +) -> None: """Name the one device waiting to be named Enrol a phone, run this, then the next phone. With more than one phone waiting nothing is named: Fleet shows identical phones as identical rows, so the one in your hand cannot be told apart from the others. + + A phone that comes back after a wipe keeps its old name, so it is not waiting. Rename it with + --instead-of and the name it had. """ if not CALLSIGN.fullmatch(callsign): click.echo("A callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen", err=True) @@ -214,7 +220,11 @@ def plan(ctx: click.Context, callsign: str, fleet_url: str | None, team: str | N if not fleet: return try: - host = fleet.name_the_waiting_host(fleet.team_id(team or config.PREP_TEAM or config.TEAM), callsign) + team_id = fleet.team_id(team or config.PREP_TEAM or config.TEAM) + if old: + host = fleet.rename_host(team_id, old, callsign) + else: + host = fleet.name_the_waiting_host(team_id, callsign) except FleetError as exc: click.echo(f"Not named: {exc}", err=True) ctx.exit(1) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 9aa1b70..bc70f2d 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -418,6 +418,21 @@ def name_the_waiting_host(self, team: int, callsign: str) -> int: LOGGER.info("Named host %s %s", waiting[0], callsign) return waiting[0] + def rename_host(self, team: int, old: str, callsign: str) -> int: + """Give the host in the team now called `old` a new callsign + + A phone that comes back after a wipe keeps the name it had, so it is not waiting to be + named and name_the_waiting_host cannot reach it. Its old name is what tells it apart. + Names are compared without case, as the deployment compares callsigns. + """ + hosts = self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] + called = [int(host["id"]) for host in hosts if self._name_of(int(host["id"])).lower() == old.lower()] + if len(called) != 1: + raise FleetError(f"{len(called)} devices in team {team} are called {old}, so none was renamed") + self._call("PUT", f"/api/latest/fleet/hosts/{called[0]}/device_mapping", {"email": callsign, "source": "idp"}) + LOGGER.info("Renamed host %s from %s to %s", called[0], old, callsign) + return called[0] + # --- the whole statement -------------------------------------------------- def apply( diff --git a/tests/test_console.py b/tests/test_console.py index 5dc7f09..ea1f215 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -49,6 +49,16 @@ def test_plan_names_the_waiting_phone(fleet: _Fleet) -> None: assert fleet.hosts[0]["device_mapping"][0]["email"] == "OTTER4" +def test_plan_renames_a_returning_phone(fleet: _Fleet) -> None: + """Named before the wipe, so the old name is how the operator points at it""" + fleet.hosts = [_host(4, "failed", named=True)] + + result = CliRunner().invoke(cli_group, ["plan", "KETTU4", "--instead-of", "OTTER1@CODE"]) + + assert result.exit_code == 0, result.output + assert fleet.hosts[0]["device_mapping"][0]["email"] == "KETTU4" + + def test_plan_says_why_it_named_nobody(fleet: _Fleet) -> None: """Two phones waiting: the operator learns to enrol them one at a time""" fleet.hosts = [_host(4, "failed", named=False), _host(5, "failed", named=False)] diff --git a/tests/test_fleet.py b/tests/test_fleet.py index d94fcd8..6afd797 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -366,6 +366,28 @@ def test_no_phone_is_named_unless_exactly_one_waits(monkeypatch: pytest.MonkeyPa assert not [call for call in fleet.calls if call[0] == "PUT"] +def test_a_returning_phone_is_renamed_by_its_old_name(monkeypatch: pytest.MonkeyPatch) -> None: + """It kept its name through the wipe, so it is not waiting, and only its old name finds it""" + fleet = _Fleet() + fleet.hosts = [_host(1, "verified", named=True), _host(2, "failed", named=False)] + + assert _mdm(fleet, monkeypatch).rename_host(8, "otter1@code", "KETTU1") == 1 + + assert fleet.hosts[0]["device_mapping"] == [{"email": "KETTU1", "source": "idp"}] + assert fleet.hosts[1].get("device_mapping") == [] + + +def test_a_name_nobody_has_renames_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + """A typo in the old name must not land the new one on some other phone""" + fleet = _Fleet() + fleet.hosts = [_host(1, "verified", named=True)] + + with pytest.raises(FleetError, match="0 devices"): + _mdm(fleet, monkeypatch).rename_host(8, "OTTER9", "KETTU1") + + assert not [call for call in fleet.calls if call[0] == "PUT"] + + def _with_cert(authority: str = "RMSCEP") -> MdmTemplate: """A template that asks for a certificate, which is what drags the authority in""" return MdmTemplate( From 9aaa82c50ff2957ccd8c751b5c5e1adc1ca5bc8e Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 1 Nov 2026 10:06:22 +0200 Subject: [PATCH 007/104] fix: keep Fleet's request log out of the commands' output --- src/odmdm_fleet/console.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 65bf6eb..75263fd 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -33,6 +33,8 @@ def cli_group(ctx: click.Context, verbose: int) -> None: loglevel = 10 init_logging(loglevel) LOGGER.setLevel(loglevel) + # One line per Fleet request buries what the command says; -vv brings them back + logging.getLogger("httpx").setLevel(max(loglevel, logging.WARNING) if verbose < 2 else loglevel) def odmdm_fleet_cli() -> None: From 68a1f38105bdf068a152442e9ae1b54ba32ba854 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Tue, 3 Nov 2026 08:46:09 +0100 Subject: [PATCH 008/104] fix: compare the policy with Fleet's copy before uploading --- src/odmdm_fleet/console.py | 6 ++--- src/odmdm_fleet/fleet.py | 28 +++++++++------------- tests/test_fleet.py | 48 ++++++++++++++++++++++++++++---------- 3 files changed, 50 insertions(+), 32 deletions(-) diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 75263fd..6a19ca0 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -105,9 +105,9 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ) -> None: """Tell Fleet what this deployment's devices need - Run it when a deployment is set up and whenever its template changes. It rewrites the policy, - which stops apps installing on phones that are enrolling at that moment, so a new enrolment - window is `challenge`, not this. + Run it when a deployment is set up and whenever its template changes. A changed policy stops + apps installing on phones that are enrolling at that moment, so a new enrolment window is + `challenge`, not this. Order matters and is handled for you. Apps install at ENROLMENT and at no other time, so a device that has already joined will not pick up a template applied afterwards -- it has to diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index bc70f2d..704fe4f 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -5,7 +5,6 @@ """ import dataclasses -import hashlib import json import logging import time @@ -43,10 +42,6 @@ def __init__(self, base_url: str, token: str, timeout: float = 60.0) -> None: self.base_url = base_url.rstrip("/") self._token = token self.timeout = timeout - #: What we last uploaded, so an unchanged policy is not rewritten. Re-pushing on every - #: pass is not merely wasteful: a policy rewritten repeatedly never settles long enough - #: for Play to finish an install, and the device comes up with nothing on it. - self._pushed: dict[str, str] = {} def _call(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]: url = f"{self.base_url}{path}" @@ -144,14 +139,12 @@ def assign_apps(self, team: int, packages: list[str], preinstall: list[str]) -> LOGGER.info("Waiting for managed Play to publish %s", package) time.sleep(WEB_APP_PUBLISH_WAIT) chosen = sorted(ids[p] for p in preinstall if p in ids) - digest = hashlib.sha256(repr(chosen).encode()).hexdigest() - if chosen and self._pushed.get(f"{team}:setup") != digest: + if chosen: self._call( "PUT", "/api/latest/fleet/setup_experience/software", {"platform": "android", "team_id": team, "software_title_ids": chosen}, ) - self._pushed[f"{team}:setup"] = digest return ids def set_app_config(self, team: int, package: str, config: dict[str, Any]) -> None: @@ -167,19 +160,17 @@ def set_app_config(self, team: int, package: str, config: dict[str, Any]) -> Non def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_NAME, force: bool = False) -> None: """Android configuration profiles carry raw policy JSON - There is no update in place, so changing one is delete then upload, and the single - profile GET returns metadata only, so there is nothing to compare against -- remember the - digest instead. Re-uploading an unchanged profile is not free: a policy rewritten on every - pass never settles long enough for Play to finish an install. + There is no update in place, so changing one is delete then upload. Re-uploading an + unchanged profile is not free: a policy rewritten on every pass never settles long enough + for Play to finish an install. So Fleet's own copy is what gets compared, because this + runs once per command and has nothing of its own to remember between runs. force exists because a profile is delivered when the PROFILE changes, not when a host arrives, so one created before a device joined is never sent to it. """ profiles = self._call("GET", f"/api/latest/fleet/configuration_profiles?team_id={team}").get("profiles", []) - wanted = json.dumps(fragment, indent=2, sort_keys=True).encode("utf-8") - digest = hashlib.sha256(wanted).hexdigest() here = [p for p in profiles if p.get("name") == name] - if here and not force and self._pushed.get(f"{team}:{name}") == digest: + if len(here) == 1 and not force and self._policy_in_fleet(here[0]["profile_uuid"]) == fragment: return for existing in here: self._call("DELETE", f"/api/latest/fleet/configuration_profiles/{existing['profile_uuid']}") @@ -187,12 +178,15 @@ def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_ "/api/latest/fleet/configuration_profiles", {"team_id": str(team)}, f"{name}.json", - wanted, + json.dumps(fragment, indent=2, sort_keys=True).encode("utf-8"), file_field="profile", ) - self._pushed[f"{team}:{name}"] = digest LOGGER.info("Uploaded policy %s to team %s", name, team) + def _policy_in_fleet(self, profile_uuid: str) -> dict[str, Any]: + """The policy as Fleet holds it; without alt=media this answers with metadata only""" + return self._call("GET", f"/api/latest/fleet/configuration_profiles/{profile_uuid}?alt=media") + def ensure_link_app(self, team: int, title: str, url: str) -> str: """A managed web app, so the deployment has an icon on the launcher diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 6afd797..0cb4186 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -152,12 +152,23 @@ def handler(self, request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"software_title_id": self._next_id}) if path.endswith("/configuration_profiles"): if request.method == "GET": - return httpx.Response(200, json={"profiles": list(self.profiles)}) + return httpx.Response( + 200, json={"profiles": [{k: v for k, v in p.items() if k != "raw"} for p in self.profiles]} + ) # An upload the MDM keeps, so a second pass can see it is already there. Without # this the adapter is right to upload again: a profile that has gone missing must # be restored whatever we remember pushing. - self.profiles.append({"name": "rmscep-policy", "profile_uuid": f"uuid-{len(self.profiles)}"}) + raw = re.search(rb"application/json\r\n\r\n(.*)\r\n--", request.read(), re.DOTALL) + assert raw, "the policy must be uploaded as JSON" + self.profiles.append( + {"name": "rmscep-policy", "profile_uuid": f"uuid-{len(self.profiles)}", "raw": json.loads(raw.group(1))} + ) return httpx.Response(200, json={}) + if "/configuration_profiles/" in path and request.method == "GET": + # Only alt=media answers with the policy; without it Fleet sends metadata. + found = next(p for p in self.profiles if p["profile_uuid"] == path.rsplit("/", 1)[-1]) + media = request.url.params.get("alt") == "media" + return httpx.Response(200, json=found["raw"] if media else {"name": found["name"]}) if "/configuration_profiles/" in path and request.method == "DELETE": self.profiles.clear() return httpx.Response(200, json={}) @@ -196,15 +207,29 @@ def test_only_the_chosen_apps_install_at_enrolment(monkeypatch: pytest.MonkeyPat assert len(result["assigned"]) == 2 +def _policy_uploads(fleet: _Fleet) -> int: + return len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + + def test_an_unchanged_policy_is_not_rewritten(monkeypatch: pytest.MonkeyPatch) -> None: - """Measured: a policy rewritten every pass never settles and nothing ever installs""" + """Measured: a policy rewritten every pass never settles and nothing ever installs + + Each run of the command is a new process, so nothing from the last run can be remembered. + """ fleet = _Fleet() - mdm = _mdm(fleet, monkeypatch) - mdm.apply("rmscep", TEMPLATE) - uploads_after_first = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) - mdm.apply("rmscep", TEMPLATE) - uploads_after_second = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) - assert uploads_after_second == uploads_after_first, "the same policy must not be uploaded twice" + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + uploads_after_first = _policy_uploads(fleet) + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + assert _policy_uploads(fleet) == uploads_after_first, "the same policy must not be uploaded twice" + + +def test_a_changed_policy_replaces_the_old_one(monkeypatch: pytest.MonkeyPatch) -> None: + """Otherwise an edited template would look applied and change nothing on a phone""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", TEMPLATE) + changed = MdmTemplate(apps=TEMPLATE.apps, policy={"defaultPermissionPolicy": "PROMPT"}) + _mdm(fleet, monkeypatch).apply("rmscep", changed) + assert [p["raw"] for p in fleet.profiles] == [changed.policy] def test_force_reaches_a_host_that_just_joined(monkeypatch: pytest.MonkeyPatch) -> None: @@ -212,10 +237,9 @@ def test_force_reaches_a_host_that_just_joined(monkeypatch: pytest.MonkeyPatch) fleet = _Fleet() mdm = _mdm(fleet, monkeypatch) mdm.apply("rmscep", TEMPLATE) - before = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) + before = _policy_uploads(fleet) mdm.apply("rmscep", TEMPLATE, force_policy=True) - after = len([1 for m, p in fleet.calls if m == "POST" and p.endswith("/configuration_profiles")]) - assert after == before + 1 + assert _policy_uploads(fleet) == before + 1 def test_a_refusal_is_reported_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None: From 6842055dfce9945da2e8b1ba2a0a7f125e3c5127 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Tue, 3 Nov 2026 08:46:40 +0100 Subject: [PATCH 009/104] fix!: remove reconcile and --force-certificate, they lock phones out --- README.rst | 10 ++++--- src/odmdm_fleet/console.py | 55 -------------------------------------- src/odmdm_fleet/fleet.py | 36 +++---------------------- tests/test_console.py | 34 +++-------------------- tests/test_fleet.py | 44 ------------------------------ 5 files changed, 12 insertions(+), 167 deletions(-) diff --git a/README.rst b/README.rst index 876b895..2a76f8f 100644 --- a/README.rst +++ b/README.rst @@ -53,11 +53,9 @@ Commands odmdm-fleet apply --dry-run # validate the template without touching Fleet odmdm-fleet challenge # give Fleet a new enrolment window's challenge, nothing else odmdm-fleet plan CALLSIGN # name the one phone waiting to be named - odmdm-fleet reconcile # ask again for phones named after they enrolled; run on a timer -``reconcile`` is for a single-team setup, where a phone enrols straight into the certificate team -before anyone has named it. That first request fails, Fleet gives up after three, and -``reconcile`` asks again once the phone has a name. +With a single team a phone enrols straight into the certificate team before anyone has named it, +and that first request fails. Name it with ``plan --team``, then transfer it out and back. Configuration ------------- @@ -132,6 +130,10 @@ What Fleet does that you would not guess is already taken. - **Renaming a phone that has its certificate gives it a second callsign.** Revoke the old one in Deploy App. +- **Replacing a team's certificate template locks its phones out.** Every phone deletes the + certificate it has and asks again, and the deployment refuses a name that is already taken. So + this repository never replaces one to retry a phone: a transfer out and back asks for that phone + alone. - **A refusal shows only as** ``SCEP enrollment failed ... failInfo: badMessageCheck`` on the phone's certificate. Usually a bad or taken name, or Fleet still has the previous window's challenge. Fix it, then transfer the phone out and back. diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 6a19ca0..0f85342 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -86,11 +86,6 @@ def _template(ctx: click.Context, path: str | None, domain: str | None) -> templ @click.option( "--force-policy", is_flag=True, help="Re-upload the policy even if unchanged, to reach a host that just joined" ) -@click.option( - "--force-certificate", - is_flag=True, - help="Ask again for the certificate of a host that was named after it enrolled", -) @click.option("--dry-run", is_flag=True, help="Read and validate the template, then stop") def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx: click.Context, @@ -100,7 +95,6 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments prep_team: str | None, domain: str | None, force_policy: bool, - force_certificate: bool, dry_run: bool, ) -> None: """Tell Fleet what this deployment's devices need @@ -134,7 +128,6 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments team or config.TEAM, wanted, force_policy=force_policy, - force_certificate=force_certificate, scep_url=f"https://{domain or config.DOMAIN}/scep", challenge=config.CHALLENGE, ) @@ -233,51 +226,3 @@ def plan( # pylint: disable=too-many-arguments,too-many-positional-arguments return click.echo(f"Host {host} is {callsign}") ctx.exit(0) - - -@cli_group.command(name="reconcile") -@click.pass_context -@click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_FLEET_TEAM)") -@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") -def reconcile( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, - path: str | None, - fleet_url: str | None, - team: str | None, - domain: str | None, -) -> None: - """Give a certificate to any device that was named after it enrolled - - Run this on a timer. A device enrolled straight into the certificate team asks before anyone - has named it, so that first attempt fails, and Fleet stops retrying after three. - - It only asks again when asking would change something: re-asking reaches every device in the - team, and a template rewritten for nothing is rewritten while somebody else is still installing. - """ - wanted = _template(ctx, path, domain) - if not wanted: - return - if not wanted.certificate: - click.echo("The template states no certificate, so there is nothing to reconcile") - ctx.exit(0) - return - fleet = _fleet(ctx, fleet_url) - if not fleet: - return - the_team = team or config.TEAM - try: - waiting = fleet.hosts_awaiting_certificate(fleet.team_id(the_team), wanted.certificate.name) - if not waiting: - click.echo("Nothing waiting") - ctx.exit(0) - return - click.echo(f"{len(waiting)} device(s) named after enrolment and still without a certificate: {waiting}") - fleet.apply(the_team, wanted, force_certificate=True) - except FleetError as exc: - click.echo(f"Fleet refused: {exc}", err=True) - ctx.exit(1) - return - click.echo("Asked again") - ctx.exit(0) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 704fe4f..6b00c18 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -325,17 +325,12 @@ def ensure_authority(self, name: str, scep_url: str, challenge: str) -> int: body = created.get("certificate_authority") or created return int(body["id"]) - def ensure_certificate(self, team: int, name: str, subject: str, authority: str, force: bool = False) -> int: + def ensure_certificate(self, team: int, name: str, subject: str, authority: str) -> int: """The template the MDM fills in per device, and asks us to sign There is no update in place, so a changed subject is delete then create. The name is kept because it becomes the Android keystore alias, and a device already holding a key under one alias will not accept a second. - - force exists because the subject is filled in when a device ENROLS, and a device enrols - before anyone has named it -- the host does not exist to be named until then. That first - attempt fails, and Fleet never retries a failed certificate on its own. Recreating the - template is what asks again, so it is how a named host finally gets its certificate. """ authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) match = [a for a in authorities if a.get("name") == authority] @@ -349,13 +344,12 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str, if template.get("name") != name: continue if ( - not force - and template.get("subject_name") == subject + template.get("subject_name") == subject and int(template.get("certificate_authority_id", 0)) == authority_id ): return int(template["id"]) self._call("DELETE", f"/api/latest/fleet/certificates/{template['id']}?team_id={team}") - LOGGER.info("Replacing certificate template %s, so it is asked for again", name) + LOGGER.info("Replacing certificate template %s", name) created = self._call( "POST", @@ -365,28 +359,6 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str, LOGGER.info("Certificate template %s asks for %s", name, subject) return int(created["id"]) - def hosts_awaiting_certificate(self, team: int, name: str) -> list[int]: - """Hosts that were named after they enrolled, and so have no certificate - - The subject is filled in when a device ENROLS, and a device enrols before anyone has named - it -- there is no host to name until it does. That first attempt fails, and nothing retries - it. These are the hosts for which asking again would now work: named, and still refused. - - Asking again is not free, because it re-asks every device in the group, so this exists to - keep that to the occasions when it would change something. - """ - hosts = self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] - waiting = [] - for host in hosts: - host_id = int(host["id"]) - detail = self._call("GET", f"/api/latest/fleet/hosts/{host_id}").get("host") or {} - profiles = (detail.get("mdm") or {}).get("profiles") or [] - if not any(p.get("name") == name and p.get("status") == "failed" for p in profiles): - continue - if self._name_of(host_id): - waiting.append(host_id) - return waiting - # --- naming --------------------------------------------------------------- def _name_of(self, host_id: int) -> str: @@ -434,7 +406,6 @@ def apply( team_name: str, template: MdmTemplate, force_policy: bool = False, - force_certificate: bool = False, scep_url: str = "", challenge: str = "", link_package: str = "", @@ -461,7 +432,6 @@ def apply( template.certificate.name, template.certificate.subject, template.certificate.authority, - force=force_certificate, ) self.ensure_policy(team, template.policy, force=force_policy) diff --git a/tests/test_console.py b/tests/test_console.py index ea1f215..0d11e56 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -79,12 +79,12 @@ def test_plan_needs_somewhere_to_send_it(monkeypatch: pytest.MonkeyPatch) -> Non assert "ODMDM_FLEET_URL" in result.output -@pytest.mark.parametrize("command", ["apply", "reconcile"]) -def test_a_template_and_domain_are_required(command: str, monkeypatch: pytest.MonkeyPatch) -> None: +@pytest.mark.parametrize("command", [["apply"], ["challenge", "--challenge", "new-window"]]) +def test_a_template_and_domain_are_required(command: list[str], monkeypatch: pytest.MonkeyPatch) -> None: """Without them there is nothing to state to Fleet""" monkeypatch.setattr(config, "TEMPLATE", None) - result = CliRunner().invoke(cli_group, [command]) + result = CliRunner().invoke(cli_group, command) assert result.exit_code == 1 assert "ODMDM_FLEET_TEMPLATE" in result.output @@ -132,34 +132,6 @@ def test_a_dry_run_never_reaches_fleet(fleet: _Fleet, tmp_path: Path, monkeypatc assert not fleet.calls -def test_reconcile_leaves_fleet_alone_when_nobody_waits( - fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Re-asking reaches every phone in the team, so it happens only when it changes something""" - _template(tmp_path, monkeypatch) - fleet.hosts = [_host(4, "verified", named=True)] - - result = CliRunner().invoke(cli_group, ["reconcile", "--team", "rmscep"]) - - assert result.exit_code == 0, result.output - assert "Nothing waiting" in result.output - assert not [call for call in fleet.calls if call[0] != "GET"] - - -def test_reconcile_asks_again_for_a_phone_named_late( - fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Named after its first request failed: recreating the template is what asks again""" - _template(tmp_path, monkeypatch) - fleet.hosts = [_host(4, "failed", named=True)] - - result = CliRunner().invoke(cli_group, ["reconcile", "--team", "rmscep"]) - - assert result.exit_code == 0, result.output - assert "Asked again" in result.output - assert ("POST", "/api/latest/fleet/certificates") in fleet.calls - - def test_a_new_window_touches_only_the_authority( fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 0cb4186..9fabf46 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -315,29 +315,6 @@ def test_an_unchanged_certificate_template_is_left_alone(monkeypatch: pytest.Mon assert after == before, "an unchanged template must not be recreated" -def test_forcing_the_certificate_asks_again(monkeypatch: pytest.MonkeyPatch) -> None: - """The ordinary recovery: a device enrols before anyone can name it, so the first ask fails - - Fleet never retries a failed certificate, and the template is what asks. Recreating it is the - only way a host named after it enrolled ever gets one. - """ - fleet = _Fleet() - with_cert = MdmTemplate( - apps=TEMPLATE.apps, - policy=TEMPLATE.policy, - certificate=Certificate(name="rmscep", subject="CN=$VAR,OU=$OTHER", authority="RMSCEP"), - ) - mdm = _mdm(fleet, monkeypatch) - mdm.apply("rmscep", with_cert) - fleet.calls.clear() - mdm.apply("rmscep", with_cert, force_certificate=True) - - assert any(method == "DELETE" and "/certificates/" in path for method, path in fleet.calls) - assert any(method == "POST" and path.endswith("/certificates") for method, path in fleet.calls) - assert len(fleet.certificates) == 1, "the template is replaced, not duplicated" - assert fleet.certificates[0]["name"] == "rmscep", "the keystore alias has to stay the same" - - def _host(host_id: int, status: str, named: bool) -> dict[str, Any]: return { "id": host_id, @@ -346,27 +323,6 @@ def _host(host_id: int, status: str, named: bool) -> dict[str, Any]: } -def test_a_host_named_after_enrolment_is_waiting(monkeypatch: pytest.MonkeyPatch) -> None: - """Named, and still refused: asking again would now work""" - fleet = _Fleet() - fleet.hosts = [_host(1, "failed", named=True)] - assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [1] - - -def test_a_host_nobody_has_named_is_not_waiting(monkeypatch: pytest.MonkeyPatch) -> None: - """Asking again changes nothing until somebody names it, and re-asking is not free""" - fleet = _Fleet() - fleet.hosts = [_host(2, "failed", named=False)] - assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [] - - -def test_a_host_that_already_has_its_certificate_is_not_waiting(monkeypatch: pytest.MonkeyPatch) -> None: - """Otherwise every pass would re-ask the whole group forever""" - fleet = _Fleet() - fleet.hosts = [_host(3, "verified", named=True)] - assert _mdm(fleet, monkeypatch).hosts_awaiting_certificate(1, "rmscep") == [] - - def test_the_only_waiting_phone_is_named(monkeypatch: pytest.MonkeyPatch) -> None: """Enrol one, name it, enrol the next: phones already named are left alone""" fleet = _Fleet() From fa9b3a6d95e169b262ae6a160461b5322424f4b9 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Tue, 3 Nov 2026 08:46:41 +0100 Subject: [PATCH 010/104] fix: refuse to replace a certificate template on a team with devices --- src/odmdm_fleet/fleet.py | 18 ++++++++++++++++-- tests/test_fleet.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 6b00c18..ee6cc99 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -331,6 +331,10 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str) There is no update in place, so a changed subject is delete then create. The name is kept because it becomes the Android keystore alias, and a device already holding a key under one alias will not accept a second. + + Refused while the team has devices. Replacing the template makes each of them delete the + certificate it has and ask again, and the deployment refuses a name that is already taken, + so all of them would lose access (measured on Fleet 4.90). """ authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) match = [a for a in authorities if a.get("name") == authority] @@ -348,6 +352,13 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str) and int(template.get("certificate_authority_id", 0)) == authority_id ): return int(template["id"]) + devices = len(self._hosts(team)) + if devices: + raise FleetError( + f"replacing certificate template {name} would delete the certificate of {devices} devices in " + f"team {team}, and their names would be refused when they ask again, so nothing was changed. " + "Use a new team, or empty this one first." + ) self._call("DELETE", f"/api/latest/fleet/certificates/{template['id']}?team_id={team}") LOGGER.info("Replacing certificate template %s", name) @@ -361,6 +372,10 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str) # --- naming --------------------------------------------------------------- + def _hosts(self, team: int) -> list[dict[str, Any]]: + """The devices in a team""" + return self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] + def _name_of(self, host_id: int) -> str: """The name a host was given, or empty if nobody has named it""" mapping = self._call("GET", f"/api/latest/fleet/hosts/{host_id}/device_mapping").get("device_mapping") or [] @@ -374,8 +389,7 @@ def name_the_waiting_host(self, team: int, callsign: str) -> int: two waiting nobody can tell which is the phone in hand, and guessing puts the callsign on somebody else's phone, so that is refused rather than picked. """ - hosts = self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] - waiting = [int(host["id"]) for host in hosts if not self._name_of(int(host["id"]))] + waiting = [int(host["id"]) for host in self._hosts(team) if not self._name_of(int(host["id"]))] if not waiting: raise FleetError(f"no device in team {team} is waiting for a name: enrol the phone first") if len(waiting) > 1: diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 9fabf46..e5f1e6e 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -315,6 +315,39 @@ def test_an_unchanged_certificate_template_is_left_alone(monkeypatch: pytest.Mon assert after == before, "an unchanged template must not be recreated" +def test_a_changed_template_on_a_team_without_devices_is_replaced(monkeypatch: pytest.MonkeyPatch) -> None: + """There is no update in place, and the name has to survive as the keystore alias""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + changed = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$OTHER", authority="RMSCEP"), + ) + _mdm(fleet, monkeypatch).apply("rmscep", changed) + + assert [(c["name"], c["subject_name"]) for c in fleet.certificates] == [("rmscep", "CN=$OTHER")] + + +def test_a_changed_template_on_a_team_with_devices_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """Measured: every device deletes its certificate, asks again, and is refused its own name""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + fleet.hosts = [_host(1, "verified", named=True)] + fleet.calls.clear() + changed = MdmTemplate( + apps=TEMPLATE.apps, + policy=TEMPLATE.policy, + certificate=Certificate(name="rmscep", subject="CN=$OTHER", authority="RMSCEP"), + ) + + with pytest.raises(FleetError, match="1 devices in team 7"): + _mdm(fleet, monkeypatch).apply("rmscep", changed) + + assert not [call for call in fleet.calls if call[0] == "DELETE"] + assert fleet.certificates[0]["subject_name"] == "CN=$VAR,OU=$OTHER" + + def _host(host_id: int, status: str, named: bool) -> dict[str, Any]: return { "id": host_id, From acf6d2201bb48f619a582869df6e4701e2519a4c Mon Sep 17 00:00:00 2001 From: benjamsf Date: Tue, 3 Nov 2026 08:46:42 +0100 Subject: [PATCH 011/104] fix: refuse --instead-of while a device waits for a name --- README.rst | 3 ++- src/odmdm_fleet/fleet.py | 14 ++++++++++++-- tests/test_fleet.py | 14 ++++++++++++-- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 2a76f8f..63f126a 100644 --- a/README.rst +++ b/README.rst @@ -127,7 +127,8 @@ What Fleet does that you would not guess has to be removed there before it can be removed from the team. - **A returning phone keeps its old team and its old name.** Transfer it to the preparation team and rename it with ``odmdm-fleet plan NEWNAME --instead-of OLDNAME``, or it asks for a name that - is already taken. + is already taken. It can also come back as a new device with no name, so ``--instead-of`` refuses + while one is waiting: name that one with plain ``plan``. - **Renaming a phone that has its certificate gives it a second callsign.** Revoke the old one in Deploy App. - **Replacing a team's certificate template locks its phones out.** Every phone deletes the diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index ee6cc99..21581e2 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -404,9 +404,19 @@ def rename_host(self, team: int, old: str, callsign: str) -> int: A phone that comes back after a wipe keeps the name it had, so it is not waiting to be named and name_the_waiting_host cannot reach it. Its old name is what tells it apart. Names are compared without case, as the deployment compares callsigns. + + A phone can also come back as a new host, and then the old name finds a row nothing is + using. Fleet shows no difference between them, so this is refused while any device waits + for a name: that one may be the phone in hand. """ - hosts = self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] - called = [int(host["id"]) for host in hosts if self._name_of(int(host["id"])).lower() == old.lower()] + names = {int(host["id"]): self._name_of(int(host["id"])) for host in self._hosts(team)} + waiting = [host for host, name in names.items() if not name] + if waiting: + raise FleetError( + f"{len(waiting)} devices in team {team} wait for a name, so none was renamed: a phone can come " + "back as a new device. Name that one with plan and no --instead-of" + ) + called = [host for host, name in names.items() if name.lower() == old.lower()] if len(called) != 1: raise FleetError(f"{len(called)} devices in team {team} are called {old}, so none was renamed") self._call("PUT", f"/api/latest/fleet/hosts/{called[0]}/device_mapping", {"email": callsign, "source": "idp"}) diff --git a/tests/test_fleet.py b/tests/test_fleet.py index e5f1e6e..7173c29 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -382,12 +382,22 @@ def test_no_phone_is_named_unless_exactly_one_waits(monkeypatch: pytest.MonkeyPa def test_a_returning_phone_is_renamed_by_its_old_name(monkeypatch: pytest.MonkeyPatch) -> None: """It kept its name through the wipe, so it is not waiting, and only its old name finds it""" fleet = _Fleet() - fleet.hosts = [_host(1, "verified", named=True), _host(2, "failed", named=False)] + fleet.hosts = [_host(1, "verified", named=True)] assert _mdm(fleet, monkeypatch).rename_host(8, "otter1@code", "KETTU1") == 1 assert fleet.hosts[0]["device_mapping"] == [{"email": "KETTU1", "source": "idp"}] - assert fleet.hosts[1].get("device_mapping") == [] + + +def test_no_phone_is_renamed_while_another_waits_for_a_name(monkeypatch: pytest.MonkeyPatch) -> None: + """Measured: a phone came back as a new host, and its old name found a row nothing was using""" + fleet = _Fleet() + fleet.hosts = [_host(1, "verified", named=True), _host(2, "failed", named=False)] + + with pytest.raises(FleetError, match="1 devices in team 8 wait for a name"): + _mdm(fleet, monkeypatch).rename_host(8, "otter1@code", "KETTU1") + + assert not [call for call in fleet.calls if call[0] == "PUT"] def test_a_name_nobody_has_renames_nothing(monkeypatch: pytest.MonkeyPatch) -> None: From bab0ce83f79ce2736ce66292f4943ffc00e891b4 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 22:27:13 +0200 Subject: [PATCH 012/104] fix!: one team, no preparation team --- README.rst | 3 --- src/odmdm_fleet/config.py | 3 --- src/odmdm_fleet/console.py | 15 ++------------- src/odmdm_fleet/fleet.py | 24 +----------------------- tests/test_console.py | 13 +++++-------- tests/test_fleet.py | 26 +------------------------- 6 files changed, 9 insertions(+), 75 deletions(-) diff --git a/README.rst b/README.rst index 63f126a..5ded113 100644 --- a/README.rst +++ b/README.rst @@ -72,9 +72,6 @@ All configuration is via environment variables: ``ODMDM_FLEET_TEAM`` The team whose phones get the certificate. Default ``Deploy App``. -``ODMDM_FLEET_PREP_TEAM`` - The team phones enrol into and are named in. Empty for a single team. - ``ODMDM_FLEET_TEMPLATE`` The document saying what to install, see below. diff --git a/src/odmdm_fleet/config.py b/src/odmdm_fleet/config.py index f022246..07ef57e 100644 --- a/src/odmdm_fleet/config.py +++ b/src/odmdm_fleet/config.py @@ -23,9 +23,6 @@ def _env(name: str, default: str = "") -> str: #: The team whose devices get the deployment's certificate TEAM: str = _env("TEAM", "Deploy App") -#: The team devices enrol into and are named in before they move to TEAM. Empty for none. -PREP_TEAM: str = _env("PREP_TEAM") - #: What this deployment wants installed, as a document. See odmdm_fleet.template. TEMPLATE: Path | None = Path(_env("TEMPLATE")) if _env("TEMPLATE") else None diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 0f85342..0f634bf 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -77,11 +77,6 @@ def _template(ctx: click.Context, path: str | None, domain: str | None) -> templ @click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") @click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") @click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_FLEET_TEAM)") -@click.option( - "--prep-team", - default=None, - help="Also set up this team, where devices enrol and are named first (default: ODMDM_FLEET_PREP_TEAM)", -) @click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") @click.option( "--force-policy", is_flag=True, help="Re-upload the policy even if unchanged, to reach a host that just joined" @@ -92,7 +87,6 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments path: str | None, fleet_url: str | None, team: str | None, - prep_team: str | None, domain: str | None, force_policy: bool, dry_run: bool, @@ -122,7 +116,6 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments fleet = _fleet(ctx, fleet_url) if not fleet: return - the_prep_team = prep_team or config.PREP_TEAM try: result = fleet.apply( team or config.TEAM, @@ -131,15 +124,11 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments scep_url=f"https://{domain or config.DOMAIN}/scep", challenge=config.CHALLENGE, ) - if the_prep_team: - prep = fleet.apply_preparation(the_prep_team, wanted, result["link"], force_policy=force_policy) except FleetError as exc: click.echo(f"Fleet refused: {exc}", err=True) ctx.exit(1) return click.echo(f"Applied to team {result['team_id']}: {len(result['assigned'])} apps assigned") - if the_prep_team: - click.echo(f"Applied to preparation team {prep['team_id']}: the same apps and launcher, no certificate") ctx.exit(0) @@ -192,7 +181,7 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen @click.option( "--team", default=None, - help="The team the device waits in (default: ODMDM_FLEET_PREP_TEAM, else ODMDM_FLEET_TEAM)", + help="The team the device waits in (default: ODMDM_FLEET_TEAM)", ) @click.option("--instead-of", "old", default=None, help="Rename the device now called this, such as a returning phone") def plan( # pylint: disable=too-many-arguments,too-many-positional-arguments @@ -215,7 +204,7 @@ def plan( # pylint: disable=too-many-arguments,too-many-positional-arguments if not fleet: return try: - team_id = fleet.team_id(team or config.PREP_TEAM or config.TEAM) + team_id = fleet.team_id(team or config.TEAM) if old: host = fleet.rename_host(team_id, old, callsign) else: diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 21581e2..fb8c68f 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -4,7 +4,6 @@ say which. None of it mentions a product: what to install arrives in the template. """ -import dataclasses import json import logging import time @@ -432,7 +431,6 @@ def apply( force_policy: bool = False, scep_url: str = "", challenge: str = "", - link_package: str = "", ) -> dict[str, Any]: """State everything the template says, in the order that actually works @@ -444,8 +442,6 @@ def apply( Given scep_url, the certificate authority is created too, so a fresh deployment needs nothing typed into Fleet by hand. Without it the authority must already be there, which is the case for an MDM we cannot create one in. - - Given link_package, that launcher is assigned instead of looking one up or publishing one. """ team = self.team_id(team_name) if template.certificate: @@ -462,7 +458,7 @@ def apply( packages = [app.package for app in template.apps] preinstall = list(template.preinstall_packages) if template.link_app: - link = link_package or self.ensure_link_app(team, template.link_app.title, template.link_app.url) + link = self.ensure_link_app(team, template.link_app.title, template.link_app.url) packages.append(link) preinstall.append(link) @@ -485,22 +481,4 @@ def apply( "team_id": team, "assigned": sorted(assigned), "preinstall": sorted(preinstall), - "link": link if template.link_app else "", } - - def apply_preparation( - self, team_name: str, template: MdmTemplate, link_package: str, force_policy: bool = False - ) -> dict[str, Any]: - """The team devices enrol into and get named in, before they move to the certificate team - - Everything but the certificate, so nothing is asked for before the device has its name. - The launcher has to be the very package the certificate team holds: apps install only at - enrolment, so a device moving to a team with another launcher package has it uninstalled - and never gets the other one. - """ - return self.apply( - team_name, - dataclasses.replace(template, certificate=None), - force_policy=force_policy, - link_package=link_package, - ) diff --git a/tests/test_console.py b/tests/test_console.py index 0d11e56..738e506 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -18,12 +18,12 @@ @pytest.fixture def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: - """A configured connector talking to a stubbed Fleet whose preparation team is "prep" """ + """A configured connector talking to a stubbed Fleet whose team is "rmscep" """ token = tmp_path / "token" token.write_text("token\n", encoding="utf-8") monkeypatch.setattr(config, "URL", "https://mdm.test") monkeypatch.setattr(config, "TOKEN_FILE", token) - monkeypatch.setattr(config, "PREP_TEAM", "prep") + monkeypatch.setattr(config, "TEAM", "rmscep") stub = _Fleet() _mdm(stub, monkeypatch) return stub @@ -106,18 +106,15 @@ def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(config, "DOMAIN", "example.fi") -def test_apply_states_the_template_to_both_teams( - fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """The certificate team gets the certificate, the preparation team everything else""" +def test_apply_states_the_template(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """One team: phones enrol into the team that has the certificate template""" _template(tmp_path, monkeypatch) monkeypatch.setattr(config, "CHALLENGE", "new-window") - result = CliRunner().invoke(cli_group, ["apply", "--team", "rmscep"]) + result = CliRunner().invoke(cli_group, ["apply"]) assert result.exit_code == 0, result.output assert "Applied to team 7" in result.output - assert "Applied to preparation team 8" in result.output assert fleet.authorities[0]["challenge"] == "new-window" assert fleet.authorities[0]["url"] == "https://example.fi/scep" diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 7173c29..2d7bc08 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -99,7 +99,7 @@ def handler(self, request: httpx.Request) -> httpx.Response: self.certificates = [c for c in self.certificates if c["id"] != gone] return httpx.Response(200, json={}) if path == "/api/latest/fleet/teams" and request.method == "GET": - return httpx.Response(200, json={"teams": [{"id": 7, "name": "rmscep"}, {"id": 8, "name": "prep"}]}) + return httpx.Response(200, json={"teams": [{"id": 7, "name": "rmscep"}]}) if path.endswith("/software/titles"): # Fleet scopes the listing to one team. A stub that ignored team_id would let a # lookup find another team's app and call that a pass. @@ -506,30 +506,6 @@ def test_applying_twice_publishes_one_web_app(monkeypatch: pytest.MonkeyPatch) - assert len(launchers) == 1, "the team must end up with one launcher, not one per run" -def test_the_preparation_team_holds_the_same_launcher_and_no_certificate(monkeypatch: pytest.MonkeyPatch) -> None: - """A device moving from the preparation team keeps the apps it enrolled with, and only those - - So the launcher has to be the same package in both teams. One of its own is another package, - which the move uninstalls and nothing installs again: the phone loses its Deploy App icon. - """ - fleet = _Fleet() - template = MdmTemplate( - apps=TEMPLATE.apps, - policy=TEMPLATE.policy, - link_app=LinkApp(title="Deploy App", url="https://same.test/"), - certificate=Certificate(name="rmscep", subject="CN=$VAR", authority="RMSCEP"), - ) - mdm = _mdm(fleet, monkeypatch) - main = mdm.apply("rmscep", template) - fleet.calls.clear() - prep = mdm.apply_preparation("prep", template, main["link"]) - - assert len(fleet.web_apps) == 1, "the preparation team must not publish a launcher of its own" - assert main["link"] in prep["assigned"] - assert prep["assigned"] == main["assigned"] - assert not [p for _, p in fleet.calls if p.endswith("/certificates")], "nothing is asked for before the name" - - def test_a_wiped_team_says_what_is_wrong_instead_of_just_409(monkeypatch: pytest.MonkeyPatch) -> None: """A name published to a team that no longer exists must fail legibly From e4226a718fe9c0295f84e38a0c0521fa79ffe031 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 22:27:34 +0200 Subject: [PATCH 013/104] fix!: remove plan, it names one phone at a time --- src/odmdm_fleet/console.py | 42 ----------------------------- src/odmdm_fleet/fleet.py | 47 -------------------------------- tests/test_console.py | 52 +---------------------------------- tests/test_fleet.py | 55 -------------------------------------- 4 files changed, 1 insertion(+), 195 deletions(-) diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 0f634bf..a1f4110 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -173,45 +173,3 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen click.echo(f"{wanted.certificate.authority} has the new challenge") ctx.exit(0) - -@cli_group.command(name="plan") -@click.pass_context -@click.argument("callsign") -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option( - "--team", - default=None, - help="The team the device waits in (default: ODMDM_FLEET_TEAM)", -) -@click.option("--instead-of", "old", default=None, help="Rename the device now called this, such as a returning phone") -def plan( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, callsign: str, fleet_url: str | None, team: str | None, old: str | None -) -> None: - """Name the one device waiting to be named - - Enrol a phone, run this, then the next phone. With more than one phone waiting nothing is - named: Fleet shows identical phones as identical rows, so the one in your hand cannot be told - apart from the others. - - A phone that comes back after a wipe keeps its old name, so it is not waiting. Rename it with - --instead-of and the name it had. - """ - if not CALLSIGN.fullmatch(callsign): - click.echo("A callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen", err=True) - ctx.exit(1) - return - fleet = _fleet(ctx, fleet_url) - if not fleet: - return - try: - team_id = fleet.team_id(team or config.TEAM) - if old: - host = fleet.rename_host(team_id, old, callsign) - else: - host = fleet.name_the_waiting_host(team_id, callsign) - except FleetError as exc: - click.echo(f"Not named: {exc}", err=True) - ctx.exit(1) - return - click.echo(f"Host {host} is {callsign}") - ctx.exit(0) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index fb8c68f..caac9c7 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -375,53 +375,6 @@ def _hosts(self, team: int) -> list[dict[str, Any]]: """The devices in a team""" return self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] - def _name_of(self, host_id: int) -> str: - """The name a host was given, or empty if nobody has named it""" - mapping = self._call("GET", f"/api/latest/fleet/hosts/{host_id}/device_mapping").get("device_mapping") or [] - return next((str(entry["email"]) for entry in mapping if entry.get("email")), "") - - def name_the_waiting_host(self, team: int, callsign: str) -> int: - """Give the one unnamed host in the team its callsign - - Identical phones look identical here: brand and model, and an enrolment ID that nothing on - the phone shows. So the only host that can be named safely is the only one waiting. With - two waiting nobody can tell which is the phone in hand, and guessing puts the callsign on - somebody else's phone, so that is refused rather than picked. - """ - waiting = [int(host["id"]) for host in self._hosts(team) if not self._name_of(int(host["id"]))] - if not waiting: - raise FleetError(f"no device in team {team} is waiting for a name: enrol the phone first") - if len(waiting) > 1: - raise FleetError(f"{len(waiting)} devices in team {team} wait for a name, so none was: enrol one at a time") - self._call("PUT", f"/api/latest/fleet/hosts/{waiting[0]}/device_mapping", {"email": callsign, "source": "idp"}) - LOGGER.info("Named host %s %s", waiting[0], callsign) - return waiting[0] - - def rename_host(self, team: int, old: str, callsign: str) -> int: - """Give the host in the team now called `old` a new callsign - - A phone that comes back after a wipe keeps the name it had, so it is not waiting to be - named and name_the_waiting_host cannot reach it. Its old name is what tells it apart. - Names are compared without case, as the deployment compares callsigns. - - A phone can also come back as a new host, and then the old name finds a row nothing is - using. Fleet shows no difference between them, so this is refused while any device waits - for a name: that one may be the phone in hand. - """ - names = {int(host["id"]): self._name_of(int(host["id"])) for host in self._hosts(team)} - waiting = [host for host, name in names.items() if not name] - if waiting: - raise FleetError( - f"{len(waiting)} devices in team {team} wait for a name, so none was renamed: a phone can come " - "back as a new device. Name that one with plan and no --instead-of" - ) - called = [host for host, name in names.items() if name.lower() == old.lower()] - if len(called) != 1: - raise FleetError(f"{len(called)} devices in team {team} are called {old}, so none was renamed") - self._call("PUT", f"/api/latest/fleet/hosts/{called[0]}/device_mapping", {"email": callsign, "source": "idp"}) - LOGGER.info("Renamed host %s from %s to %s", called[0], old, callsign) - return called[0] - # --- the whole statement -------------------------------------------------- def apply( diff --git a/tests/test_console.py b/tests/test_console.py index 738e506..af702d0 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -13,7 +13,7 @@ from odmdm_fleet import config from odmdm_fleet.console import cli_group -from .test_fleet import _Fleet, _host, _mdm +from .test_fleet import _Fleet, _mdm @pytest.fixture @@ -29,56 +29,6 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: return stub -@pytest.mark.parametrize("callsign", ["OT", "OTTER-", "OTTER_1", "X" * 33]) -def test_plan_refuses_a_callsign_the_deployment_would(callsign: str) -> None: - """Now, rather than as a failed certificate twenty minutes later, and before Fleet is touched""" - result = CliRunner().invoke(cli_group, ["plan", callsign]) - - assert result.exit_code == 1 - assert "3-32 letters" in result.output - - -def test_plan_names_the_waiting_phone(fleet: _Fleet) -> None: - """The one in your hand is the only one waiting""" - fleet.hosts = [_host(4, "failed", named=False)] - - result = CliRunner().invoke(cli_group, ["plan", "OTTER4"]) - - assert result.exit_code == 0, result.output - assert "Host 4 is OTTER4" in result.output - assert fleet.hosts[0]["device_mapping"][0]["email"] == "OTTER4" - - -def test_plan_renames_a_returning_phone(fleet: _Fleet) -> None: - """Named before the wipe, so the old name is how the operator points at it""" - fleet.hosts = [_host(4, "failed", named=True)] - - result = CliRunner().invoke(cli_group, ["plan", "KETTU4", "--instead-of", "OTTER1@CODE"]) - - assert result.exit_code == 0, result.output - assert fleet.hosts[0]["device_mapping"][0]["email"] == "KETTU4" - - -def test_plan_says_why_it_named_nobody(fleet: _Fleet) -> None: - """Two phones waiting: the operator learns to enrol them one at a time""" - fleet.hosts = [_host(4, "failed", named=False), _host(5, "failed", named=False)] - - result = CliRunner().invoke(cli_group, ["plan", "OTTER4"]) - - assert result.exit_code == 1 - assert "one at a time" in result.output - - -def test_plan_needs_somewhere_to_send_it(monkeypatch: pytest.MonkeyPatch) -> None: - """No Fleet configured is a sentence, not a traceback""" - monkeypatch.setattr(config, "URL", "") - - result = CliRunner().invoke(cli_group, ["plan", "OTTER4"]) - - assert result.exit_code == 1 - assert "ODMDM_FLEET_URL" in result.output - - @pytest.mark.parametrize("command", [["apply"], ["challenge", "--challenge", "new-window"]]) def test_a_template_and_domain_are_required(command: list[str], monkeypatch: pytest.MonkeyPatch) -> None: """Without them there is nothing to state to Fleet""" diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 2d7bc08..0a88e78 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -356,61 +356,6 @@ def _host(host_id: int, status: str, named: bool) -> dict[str, Any]: } -def test_the_only_waiting_phone_is_named(monkeypatch: pytest.MonkeyPatch) -> None: - """Enrol one, name it, enrol the next: phones already named are left alone""" - fleet = _Fleet() - fleet.hosts = [_host(1, "verified", named=True), _host(2, "failed", named=False)] - - assert _mdm(fleet, monkeypatch).name_the_waiting_host(8, "OTTER2") == 2 - - assert fleet.hosts[1]["device_mapping"] == [{"email": "OTTER2", "source": "idp"}] - assert fleet.hosts[0]["device_mapping"][0]["email"] == "OTTER1@CODE" - - -@pytest.mark.parametrize(("unnamed", "says"), [(0, "enrol the phone first"), (2, "one at a time")]) -def test_no_phone_is_named_unless_exactly_one_waits(monkeypatch: pytest.MonkeyPatch, unnamed: int, says: str) -> None: - """Identical phones are identical rows, and a guess names somebody else's phone""" - fleet = _Fleet() - fleet.hosts = [_host(1, "verified", named=True)] + [_host(10 + i, "failed", named=False) for i in range(unnamed)] - - with pytest.raises(FleetError, match=says): - _mdm(fleet, monkeypatch).name_the_waiting_host(8, "OTTER2") - - assert not [call for call in fleet.calls if call[0] == "PUT"] - - -def test_a_returning_phone_is_renamed_by_its_old_name(monkeypatch: pytest.MonkeyPatch) -> None: - """It kept its name through the wipe, so it is not waiting, and only its old name finds it""" - fleet = _Fleet() - fleet.hosts = [_host(1, "verified", named=True)] - - assert _mdm(fleet, monkeypatch).rename_host(8, "otter1@code", "KETTU1") == 1 - - assert fleet.hosts[0]["device_mapping"] == [{"email": "KETTU1", "source": "idp"}] - - -def test_no_phone_is_renamed_while_another_waits_for_a_name(monkeypatch: pytest.MonkeyPatch) -> None: - """Measured: a phone came back as a new host, and its old name found a row nothing was using""" - fleet = _Fleet() - fleet.hosts = [_host(1, "verified", named=True), _host(2, "failed", named=False)] - - with pytest.raises(FleetError, match="1 devices in team 8 wait for a name"): - _mdm(fleet, monkeypatch).rename_host(8, "otter1@code", "KETTU1") - - assert not [call for call in fleet.calls if call[0] == "PUT"] - - -def test_a_name_nobody_has_renames_nothing(monkeypatch: pytest.MonkeyPatch) -> None: - """A typo in the old name must not land the new one on some other phone""" - fleet = _Fleet() - fleet.hosts = [_host(1, "verified", named=True)] - - with pytest.raises(FleetError, match="0 devices"): - _mdm(fleet, monkeypatch).rename_host(8, "OTTER9", "KETTU1") - - assert not [call for call in fleet.calls if call[0] == "PUT"] - - def _with_cert(authority: str = "RMSCEP") -> MdmTemplate: """A template that asks for a certificate, which is what drags the authority in""" return MdmTemplate( From 6c06317a9dc6d9b46ae9cc12261e22125858bc2f Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 22:28:56 +0200 Subject: [PATCH 014/104] feat: list the team's phones and where each certificate is --- src/odmdm_fleet/console.py | 25 +++++++++++ src/odmdm_fleet/fleet.py | 71 +++++++++++++++++++++++++++++++ tests/test_console.py | 86 +++++++++++++++++++++++++++++++++++++- tests/test_fleet.py | 33 ++++++++++++--- 4 files changed, 208 insertions(+), 7 deletions(-) diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index a1f4110..67c2ac8 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -173,3 +173,28 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen click.echo(f"{wanted.certificate.authority} has the new challenge") ctx.exit(0) + +@cli_group.command(name="phones") +@click.pass_context +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_FLEET_TEAM)") +def phones(ctx: click.Context, fleet_url: str | None, team: str | None) -> None: + """List the team's phones and where each one's certificate is + + One line each: the host id that name and resend take, the callsign, the model, the day it + enrolled, and the certificate in plain words. + """ + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + try: + found = fleet.phones(fleet.team_id(team or config.TEAM), config.KEY_ALIAS) + except FleetError as exc: + click.echo(f"Fleet refused: {exc}", err=True) + ctx.exit(1) + return + for phone in found: + click.echo(f"{phone.id:<5} {phone.callsign or '-':<12} {phone.model:<26} {phone.enrolled[:10]} {phone.state}") + if not found: + click.echo("No phones in the team") + ctx.exit(0) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index caac9c7..f9960fe 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -4,6 +4,7 @@ say which. None of it mentions a product: what to install arrives in the template. """ +import dataclasses import json import logging import time @@ -34,6 +35,49 @@ class FleetError(RuntimeError): POLICY_NAME = "rmscep-policy" +@dataclasses.dataclass(frozen=True) +class Phone: + """A device in the team, and how far its certificate has got""" + + id: int + #: What the certificate's common name becomes: the name Fleet holds up to any "@". Empty while + #: nobody has named the phone. + callsign: str + model: str + enrolled: str + #: The certificate row's status and Fleet's detail on it. No status: nothing was asked for. + status: str + detail: str + + @property + def state(self) -> str: + """Where the certificate is, in words an operator can act on + + The details matched are the ones seen on a live Fleet 4.90.1. A phone acts on a request at + its next check-in, every 15 minutes. After a failure a phone reports, Fleet asks again by + itself up to three times, and that request keeps the failure's detail while it waits. + """ + if not self.status: + return "no certificate requested" + if self.status == "verified": + return "has its certificate" + if self.status == "failed": + return self._failure + waiting = "requested, waiting for the phone (up to 15 minutes)" + return f"{waiting}; last time: {self._failure}" if self.detail else waiting + + @property + def _failure(self) -> str: + """What Fleet's detail on a failed request means""" + if "does not have an IDP user" in self.detail: + return "waiting for a name" + if "SCEP enrollment failed" in self.detail: + return "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old challenge" + if "Network error" in self.detail: + return "could not reach Deploy App" + return self.detail or "failed" + + class FleetMdm: """What this feature needs an MDM to be able to do, in Fleet's words""" @@ -375,6 +419,33 @@ def _hosts(self, team: int) -> list[dict[str, Any]]: """The devices in a team""" return self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] + def phones(self, team: int, certificate: str) -> list[Phone]: + """The team's devices in enrolment order, each with its name and its certificate row + + The row is the install of the certificate template called `certificate`. A host can show + an old remove row of the same name beside the new one for a while, and that one is history. + """ + found = [] + for listed in self._hosts(team): + host = self._call("GET", f"/api/latest/fleet/hosts/{listed['id']}").get("host") or {} + users = host.get("end_users") or [] + name = next((str(user["idp_username"]) for user in users if user.get("idp_username")), "") + rows = (host.get("mdm") or {}).get("profiles") or [] + row: dict[str, Any] = next( + (r for r in rows if r.get("name") == certificate and r.get("operation_type") == "install"), {} + ) + found.append( + Phone( + id=int(listed["id"]), + callsign=name.split("@")[0], + model=str(host.get("hardware_model") or ""), + enrolled=str(host.get("last_enrolled_at") or ""), + status=str(row.get("status") or ""), + detail=str(row.get("detail") or ""), + ) + ) + return sorted(found, key=lambda phone: (phone.enrolled, phone.id)) + # --- the whole statement -------------------------------------------------- def apply( diff --git a/tests/test_console.py b/tests/test_console.py index af702d0..0c0a178 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -13,7 +13,7 @@ from odmdm_fleet import config from odmdm_fleet.console import cli_group -from .test_fleet import _Fleet, _mdm +from .test_fleet import _Fleet, _host, _mdm @pytest.fixture @@ -92,3 +92,87 @@ def test_a_new_window_touches_only_the_authority( assert fleet.authorities[0]["challenge"] == "new-window" changed = {path for method, path in fleet.calls if method != "GET"} assert changed == {"/api/latest/fleet/certificate_authorities/3"} + + +def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: + """No Fleet configured is a sentence, not a traceback""" + monkeypatch.setattr(config, "URL", "") + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 1 + assert "ODMDM_FLEET_URL" in result.output + + +NO_NAME = ( + "Could not replace certificate variables: host 6f1c0e52-9a6b-4b8e-8f43-2d0c5f6a1b7e does not have an IDP user " + "for variable FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" +) +REFUSED = "SCEP enrollment failed: Enrollment failed with SCEP failInfo: badMessageCheck" +UNREACHED = "Network error during SCEP enrollment: Failed to communicate with SCEP server" + + +@pytest.mark.parametrize( + ("status", "detail", "says"), + [ + ("", "", "no certificate requested"), + ("failed", NO_NAME, "waiting for a name"), + ("pending", "", "requested, waiting for the phone (up to 15 minutes)"), + ("delivering", "", "requested, waiting for the phone (up to 15 minutes)"), + ("delivered", "", "requested, waiting for the phone (up to 15 minutes)"), + ("pending", REFUSED, "requested, waiting for the phone (up to 15 minutes); last time: refused by Deploy App"), + ("delivered", UNREACHED, "waiting for the phone (up to 15 minutes); last time: could not reach Deploy App"), + ("verified", "", "has its certificate"), + ("failed", REFUSED, "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old"), + ("failed", UNREACHED, "could not reach Deploy App"), + ("failed", "Something Fleet says that nobody has seen yet", "Something Fleet says that nobody has seen yet"), + ], +) +def test_phones_says_where_each_certificate_is(fleet: _Fleet, status: str, detail: str, says: str) -> None: + """In words an operator can act on, rather than Fleet's status and detail""" + fleet.hosts = [_host(31, status, "OTTER4", detail)] + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 0, result.output + assert result.output.split()[:4] == ["31", "OTTER4", "Google", "sdk_gphone64_arm64"] + assert "2026-11-01" in result.output + assert says in result.output + + +def test_a_phone_fresh_from_enrolment_waits_for_a_name(fleet: _Fleet) -> None: + """Its first request fails for want of one""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 0, result.output + assert result.output.split()[:2] == ["31", "-"] + assert result.output.rstrip().endswith("waiting for a name") + + +def test_phones_lists_in_enrolment_order_with_the_callsign_fleet_issues(fleet: _Fleet) -> None: + """The certificate carries the name up to its "@"; an old remove row is history, not state""" + fleet.hosts = [ + _host(32, "verified", "OTTER1@CODE", enrolled="2026-11-02T08:00:00Z"), + _host(33, enrolled="2026-11-01T08:00:00Z"), + ] + fleet.hosts[0]["mdm"]["profiles"].insert( + 0, {"name": "rmscep", "status": "failed", "operation_type": "remove", "detail": REFUSED} + ) + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 0, result.output + lines = result.output.splitlines() + assert lines[0].split()[:2] == ["33", "-"] + assert lines[1].split()[:2] == ["32", "OTTER1"] + assert lines[1].endswith("has its certificate") + + +def test_an_empty_team_says_so(fleet: _Fleet) -> None: + """Rather than printing nothing, which reads as a failure""" + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 0, result.output + assert "No phones in the team" in result.output diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 0a88e78..3d99606 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -51,8 +51,7 @@ def handler(self, request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"device_mapping": found.get("device_mapping") or []}) if "/hosts/" in path and request.method == "GET": which = int(path.rsplit("/", 1)[-1]) - found = next(h for h in self.hosts if h["id"] == which) - return httpx.Response(200, json={"host": {"mdm": {"profiles": found.get("profiles") or []}}}) + return httpx.Response(200, json={"host": next(h for h in self.hosts if h["id"] == which)}) if path.endswith("/certificate_authorities") and request.method == "GET": # Fleet's listing omits the url; only the detail carries it. Mirrored so a check # that reads the url off the listing fails here too. @@ -333,7 +332,7 @@ def test_a_changed_template_on_a_team_with_devices_is_refused(monkeypatch: pytes """Measured: every device deletes its certificate, asks again, and is refused its own name""" fleet = _Fleet() _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) - fleet.hosts = [_host(1, "verified", named=True)] + fleet.hosts = [_host(1, "verified", "OTTER1")] fleet.calls.clear() changed = MdmTemplate( apps=TEMPLATE.apps, @@ -348,11 +347,33 @@ def test_a_changed_template_on_a_team_with_devices_is_refused(monkeypatch: pytes assert fleet.certificates[0]["subject_name"] == "CN=$VAR,OU=$OTHER" -def _host(host_id: int, status: str, named: bool) -> dict[str, Any]: +def _host( + host_id: int, status: str = "", name: str = "", detail: str = "", enrolled: str = "2026-11-01T19:38:12Z" +) -> dict[str, Any]: + """A phone as Fleet's host detail shows it, its certificate row left out when there is no status + + The policy's row is there too, so that only the certificate's row is read as the certificate. + """ + rows: list[dict[str, Any]] = [ + {"profile_uuid": "g4bb", "name": "rmscep-policy", "status": "verified", "operation_type": "install"} + ] + if status: + rows.append( + { + "profile_uuid": "fleet-host-certificate-template", + "name": "rmscep", + "status": status, + "operation_type": "install", + "detail": detail, + "certificate_template_id": 81, + } + ) return { "id": host_id, - "profiles": [{"name": "rmscep", "status": status}], - "device_mapping": [{"email": "OTTER1@CODE", "source": "mdm_idp_accounts"}] if named else [], + "hardware_model": "Google sdk_gphone64_arm64", + "last_enrolled_at": enrolled, + "end_users": [{"idp_username": name, "idp_info_updated_at": None}] if name else [], + "mdm": {"profiles": rows}, } From ed26928cb7b60e61c8f9cf0322c1cdc8e635da98 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 22:31:25 +0200 Subject: [PATCH 015/104] feat: name any number of phones, and have Fleet resend their certificates --- examples/template.json | 2 +- src/odmdm_fleet/console.py | 123 +++++++++++++++++++++++++- src/odmdm_fleet/fleet.py | 32 +++++++ tests/test_console.py | 175 ++++++++++++++++++++++++++++++++++++- tests/test_fleet.py | 43 +++++++-- 5 files changed, 366 insertions(+), 9 deletions(-) diff --git a/examples/template.json b/examples/template.json index 0348296..36a18f1 100644 --- a/examples/template.json +++ b/examples/template.json @@ -38,7 +38,7 @@ "certificate": { "_comment": [ "The template Fleet fills in per phone. Its common name becomes the phone's callsign: 3-32", - "letters, digits or inner hyphens. This is the name `odmdm-fleet plan` gives a phone. To skip", + "letters, digits or inner hyphens. This is the name `odmdm-fleet name` gives a phone. To skip", "naming, CN=$FLEET_VAR_HOST_HARDWARE_SERIAL works for company-owned phones only.", "The name becomes the Android keystore alias, so it is per deployment, not per phone." ], diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 67c2ac8..596b339 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -10,7 +10,7 @@ from odmdm_fleet import __version__ from . import config, template -from .fleet import FleetError, FleetMdm +from .fleet import FleetError, FleetMdm, Phone LOGGER = logging.getLogger(__name__) @@ -198,3 +198,124 @@ def phones(ctx: click.Context, fleet_url: str | None, team: str | None) -> None: if not found: click.echo("No phones in the team") ctx.exit(0) + + +def _pairs(values: tuple[str, ...]) -> list[tuple[int, str]]: + """HOST=CALLSIGN arguments, as host ids and callsigns""" + pairs = [] + for value in values: + host, _, callsign = value.partition("=") + if not host.isdigit() or not callsign: + raise click.UsageError(f"{value!r} is not HOST=CALLSIGN, the host being the id that phones prints") + pairs.append((int(host), callsign)) + return pairs + + +def _numbered(found: list[Phone], prefix: str, start: int | None) -> list[tuple[int, str]]: + """PREFIX for every phone without a name, in enrolment order + + Numbered from start, else from one above the highest PREFIX already in the team. + """ + if start is None: + used = (re.fullmatch(re.escape(prefix) + r"(\d+)", phone.callsign, re.IGNORECASE) for phone in found) + start = max((int(match.group(1)) for match in used if match), default=0) + 1 + waiting = [phone.id for phone in found if not phone.callsign] + return [(host, f"{prefix}{start + n}") for n, host in enumerate(waiting)] + + +def _refusal(found: dict[int, Phone], wanted: list[tuple[int, str]]) -> str: + """Why these names cannot all be given, or empty when they can + + Callsigns are compared without case, as the deployment compares them. + """ + hosts: set[int] = set() + callsigns: set[str] = set() + for host, callsign in wanted: + if host not in found: + return f"host {host} is not in the team" + if host in hosts: + return f"host {host} is named twice" + if not CALLSIGN.fullmatch(callsign): + return f"{callsign}: a callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen" + if callsign.lower() in callsigns: + return f"{callsign} is given twice" + owner = next((p.id for p in found.values() if p.id != host and p.callsign.lower() == callsign.lower()), 0) + if owner: + return f"{callsign} already belongs to host {owner}" + hosts.add(host) + callsigns.add(callsign.lower()) + return "" + + +@cli_group.command(name="name") +@click.pass_context +@click.argument("pairs", nargs=-1, metavar="[HOST=CALLSIGN]...") +@click.option( + "--all", + "prefix", + metavar="PREFIX", + default=None, + help="Name every phone that has no name PREFIX, in enrolment order", +) +@click.option( + "--start", type=int, metavar="N", default=None, help="The first n for --all (default: one above the highest in use)" +) +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_FLEET_TEAM)") +def name( # pylint: disable=too-many-arguments,too-many-positional-arguments + ctx: click.Context, + pairs: tuple[str, ...], + prefix: str | None, + start: int | None, + fleet_url: str | None, + team: str | None, +) -> None: + """Name phones, and have Fleet send them certificates + + HOST=CALLSIGN for as many phones as you like, in any order, the host being the id that phones + prints. Or --all PREFIX, which numbers every phone that has no name yet. Each phone gets its + certificate at its next check-in, within about 15 minutes. A phone that already has its + certificate under the name is left alone. + + Nothing is changed if a name is not a callsign, is given twice or belongs to another phone in + the team, or if a host is not in the team. + """ + if bool(pairs) == bool(prefix) or (start is not None and not prefix): + raise click.UsageError("Give HOST=CALLSIGN for each phone, or --all PREFIX") + wanted = _pairs(pairs) + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + try: + team_id = fleet.team_id(team or config.TEAM) + found = {phone.id: phone for phone in fleet.phones(team_id, config.KEY_ALIAS)} + if prefix: + wanted = _numbered(list(found.values()), prefix, start) + refused = _refusal(found, wanted) + if refused: + click.echo(f"Nothing named: {refused}", err=True) + ctx.exit(1) + return + if not wanted: + click.echo("Nothing to name") + ctx.exit(0) + return + template = fleet.certificate_template(team_id, config.KEY_ALIAS) + for host, callsign in wanted: + old = found[host] + # Asked again under the name it holds, it is refused as taken: a working phone then shows as refused + if old.status == "verified" and old.callsign.lower() == callsign.lower(): + click.echo(f"Host {host} is already {old.callsign}") + continue + fleet.name_host(host, callsign, template if old.status else None) + line = f"Host {host} is {callsign}" + if not old.status: + line += ". Fleet has no certificate request for it, so nothing was sent" + elif old.status == "verified" and old.callsign: + line += f". It was {old.callsign} and still has that certificate: revoke {old.callsign} in Deploy App." + click.echo(line) + except FleetError as exc: + click.echo(f"Fleet refused: {exc}", err=True) + ctx.exit(1) + return + ctx.exit(0) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index f9960fe..d73c29d 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -446,6 +446,38 @@ def phones(self, team: int, certificate: str) -> list[Phone]: ) return sorted(found, key=lambda phone: (phone.enrolled, phone.id)) + def certificate_template(self, team: int, name: str) -> int: + """The id of the team's certificate template of that name""" + for template in self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []): + if template.get("name") == name: + return int(template["id"]) + raise FleetError(f"team {team} has no certificate template named {name}: run apply first") + + def name_host(self, host: int, callsign: str, template: int | None) -> None: + """Give the host its callsign, and have Fleet ask for its certificate again under it + + A phone enrols before anybody can name it, so its first request has already failed for + want of a name, and naming it does not send that request again by itself. A host with no + request yet gets no template: Fleet has none to send again (404, read in Fleet 4.90.1's + source), and fills the name in when it makes one. + """ + self._call("PUT", f"/api/latest/fleet/hosts/{host}/device_mapping", {"email": callsign, "source": "idp"}) + if template: + self.resend(host, template) + + def resend(self, host: int, template: int) -> None: + """Have Fleet send the host its certificate request again, for one more attempt + + The phone acts on it at its next check-in. Fleet refuses a request still pending (400), and + that one needs nothing: it is filled in when it goes, with the name the host has by then. + Measured on Fleet 4.90.1. + """ + try: + self._call("POST", f"/api/latest/fleet/hosts/{host}/certificates/{template}/resend") + except FleetError as exc: + if "answered 400" not in str(exc) or "pending" not in str(exc): + raise + # --- the whole statement -------------------------------------------------- def apply( diff --git a/tests/test_console.py b/tests/test_console.py index 0c0a178..d0eb6b4 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -18,13 +18,14 @@ @pytest.fixture def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: - """A configured connector talking to a stubbed Fleet whose team is "rmscep" """ + """A configured connector talking to a stubbed Fleet whose team "rmscep" has its certificate template""" token = tmp_path / "token" token.write_text("token\n", encoding="utf-8") monkeypatch.setattr(config, "URL", "https://mdm.test") monkeypatch.setattr(config, "TOKEN_FILE", token) monkeypatch.setattr(config, "TEAM", "rmscep") stub = _Fleet() + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$VAR", "certificate_authority_id": 3}] _mdm(stub, monkeypatch) return stub @@ -176,3 +177,175 @@ def test_an_empty_team_says_so(fleet: _Fleet) -> None: assert result.exit_code == 0, result.output assert "No phones in the team" in result.output + + +def _named(fleet: _Fleet) -> dict[int, str]: + return {h["id"]: h["end_users"][0]["idp_username"] if h["end_users"] else "" for h in fleet.hosts} + + +def _changes(fleet: _Fleet) -> list[tuple[str, str]]: + return [(method, path.removeprefix("/api/latest/fleet")) for method, path in fleet.calls if method != "GET"] + + +def test_name_gives_any_number_of_phones_their_callsigns(fleet: _Fleet) -> None: + """In any order, each named and then asked for its certificate again under the name""" + fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] + + result = CliRunner().invoke(cli_group, ["name", "33=OTTER5", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Host 33 is OTTER5", "Host 31 is OTTER4"] + assert _named(fleet) == {31: "OTTER4", 32: "", 33: "OTTER5"} + assert _changes(fleet) == [ + ("PUT", "/hosts/33/device_mapping"), + ("POST", "/hosts/33/certificates/81/resend"), + ("PUT", "/hosts/31/device_mapping"), + ("POST", "/hosts/31/certificates/81/resend"), + ] + + +def test_a_request_still_pending_takes_the_name_without_a_resend(fleet: _Fleet) -> None: + """Fleet refuses to resend it, and it needs none: it is filled in when it goes""" + fleet.hosts = [_host(31, "pending")] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Host 31 is OTTER4"] + assert _named(fleet) == {31: "OTTER4"} + + +def test_a_phone_with_its_certificate_under_the_name_is_left_alone(fleet: _Fleet) -> None: + """Asked again under the name it holds, it is refused as taken and then reads as refused""" + fleet.hosts = [_host(31, "verified", "OTTER4@CODE"), _host(32, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, ["name", "31=otter4", "32=OTTER5"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Host 31 is already OTTER4", "Host 32 is OTTER5"] + assert _changes(fleet) == [("PUT", "/hosts/32/device_mapping"), ("POST", "/hosts/32/certificates/81/resend")] + assert _named(fleet)[31] == "OTTER4@CODE" + + +def test_a_phone_with_no_request_is_named_and_the_batch_goes_on(fleet: _Fleet) -> None: + """Fleet has no request to send it again, and fills the name in when it makes one""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME), _host(32), _host(33, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [ + "Host 31 is OTTER1", + "Host 32 is OTTER2. Fleet has no certificate request for it, so nothing was sent", + "Host 33 is OTTER3", + ] + assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: "OTTER3"} + assert ("POST", "/hosts/32/certificates/81/resend") not in _changes(fleet) + + +@pytest.mark.parametrize( + ("first", "start", "expected"), + [ + ("KETTU1", [], {42: "OTTER1", 43: "OTTER2", 41: "OTTER3"}), + ("otter7", [], {42: "OTTER8", 43: "OTTER9", 41: "OTTER10"}), + ("OTTER7", ["--start", "20"], {42: "OTTER20", 43: "OTTER21", 41: "OTTER22"}), + ], +) +def test_name_all_numbers_the_phones_without_a_name( + fleet: _Fleet, first: str, start: list[str], expected: dict[int, str] +) -> None: + """In enrolment order, then host id, from one above the highest number in use unless told""" + fleet.hosts = [ + _host(40, "verified", first, enrolled="2026-11-01T08:00:00Z"), + _host(41, "failed", detail=NO_NAME, enrolled="2026-11-03T08:00:00Z"), + _host(43, "failed", detail=NO_NAME, enrolled="2026-11-02T08:00:00Z"), + _host(42, "failed", detail=NO_NAME, enrolled="2026-11-02T08:00:00Z"), + ] + + result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER", *start]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [f"Host {host} is {callsign}" for host, callsign in expected.items()] + assert _named(fleet) == {40: first, **expected} + + +def test_name_all_with_every_phone_named_names_nothing(fleet: _Fleet) -> None: + """A second run finds nobody waiting, and changes nothing""" + fleet.hosts = [_host(31, "verified", "OTTER1")] + + result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER"]) + + assert result.exit_code == 0, result.output + assert "Nothing to name" in result.output + assert not _changes(fleet) + + +@pytest.mark.parametrize( + ("arguments", "says"), + [ + (["31=OT"], "OT: a callsign is 3-32 letters"), + (["31=OTTER-"], "OTTER-: a callsign is 3-32 letters"), + (["--all", "O"], "O1: a callsign is 3-32 letters"), + (["31=OTTER4", "32=otter4"], "otter4 is given twice"), + (["31=OTTER4", "31=OTTER5"], "host 31 is named twice"), + (["31=otter9"], "otter9 already belongs to host 33"), + (["--all", "OTTER", "--start", "9"], "OTTER9 already belongs to host 33"), + (["31=OTTER4", "99=OTTER5"], "host 99 is not in the team"), + ], +) +def test_name_changes_nothing_unless_every_name_can_be_given(fleet: _Fleet, arguments: list[str], says: str) -> None: + """A typo refuses the whole command, rather than leaving half a batch named""" + fleet.hosts = [ + _host(31, "failed", detail=NO_NAME), + _host(32, "failed", detail=NO_NAME), + _host(33, "verified", "OTTER9@CODE"), + ] + + result = CliRunner().invoke(cli_group, ["name", *arguments]) + + assert result.exit_code == 1 + assert f"Nothing named: {says}" in result.output + assert not _changes(fleet) + + +@pytest.mark.parametrize("arguments", [[], ["31=OTTER4", "--all", "OTTER"], ["31=OTTER4", "--start", "3"], ["OTTER4"]]) +def test_name_says_how_it_is_used(fleet: _Fleet, arguments: list[str]) -> None: + """Before Fleet is asked anything""" + result = CliRunner().invoke(cli_group, ["name", *arguments]) + + assert result.exit_code == 2 + assert not fleet.calls + + +def test_renaming_a_phone_with_its_certificate_says_what_to_revoke(fleet: _Fleet) -> None: + """The old callsign stays valid in Deploy App until an admin revokes it there""" + fleet.hosts = [_host(31, "verified", "OTTER3")] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [ + "Host 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." + ] + + +def test_renaming_a_refused_phone_says_nothing_to_revoke(fleet: _Fleet) -> None: + """A refused name was never issued to this phone, and may be another phone's""" + fleet.hosts = [_host(31, "failed", "OTTER3", REFUSED)] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Host 31 is OTTER4"] + + +def test_name_without_a_certificate_template_says_so(fleet: _Fleet) -> None: + """Before a phone is named, so nothing is left half done""" + fleet.certificates = [] + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 1 + assert "no certificate template named rmscep: run apply first" in result.output + assert not _changes(fleet) diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 3d99606..db8eff6 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -43,12 +43,34 @@ def handler(self, request: httpx.Request) -> httpx.Response: self.calls.append((request.method, path)) if path.endswith("/hosts") and request.method == "GET": return httpx.Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts]}) - if path.endswith("/device_mapping"): - which = int(path.split("/hosts/")[1].split("/")[0]) - found = next(h for h in self.hosts if h["id"] == which) - if request.method == "PUT": - found["device_mapping"] = [json.loads(request.content)] - return httpx.Response(200, json={"device_mapping": found.get("device_mapping") or []}) + if path.endswith("/device_mapping") and request.method == "PUT": + # The name shows in the host detail as its IdP user, which is what the certificate reads + found = next(h for h in self.hosts if h["id"] == int(path.split("/")[-2])) + found["end_users"] = [{"idp_username": json.loads(request.content)["email"], "idp_info_updated_at": None}] + return httpx.Response(200, json={}) + if path.endswith("/resend") and request.method == "POST": + # Fleet finds the template through the host's own row, so a host without one is not + # found (read in Fleet 4.90.1's source). A row still pending is refused, and any other + # starts over as pending; the answer has no body (both seen on a live Fleet 4.90.1). + found = next(h for h in self.hosts if h["id"] == int(path.split("/")[-4])) + template = int(path.split("/")[-2]) + rows = [ + r + for r in found["mdm"]["profiles"] + if r.get("certificate_template_id") == template and r["operation_type"] == "install" + ] + if not rows: + return httpx.Response(404, json={"message": "Resource Not Found"}) + if rows[0]["status"] == "pending": + return httpx.Response( + 400, + json={ + "message": "Bad request", + "errors": [{"name": "base", "reason": "Couldn't resend pending certificate template."}], + }, + ) + rows[0].update(status="pending", detail="") + return httpx.Response(200) if "/hosts/" in path and request.method == "GET": which = int(path.rsplit("/", 1)[-1]) return httpx.Response(200, json={"host": next(h for h in self.hosts if h["id"] == which)}) @@ -377,6 +399,15 @@ def _host( } +def test_a_resend_refused_for_another_reason_is_reported(monkeypatch: pytest.MonkeyPatch) -> None: + """Only a request still pending needs nothing; a host with no request at all is not found""" + fleet = _Fleet() + fleet.hosts = [_host(31)] + + with pytest.raises(FleetError, match="answered 404"): + _mdm(fleet, monkeypatch).resend(31, 81) + + def _with_cert(authority: str = "RMSCEP") -> MdmTemplate: """A template that asks for a certificate, which is what drags the authority in""" return MdmTemplate( From 512e1bc0e8fb3d1b09b6a11e74d379f3facdbee8 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 22:31:54 +0200 Subject: [PATCH 016/104] feat: resend refused phones' certificate requests --- src/odmdm_fleet/console.py | 45 +++++++++++++++++++++++++++++++++++ src/odmdm_fleet/fleet.py | 3 +++ tests/test_console.py | 48 +++++++++++++++++++++++++++++++++++++- 3 files changed, 95 insertions(+), 1 deletion(-) diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 596b339..3a59c17 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -319,3 +319,48 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx.exit(1) return ctx.exit(0) + + +@cli_group.command(name="resend") +@click.pass_context +@click.argument("hosts", nargs=-1, type=int) +@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") +@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_FLEET_TEAM)") +def resend(ctx: click.Context, hosts: tuple[int, ...], fleet_url: str | None, team: str | None) -> None: + """Have Fleet send phones their certificate requests again + + For a refused phone once the cause is fixed, such as enrolment opened again and its new + challenge given to Fleet. A taken name is not one of those: Deploy App never frees a name, so + give the phone another with name, which sends the request itself. Without host ids, every phone + that has a name and whose certificate failed. Each acts on it at its next check-in, within + about 15 minutes. + + A host id is asked whatever its state. A phone that has its certificate asks again under the + name it holds and is refused, and reads as refused from then on though that certificate still + works. + """ + fleet = _fleet(ctx, fleet_url) + if not fleet: + return + try: + team_id = fleet.team_id(team or config.TEAM) + found = {phone.id: phone for phone in fleet.phones(team_id, config.KEY_ALIAS)} + unknown = [host for host in hosts if host not in found] + if unknown: + click.echo(f"Nothing sent: host {unknown[0]} is not in the team", err=True) + ctx.exit(1) + return + chosen = list(hosts) or [phone.id for phone in found.values() if phone.status == "failed" and phone.callsign] + if not chosen: + click.echo("Nothing to resend") + ctx.exit(0) + return + template = fleet.certificate_template(team_id, config.KEY_ALIAS) + for host in chosen: + fleet.resend(host, template) + click.echo(f"Host {host} ({found[host].callsign or 'no name'}): certificate asked for again") + except FleetError as exc: + click.echo(f"Fleet refused: {exc}", err=True) + ctx.exit(1) + return + ctx.exit(0) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index d73c29d..77dd111 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -70,6 +70,9 @@ def state(self) -> str: def _failure(self) -> str: """What Fleet's detail on a failed request means""" if "does not have an IDP user" in self.detail: + # Naming does not send the request again, so a name beside this detail was given without a resend + if self.callsign: + return "named, but its certificate was not asked for again: run resend" return "waiting for a name" if "SCEP enrollment failed" in self.detail: return "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old challenge" diff --git a/tests/test_console.py b/tests/test_console.py index d0eb6b4..fe4fb30 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -117,7 +117,7 @@ def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: ("status", "detail", "says"), [ ("", "", "no certificate requested"), - ("failed", NO_NAME, "waiting for a name"), + ("failed", NO_NAME, "named, but its certificate was not asked for again: run resend"), ("pending", "", "requested, waiting for the phone (up to 15 minutes)"), ("delivering", "", "requested, waiting for the phone (up to 15 minutes)"), ("delivered", "", "requested, waiting for the phone (up to 15 minutes)"), @@ -349,3 +349,49 @@ def test_name_without_a_certificate_template_says_so(fleet: _Fleet) -> None: assert result.exit_code == 1 assert "no certificate template named rmscep: run apply first" in result.output assert not _changes(fleet) + + +def test_resend_asks_again_for_every_named_phone_that_failed(fleet: _Fleet) -> None: + """A phone named in Fleet by hand is one of them: naming alone does not send the request again""" + fleet.hosts = [ + _host(31, "failed", "OTTER4", REFUSED), + _host(32, "failed", detail=NO_NAME), + _host(33, "verified", "OTTER5"), + _host(34, "failed", "OTTER6", NO_NAME), + _host(35, "pending", "OTTER7"), + ] + + result = CliRunner().invoke(cli_group, ["resend"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [ + "Host 31 (OTTER4): certificate asked for again", + "Host 34 (OTTER6): certificate asked for again", + ] + assert _changes(fleet) == [ + ("POST", "/hosts/31/certificates/81/resend"), + ("POST", "/hosts/34/certificates/81/resend"), + ] + + +def test_resend_given_hosts_asks_for_those(fleet: _Fleet) -> None: + """Whatever state they are in: the operator chose them""" + fleet.hosts = [_host(31, "failed", "OTTER4", REFUSED), _host(32, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, ["resend", "32"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Host 32 (no name): certificate asked for again"] + assert _changes(fleet) == [("POST", "/hosts/32/certificates/81/resend")] + + +@pytest.mark.parametrize(("arguments", "says", "code"), [([], "Nothing to resend", 0), (["99"], "not in the team", 1)]) +def test_resend_says_when_it_sends_nothing(fleet: _Fleet, arguments: list[str], says: str, code: int) -> None: + """Nobody failed, or a host that is not in the team: said, and nothing sent""" + fleet.hosts = [_host(31, "verified", "OTTER4")] + + result = CliRunner().invoke(cli_group, ["resend", *arguments]) + + assert result.exit_code == code, result.output + assert says in result.output + assert not _changes(fleet) From 7abde943b8a1bc2c1e4e68f2bd9408dff29ec481 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 22:33:29 +0200 Subject: [PATCH 017/104] docs: enrol into one team, name phones in any number and order --- README.rst | 85 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 52 insertions(+), 33 deletions(-) diff --git a/README.rst b/README.rst index 5ded113..353879a 100644 --- a/README.rst +++ b/README.rst @@ -17,45 +17,61 @@ facing service. Enrolling phones ---------------- -Two Fleet teams: phones enrol into a preparation team and are named there, then move to the team -that gets the certificate. Naming first means the first certificate request already carries the -callsign. +One Fleet team, the one with the certificate template. Phones enrol into it before anybody names +them, and each gets its certificate once it has a name. 1. Once per deployment, and whenever the template changes:: - odmdm-fleet apply --team "Deploy App" --prep-team Preparation + odmdm-fleet apply -2. Enrol a phone into the preparation team, then name it:: +2. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge. It + asks for it, and changes nothing else:: - odmdm-fleet plan OTTER4 + odmdm-fleet challenge - ``plan`` names the one phone in the preparation team that has no name yet. With two waiting it - names neither, because Fleet shows identical phones as identical rows and nothing tells you - which is the one in your hand. Enrol, plan, next phone. +3. Enrol phones into the ``Deploy App`` team, as many as you like, in any order. -3. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge. It - asks for it, and changes nothing else:: +4. Name them, all at once or a few at a time:: - odmdm-fleet challenge + odmdm-fleet name --all OTTER # OTTER1, OTTER2, ... in the order they enrolled + odmdm-fleet name 31=OTTER4 32=OTTER5 # host id = callsign, the ids being what phones prints -4. In Fleet, transfer the named phones to the ``Deploy App`` team. Each gets its certificate 7 to - 20 minutes later and greets its callsign in Deploy App. + Each phone gets its certificate at its next check-in, within about 15 minutes, and greets its + callsign in Deploy App. ``phones`` shows where each one is. ``resend`` asks again for a refused + phone once the cause is fixed. -Close enrolment when the last phone is in. The next opening makes a new challenge, so step 3 -comes again before the next batch. +Close enrolment once ``phones`` says every phone has its certificate: a request that arrives after +it closes is refused. The next opening makes a new challenge, so step 2 comes again before the +next batch. + +Without this tool, in Fleet: open the phone, **Edit user** to give it its callsign, then under +**OS settings** pick the certificate and **Resend**. Naming alone does not send the request again. + +Phones already enrolled in another Fleet team: transfer them into this team in Fleet, then name +them like the rest. Apps install only at enrolment, so a transferred phone gets its certificate but +not this team's apps or launcher. For those, remove its work profile after the transfer and enrol +it again into this team; see `The order that works`_. Commands -------- .. code-block:: bash - odmdm-fleet apply # state what devices need; --force-policy after one joins - odmdm-fleet apply --dry-run # validate the template without touching Fleet - odmdm-fleet challenge # give Fleet a new enrolment window's challenge, nothing else - odmdm-fleet plan CALLSIGN # name the one phone waiting to be named - -With a single team a phone enrols straight into the certificate team before anyone has named it, -and that first request fails. Name it with ``plan --team``, then transfer it out and back. + odmdm-fleet apply # state what devices need; --force-policy after one joins + odmdm-fleet apply --dry-run # validate the template without touching Fleet + odmdm-fleet challenge # give Fleet a new window's challenge, nothing else + odmdm-fleet phones # each phone's host id, callsign, model and certificate + odmdm-fleet name 31=OTTER4 32=OTTER5 # name these phones, and Fleet sends their certificates + odmdm-fleet name --all OTTER # the same for every phone without a name, numbered + odmdm-fleet resend [HOST_ID ...] # ask again; without ids, every named phone that failed + +``name --all`` numbers in enrolment order from one above the highest ``OTTER`` in the team, or +from ``--start N``. It sees only this team's phones, and Deploy App never gives a callsign out +twice: where callsigns were used by phones no longer in the team, give ``--start`` above the +highest ever used. ``name`` changes nothing at all if a callsign is malformed, given twice or +already another phone's, or if a host is not in the team. A phone that already has its certificate +under the name is left alone. Renaming a phone that has its certificate says which old callsign to +revoke. Configuration ------------- @@ -70,7 +86,7 @@ All configuration is via environment variables: global admin token, because Fleet keeps certificate authorities outside teams. ``ODMDM_FLEET_TEAM`` - The team whose phones get the certificate. Default ``Deploy App``. + The team phones enrol into and get the certificate in. Default ``Deploy App``. ``ODMDM_FLEET_TEMPLATE`` The document saying what to install, see below. @@ -107,8 +123,8 @@ The order that works Three facts about managed Android pull against each other. Each was learned by getting it wrong. 1. **Apps install at enrolment and at no other time.** The team must carry them before a phone - joins. So both teams carry the **same** launcher package: a transfer to a team with another - package uninstalls the launcher and never installs the other. + joins. A phone transferred in from a team with another launcher package loses that launcher + and never gets this one. 2. **A profile is delivered when the profile changes, not when a phone arrives.** One uploaded before a phone joined is never sent to it, so a first enrolment needs ``--force-policy``. 3. **A policy rewritten while apps are installing stops them installing.** Leave the phones alone @@ -122,19 +138,22 @@ What Fleet does that you would not guess launcher and leaves the old one orphaned. Google refuses a title of 30 characters or more. - **A web app's display name is unique within a team** (409). A title in a team's setup experience has to be removed there before it can be removed from the team. -- **A returning phone keeps its old team and its old name.** Transfer it to the preparation team - and rename it with ``odmdm-fleet plan NEWNAME --instead-of OLDNAME``, or it asks for a name that - is already taken. It can also come back as a new device with no name, so ``--instead-of`` refuses - while one is waiting: name that one with plain ``plan``. +- **A phone enrols before it has a name**, so its first certificate request fails (``does not + have an IDP user``) until it is named, and naming it does not send the request again. ``name`` + resends. A resend is one more attempt, which the phone acts on at its next check-in, every 15 + minutes. +- **A returning phone keeps its old team and its old name.** Transfer it into this team if it was + in another, and give it a new name with ``name``, or it asks for a name that is already taken. It + can also come back as a new device with no name. - **Renaming a phone that has its certificate gives it a second callsign.** Revoke the old one in Deploy App. - **Replacing a team's certificate template locks its phones out.** Every phone deletes the certificate it has and asks again, and the deployment refuses a name that is already taken. So - this repository never replaces one to retry a phone: a transfer out and back asks for that phone - alone. + this repository never replaces one to retry a phone: ``resend`` asks for that phone alone. - **A refusal shows only as** ``SCEP enrollment failed ... failInfo: badMessageCheck`` on the phone's certificate. Usually a bad or taken name, or Fleet still has the previous window's - challenge. Fix it, then transfer the phone out and back. + challenge. A taken name is never freed, not even by revoking it, so give the phone another with + ``name``. For the challenge, ``challenge`` and then ``resend``. Docker ------ From fb4ab2bdbf380d7c3f6776f3879ed52a61dc6c4d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 23:06:26 +0200 Subject: [PATCH 018/104] fix: create a team only in apply, so a mistyped --team changes nothing --- src/odmdm_fleet/fleet.py | 12 +++++++++--- tests/test_console.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 77dd111..02ed9d1 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -139,11 +139,17 @@ def _upload( # --- scopes --------------------------------------------------------------- - def team_id(self, name: str) -> int: - """The team by name, created if it is not there yet""" + def team_id(self, name: str, create: bool = False) -> int: + """The team by name + + Only apply creates a team that is not there. Anywhere else an unknown name is a typo, and + must not leave a team behind. + """ for team in self._call("GET", "/api/latest/fleet/teams").get("teams", []): if team.get("name") == name: return int(team["id"]) + if not create: + raise FleetError(f"no team named {name}: check --team or ODMDM_FLEET_TEAM") created = self._call("POST", "/api/latest/fleet/teams", {"name": name}) team = created.get("team", created) LOGGER.info("Created team %s", name) @@ -502,7 +508,7 @@ def apply( nothing typed into Fleet by hand. Without it the authority must already be there, which is the case for an MDM we cannot create one in. """ - team = self.team_id(team_name) + team = self.team_id(team_name, create=True) if template.certificate: if scep_url: self.ensure_authority(template.certificate.authority, scep_url, challenge) diff --git a/tests/test_console.py b/tests/test_console.py index fe4fb30..040ddaf 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -395,3 +395,15 @@ def test_resend_says_when_it_sends_nothing(fleet: _Fleet, arguments: list[str], assert result.exit_code == code, result.output assert says in result.output assert not _changes(fleet) + + +@pytest.mark.parametrize("command", [["phones"], ["name", "31=OTTER4"], ["resend"]]) +def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str]) -> None: + """A typo must not leave an empty team behind for the next phone to enrol into""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, [*command, "--team", "Typo"]) + + assert result.exit_code == 1 + assert "no team named Typo" in result.output + assert not _changes(fleet) From 4f6618e1182b9de053c8782ce6a7469b9968bb2e Mon Sep 17 00:00:00 2001 From: benjamsf Date: Fri, 20 Nov 2026 23:35:03 +0200 Subject: [PATCH 019/104] fix: send the policy again after name and resend when a phone enrolled after it --- README.rst | 19 +++-- src/odmdm_fleet/console.py | 18 ++++- src/odmdm_fleet/fleet.py | 68 +++++++++++++--- tests/test_console.py | 160 ++++++++++++++++++++++++++++++++++++- tests/test_fleet.py | 54 ++++++++++++- 5 files changed, 299 insertions(+), 20 deletions(-) diff --git a/README.rst b/README.rst index 353879a..8402660 100644 --- a/README.rst +++ b/README.rst @@ -29,7 +29,8 @@ them, and each gets its certificate once it has a name. odmdm-fleet challenge -3. Enrol phones into the ``Deploy App`` team, as many as you like, in any order. +3. Enrol phones into the ``Deploy App`` team, as many as you like, in any order. Name them once + every phone in the team has its apps: naming can send the policy to all of them again. 4. Name them, all at once or a few at a time:: @@ -46,6 +47,8 @@ next batch. Without this tool, in Fleet: open the phone, **Edit user** to give it its callsign, then under **OS settings** pick the certificate and **Resend**. Naming alone does not send the request again. +Once the phones have enrolled and their apps have arrived, delete the policy in Fleet and upload +it again: Fleet can overwrite a new phone's policy, see `The order that works`_. Phones already enrolled in another Fleet team: transfer them into this team in Fleet, then name them like the rest. Apps install only at enrolment, so a transferred phone gets its certificate but @@ -57,7 +60,7 @@ Commands .. code-block:: bash - odmdm-fleet apply # state what devices need; --force-policy after one joins + odmdm-fleet apply # state what devices need; --force-policy sends the policy again odmdm-fleet apply --dry-run # validate the template without touching Fleet odmdm-fleet challenge # give Fleet a new window's challenge, nothing else odmdm-fleet phones # each phone's host id, callsign, model and certificate @@ -120,13 +123,19 @@ The certificate subject is the contract with the deployment. Its common name bec The order that works -------------------- -Three facts about managed Android pull against each other. Each was learned by getting it wrong. +Three facts about managed Android and Fleet pull against each other. Each was learned by getting +it wrong. 1. **Apps install at enrolment and at no other time.** The team must carry them before a phone joins. A phone transferred in from a team with another launcher package loses that launcher and never gets this one. -2. **A profile is delivered when the profile changes, not when a phone arrives.** One uploaded - before a phone joined is never sent to it, so a first enrolment needs ``--force-policy``. +2. **Fleet can overwrite a new phone's policy moments after sending it.** It sends a phone that + enrols the team's policy, and seconds later can write a bare one over it. It goes on showing + the policy as verified on that phone and never sends it again, so the phone has its certificate + but Chrome may not use it, and Deploy App says "Certificate Authentication Failed". ``name`` and + ``resend`` send the policy again, to every phone in the team, when a phone enrolled after it + was last sent. By hand it is ``apply --force-policy``, or deleting the policy in Fleet and + uploading it again. 3. **A policy rewritten while apps are installing stops them installing.** Leave the phones alone until the apps have arrived. diff --git a/src/odmdm_fleet/console.py b/src/odmdm_fleet/console.py index 3a59c17..2f53c77 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_fleet/console.py @@ -247,6 +247,13 @@ def _refusal(found: dict[int, Phone], wanted: list[tuple[int, str]]) -> str: return "" +def _policy_again(fleet: FleetMdm, team_id: int, found: dict[int, Phone]) -> None: + """Send the policy again if a phone enrolled after it was last sent, as Fleet may have overwritten it there""" + later = fleet.resend_policy(team_id, list(found.values())) + if later: + click.echo(f"Policy sent again: {later} phone{'' if later == 1 else 's'} enrolled after it was last sent") + + @cli_group.command(name="name") @click.pass_context @click.argument("pairs", nargs=-1, metavar="[HOST=CALLSIGN]...") @@ -279,6 +286,10 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments Nothing is changed if a name is not a callsign, is given twice or belongs to another phone in the team, or if a host is not in the team. + + The team's policy is sent again, to every phone in it, if a phone enrolled after it was last + sent, because Fleet can overwrite a new phone's policy. So name phones once every phone in the + team has its apps. """ if bool(pairs) == bool(prefix) or (start is not None and not prefix): raise click.UsageError("Give HOST=CALLSIGN for each phone, or --all PREFIX") @@ -301,6 +312,7 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx.exit(0) return template = fleet.certificate_template(team_id, config.KEY_ALIAS) + named = False for host, callsign in wanted: old = found[host] # Asked again under the name it holds, it is refused as taken: a working phone then shows as refused @@ -308,12 +320,15 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments click.echo(f"Host {host} is already {old.callsign}") continue fleet.name_host(host, callsign, template if old.status else None) + named = True line = f"Host {host} is {callsign}" if not old.status: line += ". Fleet has no certificate request for it, so nothing was sent" elif old.status == "verified" and old.callsign: line += f". It was {old.callsign} and still has that certificate: revoke {old.callsign} in Deploy App." click.echo(line) + if named: + _policy_again(fleet, team_id, found) except FleetError as exc: click.echo(f"Fleet refused: {exc}", err=True) ctx.exit(1) @@ -337,7 +352,7 @@ def resend(ctx: click.Context, hosts: tuple[int, ...], fleet_url: str | None, te A host id is asked whatever its state. A phone that has its certificate asks again under the name it holds and is refused, and reads as refused from then on though that certificate still - works. + works. As with name, the team's policy is sent again if a phone enrolled after it was last sent. """ fleet = _fleet(ctx, fleet_url) if not fleet: @@ -359,6 +374,7 @@ def resend(ctx: click.Context, hosts: tuple[int, ...], fleet_url: str | None, te for host in chosen: fleet.resend(host, template) click.echo(f"Host {host} ({found[host].callsign or 'no name'}): certificate asked for again") + _policy_again(fleet, team_id, found) except FleetError as exc: click.echo(f"Fleet refused: {exc}", err=True) ctx.exit(1) diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_fleet/fleet.py index 02ed9d1..832f0c4 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_fleet/fleet.py @@ -5,6 +5,7 @@ """ import dataclasses +import datetime import json import logging import time @@ -81,6 +82,18 @@ def _failure(self) -> str: return self.detail or "failed" +def _moment(value: str) -> datetime.datetime: + """A time Fleet wrote, as a time + + Fleet writes a profile's created_at to the microsecond and its updated_at and a host's + last_enrolled_at to the second, so as strings "...44Z" sorts after "...44.458685Z". + """ + try: + return datetime.datetime.fromisoformat(value) + except ValueError as exc: + raise FleetError(f"the time {value!r} could not be read") from exc + + class FleetMdm: """What this feature needs an MDM to be able to do, in Fleet's words""" @@ -217,28 +230,61 @@ def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_ for Play to finish an install. So Fleet's own copy is what gets compared, because this runs once per command and has nothing of its own to remember between runs. - force exists because a profile is delivered when the PROFILE changes, not when a host - arrives, so one created before a device joined is never sent to it. + force exists because Fleet can overwrite a newly enrolled phone's policy with a bare one + moments after sending ours, then shows ours as verified and never sends it again. Only a + new upload reaches that phone. resend_policy makes one when a phone enrolled after the + last upload. """ profiles = self._call("GET", f"/api/latest/fleet/configuration_profiles?team_id={team}").get("profiles", []) here = [p for p in profiles if p.get("name") == name] if len(here) == 1 and not force and self._policy_in_fleet(here[0]["profile_uuid"]) == fragment: return - for existing in here: - self._call("DELETE", f"/api/latest/fleet/configuration_profiles/{existing['profile_uuid']}") - self._upload( - "/api/latest/fleet/configuration_profiles", - {"team_id": str(team)}, - f"{name}.json", - json.dumps(fragment, indent=2, sort_keys=True).encode("utf-8"), - file_field="profile", - ) + try: + for existing in here: + self._call("DELETE", f"/api/latest/fleet/configuration_profiles/{existing['profile_uuid']}") + self._upload( + "/api/latest/fleet/configuration_profiles", + {"team_id": str(team)}, + f"{name}.json", + json.dumps(fragment, indent=2, sort_keys=True).encode("utf-8"), + file_field="profile", + ) + except FleetError as exc: + if not here: + raise + # Between the delete and the upload the team has no policy, and every phone in it loses the settings + raise FleetError( + f"policy {name} was being replaced in team {team} and may now be missing ({exc}). " + "Run apply to put it back" + ) from exc LOGGER.info("Uploaded policy %s to team %s", name, team) def _policy_in_fleet(self, profile_uuid: str) -> dict[str, Any]: """The policy as Fleet holds it; without alt=media this answers with metadata only""" return self._call("GET", f"/api/latest/fleet/configuration_profiles/{profile_uuid}?alt=media") + def resend_policy(self, team: int, phones: list[Phone], name: str = POLICY_NAME) -> int: + """Upload the team's policy again if any of the phones enrolled after it was last sent + + Answers how many did, 0 when nothing was sent. Measured on Fleet 4.90.1: a phone that + enrols is sent our policy, and seconds later Fleet can write one holding only its status + reporting over it. Fleet goes on showing ours as verified there and never sends it again, + so the phone installs its certificate and Chrome is not allowed to use it. The same + policy uploaded again reaches the phone and leaves its certificate and apps alone. + + Fleet's own copy is what goes, so no template is needed. A phone that enrols again onto its + old host keeps its old last_enrolled_at, and is not seen here: apply --force-policy reaches it. + """ + profiles = self._call("GET", f"/api/latest/fleet/configuration_profiles?team_id={team}").get("profiles", []) + profile = next((p for p in profiles if p.get("name") == name), None) + if not profile: + return 0 + sent = _moment(str(profile.get("updated_at") or profile.get("created_at") or "")) + later = [phone for phone in phones if phone.enrolled and _moment(phone.enrolled) > sent] + if later: + self.ensure_policy(team, self._policy_in_fleet(profile["profile_uuid"]), name=name, force=True) + return len(later) + def ensure_link_app(self, team: int, title: str, url: str) -> str: """A managed web app, so the deployment has an icon on the launcher diff --git a/tests/test_console.py b/tests/test_console.py index 040ddaf..6eb6cf4 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -7,6 +7,7 @@ import json from pathlib import Path +import httpx import pytest from click.testing import CliRunner @@ -18,7 +19,10 @@ @pytest.fixture def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: - """A configured connector talking to a stubbed Fleet whose team "rmscep" has its certificate template""" + """A configured connector talking to a stubbed Fleet whose team "rmscep" has its certificate template + + And its policy, last sent after the time _host gives a phone by default. + """ token = tmp_path / "token" token.write_text("token\n", encoding="utf-8") monkeypatch.setattr(config, "URL", "https://mdm.test") @@ -26,6 +30,15 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: monkeypatch.setattr(config, "TEAM", "rmscep") stub = _Fleet() stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$VAR", "certificate_authority_id": 3}] + stub.profiles = [ + { + "name": "rmscep-policy", + "profile_uuid": "g4bb", + "created_at": "2026-11-20T21:02:44.458685Z", + "updated_at": "2026-11-20T21:02:44Z", + "raw": {"defaultPermissionPolicy": "GRANT"}, + } + ] _mdm(stub, monkeypatch) return stub @@ -397,6 +410,151 @@ def test_resend_says_when_it_sends_nothing(fleet: _Fleet, arguments: list[str], assert not _changes(fleet) +#: After the fixture's policy was last sent +LATER = "2026-11-20T21:10:02Z" + + +def _policy_changes(fleet: _Fleet) -> list[tuple[str, str]]: + return [change for change in _changes(fleet) if "/configuration_profiles" in change[1]] + + +def test_name_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet) -> None: + """Fleet can write a bare policy over a new phone's, and never sends ours again by itself + + Measured: the certificate installs, Chrome is not allowed to use it, and Deploy App says + "Certificate Authentication Failed". Fleet's own copy uploaded again reaches the phone. + """ + fleet.hosts = [ + _host(31, "failed", detail=NO_NAME, enrolled=LATER), + _host(32, "failed", detail=NO_NAME, enrolled=LATER), + _host(33, "verified", "OTTER1"), + ] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines() == [ + "Host 31 is OTTER4", + "Policy sent again: 2 phones enrolled after it was last sent", + ] + assert _policy_changes(fleet) == [("DELETE", "/configuration_profiles/g4bb"), ("POST", "/configuration_profiles")] + assert [profile["raw"] for profile in fleet.profiles] == [{"defaultPermissionPolicy": "GRANT"}] + + +def test_resend_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet) -> None: + """The phone asked again may be one whose policy Fleet overwrote""" + fleet.hosts = [_host(31, "failed", "OTTER4", REFUSED, enrolled=LATER), _host(32, "verified", "OTTER5")] + + result = CliRunner().invoke(cli_group, ["resend"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines() == [ + "Host 31 (OTTER4): certificate asked for again", + "Policy sent again: 1 phone enrolled after it was last sent", + ] + assert _policy_changes(fleet) == [("DELETE", "/configuration_profiles/g4bb"), ("POST", "/configuration_profiles")] + + +def test_a_policy_sent_again_is_then_left_alone(fleet: _Fleet) -> None: + """Fleet stamps an upload with its own clock, so the policy is newer than every phone already there + + Sent on every run, it would be rewritten under phones still installing their apps. + """ + fleet.now = "2026-11-20T21:30:00.123456Z" + fleet.hosts = [ + _host(31, "failed", detail=NO_NAME, enrolled=LATER), + _host(32, "failed", detail=NO_NAME, enrolled=LATER), + ] + + first = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + fleet.calls.clear() + second = CliRunner().invoke(cli_group, ["name", "32=OTTER5"]) + + assert first.stdout.splitlines()[-1] == "Policy sent again: 2 phones enrolled after it was last sent" + assert second.exit_code == 0, second.output + assert second.stdout.splitlines() == ["Host 32 is OTTER5"] + assert not _policy_changes(fleet) + + +@pytest.mark.parametrize(("policy", "enrolled"), [(True, "2026-11-01T19:38:12Z"), (False, LATER)]) +def test_the_policy_is_left_alone_unless_a_phone_enrolled_after_it(fleet: _Fleet, policy: bool, enrolled: str) -> None: + """Every phone enrolled before it was last sent, or the team has no policy to send""" + if not policy: + fleet.profiles = [] + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=enrolled)] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == ["Host 31 is OTTER4"] + assert _changes(fleet) == [("PUT", "/hosts/31/device_mapping"), ("POST", "/hosts/31/certificates/81/resend")] + + +@pytest.mark.parametrize( + ("command", "said"), + [ + (["name", "31=OTTER4"], "Host 31 is already OTTER4"), + (["name", "--all", "OTTER"], "Nothing to name"), + (["resend"], "Nothing to resend"), + ], +) +def test_the_policy_is_sent_again_only_after_a_phone_is_named_or_asked_again( + fleet: _Fleet, command: list[str], said: str +) -> None: + """A run that changed nothing leaves the policy alone, as it would a phone still installing apps""" + fleet.hosts = [_host(31, "verified", "OTTER4", enrolled=LATER)] + + result = CliRunner().invoke(cli_group, command) + + assert result.exit_code == 0, result.output + assert result.output.splitlines() == [said] + assert not _changes(fleet) + + +def test_a_policy_fleet_refuses_is_said_after_the_names(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """The phones are named all the same, and the refusal is said as any other""" + answer = fleet.handler + + def refusing(request: httpx.Request) -> httpx.Response: + if request.url.params.get("alt") == "media": + return httpx.Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=LATER)] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 1 + assert result.output.splitlines()[0] == "Host 31 is OTTER4" + assert "Fleet refused: GET /api/latest/fleet/configuration_profiles/g4bb?alt=media answered 500" in result.output + assert _named(fleet) == {31: "OTTER4"} + assert not _policy_changes(fleet) + + +def test_a_policy_lost_between_delete_and_upload_is_said(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """The team then has no policy, every phone in it loses the settings, and a later run sees nothing""" + answer = fleet.handler + + def refusing(request: httpx.Request) -> httpx.Response: + if request.method == "POST" and request.url.path.endswith("/configuration_profiles"): + return httpx.Response(502, text="Bad Gateway") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=LATER)] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + + assert result.exit_code == 1 + assert result.output.splitlines()[0] == "Host 31 is OTTER4" + assert "may now be missing" in result.output + assert "Run apply to put it back" in result.output + assert not fleet.profiles + + @pytest.mark.parametrize("command", [["phones"], ["name", "31=OTTER4"], ["resend"]]) def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str]) -> None: """A typo must not leave an empty team behind for the next phone to enrol into""" diff --git a/tests/test_fleet.py b/tests/test_fleet.py index db8eff6..2f1b3ba 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -32,6 +32,9 @@ def __init__(self) -> None: self.calls: list[tuple[str, str]] = [] self.titles: list[dict[str, Any]] = [] self.profiles: list[dict[str, Any]] = [] + #: When an upload lands. Fleet lists a profile's created_at to the microsecond and its + #: updated_at to the second (a live Fleet 4.90.1). + self.now = "2026-11-20T21:02:44.458685Z" self.certificates: list[dict[str, Any]] = [] self.hosts: list[dict[str, Any]] = [] self.web_apps: list[dict[str, Any]] = [] @@ -182,7 +185,13 @@ def handler(self, request: httpx.Request) -> httpx.Response: raw = re.search(rb"application/json\r\n\r\n(.*)\r\n--", request.read(), re.DOTALL) assert raw, "the policy must be uploaded as JSON" self.profiles.append( - {"name": "rmscep-policy", "profile_uuid": f"uuid-{len(self.profiles)}", "raw": json.loads(raw.group(1))} + { + "name": "rmscep-policy", + "profile_uuid": f"uuid-{len(self.profiles)}", + "created_at": self.now, + "updated_at": self.now.split(".")[0] + "Z", + "raw": json.loads(raw.group(1)), + } ) return httpx.Response(200, json={}) if "/configuration_profiles/" in path and request.method == "GET": @@ -254,7 +263,7 @@ def test_a_changed_policy_replaces_the_old_one(monkeypatch: pytest.MonkeyPatch) def test_force_reaches_a_host_that_just_joined(monkeypatch: pytest.MonkeyPatch) -> None: - """A profile is delivered when the PROFILE changes, not when a host arrives""" + """Fleet can overwrite a new host's policy with a bare one, and never sends ours again by itself""" fleet = _Fleet() mdm = _mdm(fleet, monkeypatch) mdm.apply("rmscep", TEMPLATE) @@ -566,3 +575,44 @@ def test_the_launcher_title_names_the_deployment_and_fits() -> None: long_name = FleetMdm._published_title("Deploy App", "https://mtls.thoughtful-hippopotamus.example.org/") assert len(long_name) < 30 assert long_name.startswith("Deploy App (thoughtful") + + +@pytest.mark.parametrize( + ("created", "updated", "enrolled", "later"), + [ + ("2026-11-20T21:02:44.458685Z", "2026-11-20T21:02:44Z", "2026-11-20T21:02:44Z", 0), + ("2026-11-20T21:02:44.458685Z", "2026-11-20T21:02:44Z", "2026-11-20T21:10:02Z", 1), + ("2026-11-20T21:02:44.458685Z", None, "2026-11-20T21:02:44Z", 0), + ("2026-11-20T21:02:44.458685Z", None, "2026-11-20T21:02:45Z", 1), + ("2026-11-20T21:02:44.458685Z", "2026-11-20T21:20:00Z", "2026-11-20T21:10:02Z", 0), + ], +) +def test_enrolment_and_upload_are_compared_as_times( + monkeypatch: pytest.MonkeyPatch, created: str, updated: str | None, enrolled: str, later: int +) -> None: + """Fleet writes created_at to the microsecond, updated_at and last_enrolled_at to the second + + As strings, "...44Z" sorts after "...44.458685Z", so a phone that enrolled before the upload + would read as later. updated_at is the last upload when Fleet gives it. + """ + fleet = _Fleet() + profile = {"name": "rmscep-policy", "profile_uuid": "g4bb", "created_at": created, "raw": TEMPLATE.policy} + fleet.profiles = [profile | ({"updated_at": updated} if updated else {})] + fleet.hosts = [_host(31, enrolled=enrolled), _host(32, enrolled="")] + mdm = _mdm(fleet, monkeypatch) + + assert mdm.resend_policy(7, mdm.phones(7, "rmscep")) == later + assert _policy_uploads(fleet) == later + assert [p["raw"] for p in fleet.profiles] == [TEMPLATE.policy] + + +def test_a_policy_without_a_time_is_reported(monkeypatch: pytest.MonkeyPatch) -> None: + """Rather than ending a command that has already named phones in a traceback""" + fleet = _Fleet() + fleet.profiles = [{"name": "rmscep-policy", "profile_uuid": "g4bb", "raw": TEMPLATE.policy}] + fleet.hosts = [_host(31)] + mdm = _mdm(fleet, monkeypatch) + + with pytest.raises(FleetError, match="the time '' could not be read"): + mdm.resend_policy(7, mdm.phones(7, "rmscep")) + assert not _policy_uploads(fleet) From 9c8381eba460b88a1097c42a92c06bda7573d6fc Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:03:20 +0200 Subject: [PATCH 020/104] refactor!: rename to odmdm-connector, settings to ODMDM_* and --mdm-url --- .bumpversion.toml | 8 +-- README.rst | 50 +++++++-------- examples/template.json | 4 +- pyproject.toml | 8 +-- .../__init__.py | 0 .../config.py | 8 +-- .../console.py | 62 +++++++++---------- src/{odmdm_fleet => odmdm_connector}/fleet.py | 2 +- src/{odmdm_fleet => odmdm_connector}/icon.py | 0 src/{odmdm_fleet => odmdm_connector}/py.typed | 0 .../template.py | 0 tests/test_console.py | 8 +-- tests/test_fleet.py | 6 +- ...odmdm_fleet.py => test_odmdm_connector.py} | 2 +- tests/test_template.py | 2 +- uv.lock | 2 +- 16 files changed, 81 insertions(+), 81 deletions(-) rename src/{odmdm_fleet => odmdm_connector}/__init__.py (100%) rename src/{odmdm_fleet => odmdm_connector}/config.py (89%) rename src/{odmdm_fleet => odmdm_connector}/console.py (88%) rename src/{odmdm_fleet => odmdm_connector}/fleet.py (99%) rename src/{odmdm_fleet => odmdm_connector}/icon.py (100%) rename src/{odmdm_fleet => odmdm_connector}/py.typed (100%) rename src/{odmdm_fleet => odmdm_connector}/template.py (100%) rename tests/{test_odmdm_fleet.py => test_odmdm_connector.py} (78%) diff --git a/.bumpversion.toml b/.bumpversion.toml index 6d289c2..0f8a5d7 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -30,18 +30,18 @@ search = 'version = "{current_version}"' replace = 'version = "{new_version}"' [[tool.bumpversion.files]] -filename = "src/odmdm_fleet/__init__.py" +filename = "src/odmdm_connector/__init__.py" search = '__version__ = "{current_version}"' replace = '__version__ = "{new_version}"' [[tool.bumpversion.files]] -filename = "tests/test_odmdm_fleet.py" +filename = "tests/test_odmdm_connector.py" search = '__version__ == "{current_version}"' replace = '__version__ == "{new_version}"' [[tool.bumpversion.files]] filename = "uv.lock" -search = '''name = "odmdm-fleet" +search = '''name = "odmdm-connector" version = "{current_version}"''' -replace = '''name = "odmdm-fleet" +replace = '''name = "odmdm-connector" version = "{new_version}"''' diff --git a/README.rst b/README.rst index 8402660..c3d18d7 100644 --- a/README.rst +++ b/README.rst @@ -1,6 +1,6 @@ -=========== -odmdm-fleet -=========== +=============== +odmdm-connector +=============== Connects FleetDM to an OpenDefence deployment's device enrolment. @@ -22,20 +22,20 @@ them, and each gets its certificate once it has a name. 1. Once per deployment, and whenever the template changes:: - odmdm-fleet apply + odmdm-connector apply 2. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge. It asks for it, and changes nothing else:: - odmdm-fleet challenge + odmdm-connector challenge 3. Enrol phones into the ``Deploy App`` team, as many as you like, in any order. Name them once every phone in the team has its apps: naming can send the policy to all of them again. 4. Name them, all at once or a few at a time:: - odmdm-fleet name --all OTTER # OTTER1, OTTER2, ... in the order they enrolled - odmdm-fleet name 31=OTTER4 32=OTTER5 # host id = callsign, the ids being what phones prints + odmdm-connector name --all OTTER # OTTER1, OTTER2, ... in the order they enrolled + odmdm-connector name 31=OTTER4 32=OTTER5 # host id = callsign, the ids being what phones prints Each phone gets its certificate at its next check-in, within about 15 minutes, and greets its callsign in Deploy App. ``phones`` shows where each one is. ``resend`` asks again for a refused @@ -60,13 +60,13 @@ Commands .. code-block:: bash - odmdm-fleet apply # state what devices need; --force-policy sends the policy again - odmdm-fleet apply --dry-run # validate the template without touching Fleet - odmdm-fleet challenge # give Fleet a new window's challenge, nothing else - odmdm-fleet phones # each phone's host id, callsign, model and certificate - odmdm-fleet name 31=OTTER4 32=OTTER5 # name these phones, and Fleet sends their certificates - odmdm-fleet name --all OTTER # the same for every phone without a name, numbered - odmdm-fleet resend [HOST_ID ...] # ask again; without ids, every named phone that failed + odmdm-connector apply # state what devices need; --force-policy sends the policy again + odmdm-connector apply --dry-run # validate the template without touching Fleet + odmdm-connector challenge # give Fleet a new window's challenge, nothing else + odmdm-connector phones # each phone's host id, callsign, model and certificate + odmdm-connector name 31=OTTER4 32=OTTER5 # name these phones, and Fleet sends their certificates + odmdm-connector name --all OTTER # the same for every phone without a name, numbered + odmdm-connector resend [HOST_ID ...] # ask again; without ids, every named phone that failed ``name --all`` numbers in enrolment order from one above the highest ``OTTER`` in the team, or from ``--start N``. It sees only this team's phones, and Deploy App never gives a callsign out @@ -81,27 +81,27 @@ Configuration All configuration is via environment variables: -``ODMDM_FLEET_URL`` +``ODMDM_MDM_URL`` Base URL of Fleet's API. -``ODMDM_FLEET_TOKEN_FILE`` +``ODMDM_TOKEN_FILE`` A file holding the Fleet API token. Changing the certificate authority's challenge needs a global admin token, because Fleet keeps certificate authorities outside teams. -``ODMDM_FLEET_TEAM`` +``ODMDM_TEAM`` The team phones enrol into and get the certificate in. Default ``Deploy App``. -``ODMDM_FLEET_TEMPLATE`` +``ODMDM_TEMPLATE`` The document saying what to install, see below. -``ODMDM_FLEET_DOMAIN`` +``ODMDM_DOMAIN`` The deployment's DNS name. -``ODMDM_FLEET_CHALLENGE`` +``ODMDM_CHALLENGE`` The challenge on Deploy App's MDM page, for ``challenge`` and a first ``apply``. New for every enrolment window. -``ODMDM_FLEET_KEY_ALIAS`` +``ODMDM_KEY_ALIAS`` The certificate template's name, which becomes the Android keystore alias. Default ``rmscep``, what the first deployments were set up with. Never change it for a deployment: a second key will not install over an existing alias. @@ -169,11 +169,11 @@ Docker The ``production`` target runs the CLI:: - docker build --ssh default --target production -t odmdm-fleet:latest . - docker run --rm -e ODMDM_FLEET_URL -e ODMDM_FLEET_TOKEN_FILE=/run/token \ + docker build --ssh default --target production -t odmdm-connector:latest . + docker run --rm -e ODMDM_MDM_URL -e ODMDM_TOKEN_FILE=/run/token \ -v "$PWD/fleet.token:/run/token:ro" -v "$PWD/template.json:/run/template.json:ro" \ - -e ODMDM_FLEET_TEMPLATE=/run/template.json -e ODMDM_FLEET_DOMAIN \ - odmdm-fleet:latest odmdm-fleet apply + -e ODMDM_TEMPLATE=/run/template.json -e ODMDM_DOMAIN \ + odmdm-connector:latest odmdm-connector apply For the test suite in docker use the ``tox`` target, and for a development shell ``devel_shell``. diff --git a/examples/template.json b/examples/template.json index 36a18f1..582f9d6 100644 --- a/examples/template.json +++ b/examples/template.json @@ -1,7 +1,7 @@ { "_comment": [ "What a Deploy App deployment's phones need. Copy it, change what to install, and apply it with", - " odmdm-fleet apply --template template.json --domain ", + " odmdm-connector apply --template template.json --domain ", "", "Placeholders filled in at apply time: {domain}, {mtls_url}, {key_alias}.", "", @@ -38,7 +38,7 @@ "certificate": { "_comment": [ "The template Fleet fills in per phone. Its common name becomes the phone's callsign: 3-32", - "letters, digits or inner hyphens. This is the name `odmdm-fleet name` gives a phone. To skip", + "letters, digits or inner hyphens. This is the name `odmdm-connector name` gives a phone. To skip", "naming, CN=$FLEET_VAR_HOST_HARDWARE_SERIAL works for company-owned phones only.", "The name becomes the Android keystore alias, so it is per deployment, not per phone." ], diff --git a/pyproject.toml b/pyproject.toml index ed44436..afa1eb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [project] -name = "odmdm-fleet" +name = "odmdm-connector" version = "0.1.0+261031" description = "Connects FleetDM to an OpenDefence deployment's SCEP device enrolment" authors = [ @@ -19,7 +19,7 @@ homepage = "https://github.com/pvarki/python-odmdm-fleet" repository = "https://github.com/pvarki/python-odmdm-fleet" [project.scripts] -odmdm-fleet = "odmdm_fleet.console:odmdm_fleet_cli" +odmdm-connector = "odmdm_connector.console:odmdm_connector_cli" [dependency-groups] dev = [ @@ -41,7 +41,7 @@ requires = ["hatchling"] build-backend = "hatchling.build" [tool.hatch.build.targets.wheel] -packages = ["src/odmdm_fleet"] +packages = ["src/odmdm_connector"] [tool.ruff] line-length = 120 @@ -56,7 +56,7 @@ disallow_untyped_decorators=false [tool.pytest.ini_options] junit_family="xunit2" -addopts="--cov=odmdm_fleet --cov-fail-under=65 --cov-branch" +addopts="--cov=odmdm_connector --cov-fail-under=65 --cov-branch" [tool.coverage.run] omit = ["tests/*"] diff --git a/src/odmdm_fleet/__init__.py b/src/odmdm_connector/__init__.py similarity index 100% rename from src/odmdm_fleet/__init__.py rename to src/odmdm_connector/__init__.py diff --git a/src/odmdm_fleet/config.py b/src/odmdm_connector/config.py similarity index 89% rename from src/odmdm_fleet/config.py rename to src/odmdm_connector/config.py index 07ef57e..067ed48 100644 --- a/src/odmdm_fleet/config.py +++ b/src/odmdm_connector/config.py @@ -1,6 +1,6 @@ """Configuration, from the environment -Every setting is prefixed ODMDM_FLEET_. +Every setting is prefixed ODMDM_. """ import os @@ -8,13 +8,13 @@ def _env(name: str, default: str = "") -> str: - return os.environ.get(f"ODMDM_FLEET_{name}", default) + return os.environ.get(f"ODMDM_{name}", default) LOG_LEVEL: int = int(_env("LOG_LEVEL", "20")) #: Where Fleet's API answers -URL: str = _env("URL") +URL: str = _env("MDM_URL") #: A file holding the Fleet API token. A path rather than the value, so it can be a mounted secret #: and never appears in a process environment. @@ -23,7 +23,7 @@ def _env(name: str, default: str = "") -> str: #: The team whose devices get the deployment's certificate TEAM: str = _env("TEAM", "Deploy App") -#: What this deployment wants installed, as a document. See odmdm_fleet.template. +#: What this deployment wants installed, as a document. See odmdm_connector.template. TEMPLATE: Path | None = Path(_env("TEMPLATE")) if _env("TEMPLATE") else None #: The deployment's DNS name, which the template substitutes into URLs diff --git a/src/odmdm_fleet/console.py b/src/odmdm_connector/console.py similarity index 88% rename from src/odmdm_fleet/console.py rename to src/odmdm_connector/console.py index 2f53c77..e2a7636 100644 --- a/src/odmdm_fleet/console.py +++ b/src/odmdm_connector/console.py @@ -1,4 +1,4 @@ -"""CLI entrypoints for odmdm-fleet""" +"""CLI entrypoints for odmdm-connector""" import logging import re @@ -7,7 +7,7 @@ import click from libadvian.logging import init_logging -from odmdm_fleet import __version__ +from odmdm_connector import __version__ from . import config, template from .fleet import FleetError, FleetMdm, Phone @@ -37,7 +37,7 @@ def cli_group(ctx: click.Context, verbose: int) -> None: logging.getLogger("httpx").setLevel(max(loglevel, logging.WARNING) if verbose < 2 else loglevel) -def odmdm_fleet_cli() -> None: +def odmdm_connector_cli() -> None: """CLI entrypoint""" cli_group() # pylint: disable=no-value-for-parameter @@ -46,11 +46,11 @@ def _fleet(ctx: click.Context, url: str | None) -> FleetMdm | None: """Fleet's API, or None after saying what is missing""" the_url = url or config.URL if not the_url: - click.echo("Give --fleet-url or set ODMDM_FLEET_URL", err=True) + click.echo("Give --mdm-url or set ODMDM_MDM_URL", err=True) ctx.exit(1) return None if not config.TOKEN_FILE or not config.TOKEN_FILE.is_file(): - click.echo("Set ODMDM_FLEET_TOKEN_FILE to a file holding the Fleet API token", err=True) + click.echo("Set ODMDM_TOKEN_FILE to a file holding the Fleet API token", err=True) ctx.exit(1) return None return FleetMdm(the_url, config.TOKEN_FILE.read_text(encoding="utf-8").strip()) @@ -61,7 +61,7 @@ def _template(ctx: click.Context, path: str | None, domain: str | None) -> templ the_path = Path(path) if path else config.TEMPLATE the_domain = domain or config.DOMAIN if not the_path or not the_domain: - click.echo("Give --template and --domain or set ODMDM_FLEET_TEMPLATE and ODMDM_FLEET_DOMAIN", err=True) + click.echo("Give --template and --domain or set ODMDM_TEMPLATE and ODMDM_DOMAIN", err=True) ctx.exit(1) return None try: @@ -74,10 +74,10 @@ def _template(ctx: click.Context, path: str | None, domain: str | None) -> templ @cli_group.command(name="apply") @click.pass_context -@click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_FLEET_TEAM)") -@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") +@click.option("--template", "path", default=None, help="What to install (default: ODMDM_TEMPLATE)") +@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") +@click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_TEAM)") +@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_DOMAIN)") @click.option( "--force-policy", is_flag=True, help="Re-upload the policy even if unchanged, to reach a host that just joined" ) @@ -85,7 +85,7 @@ def _template(ctx: click.Context, path: str | None, domain: str | None) -> templ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx: click.Context, path: str | None, - fleet_url: str | None, + mdm_url: str | None, team: str | None, domain: str | None, force_policy: bool, @@ -113,7 +113,7 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx.exit(0) return - fleet = _fleet(ctx, fleet_url) + fleet = _fleet(ctx, mdm_url) if not fleet: return try: @@ -137,16 +137,16 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments @click.option( "--challenge", "value", - envvar="ODMDM_FLEET_CHALLENGE", + envvar="ODMDM_CHALLENGE", prompt="Challenge from Deploy App's MDM page", hide_input=True, - help="The new window's challenge (default: ODMDM_FLEET_CHALLENGE, else asked for)", + help="The new window's challenge (default: ODMDM_CHALLENGE, else asked for)", ) -@click.option("--template", "path", default=None, help="What to install (default: ODMDM_FLEET_TEMPLATE)") -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_FLEET_DOMAIN)") +@click.option("--template", "path", default=None, help="What to install (default: ODMDM_TEMPLATE)") +@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") +@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_DOMAIN)") def challenge( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, value: str, path: str | None, fleet_url: str | None, domain: str | None + ctx: click.Context, value: str, path: str | None, mdm_url: str | None, domain: str | None ) -> None: """Give Fleet the challenge of the enrolment window just opened @@ -161,7 +161,7 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen click.echo("The template states no certificate, so there is no authority to give it to", err=True) ctx.exit(1) return - fleet = _fleet(ctx, fleet_url) + fleet = _fleet(ctx, mdm_url) if not fleet: return try: @@ -176,15 +176,15 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen @cli_group.command(name="phones") @click.pass_context -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_FLEET_TEAM)") -def phones(ctx: click.Context, fleet_url: str | None, team: str | None) -> None: +@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") +@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") +def phones(ctx: click.Context, mdm_url: str | None, team: str | None) -> None: """List the team's phones and where each one's certificate is One line each: the host id that name and resend take, the callsign, the model, the day it enrolled, and the certificate in plain words. """ - fleet = _fleet(ctx, fleet_url) + fleet = _fleet(ctx, mdm_url) if not fleet: return try: @@ -267,14 +267,14 @@ def _policy_again(fleet: FleetMdm, team_id: int, found: dict[int, Phone]) -> Non @click.option( "--start", type=int, metavar="N", default=None, help="The first n for --all (default: one above the highest in use)" ) -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_FLEET_TEAM)") +@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") +@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") def name( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx: click.Context, pairs: tuple[str, ...], prefix: str | None, start: int | None, - fleet_url: str | None, + mdm_url: str | None, team: str | None, ) -> None: """Name phones, and have Fleet send them certificates @@ -294,7 +294,7 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments if bool(pairs) == bool(prefix) or (start is not None and not prefix): raise click.UsageError("Give HOST=CALLSIGN for each phone, or --all PREFIX") wanted = _pairs(pairs) - fleet = _fleet(ctx, fleet_url) + fleet = _fleet(ctx, mdm_url) if not fleet: return try: @@ -339,9 +339,9 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments @cli_group.command(name="resend") @click.pass_context @click.argument("hosts", nargs=-1, type=int) -@click.option("--fleet-url", default=None, help="Base URL of Fleet's API (default: ODMDM_FLEET_URL)") -@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_FLEET_TEAM)") -def resend(ctx: click.Context, hosts: tuple[int, ...], fleet_url: str | None, team: str | None) -> None: +@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") +@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") +def resend(ctx: click.Context, hosts: tuple[int, ...], mdm_url: str | None, team: str | None) -> None: """Have Fleet send phones their certificate requests again For a refused phone once the cause is fixed, such as enrolment opened again and its new @@ -354,7 +354,7 @@ def resend(ctx: click.Context, hosts: tuple[int, ...], fleet_url: str | None, te name it holds and is refused, and reads as refused from then on though that certificate still works. As with name, the team's policy is sent again if a phone enrolled after it was last sent. """ - fleet = _fleet(ctx, fleet_url) + fleet = _fleet(ctx, mdm_url) if not fleet: return try: diff --git a/src/odmdm_fleet/fleet.py b/src/odmdm_connector/fleet.py similarity index 99% rename from src/odmdm_fleet/fleet.py rename to src/odmdm_connector/fleet.py index 832f0c4..36a81b4 100644 --- a/src/odmdm_fleet/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -162,7 +162,7 @@ def team_id(self, name: str, create: bool = False) -> int: if team.get("name") == name: return int(team["id"]) if not create: - raise FleetError(f"no team named {name}: check --team or ODMDM_FLEET_TEAM") + raise FleetError(f"no team named {name}: check --team or ODMDM_TEAM") created = self._call("POST", "/api/latest/fleet/teams", {"name": name}) team = created.get("team", created) LOGGER.info("Created team %s", name) diff --git a/src/odmdm_fleet/icon.py b/src/odmdm_connector/icon.py similarity index 100% rename from src/odmdm_fleet/icon.py rename to src/odmdm_connector/icon.py diff --git a/src/odmdm_fleet/py.typed b/src/odmdm_connector/py.typed similarity index 100% rename from src/odmdm_fleet/py.typed rename to src/odmdm_connector/py.typed diff --git a/src/odmdm_fleet/template.py b/src/odmdm_connector/template.py similarity index 100% rename from src/odmdm_fleet/template.py rename to src/odmdm_connector/template.py diff --git a/tests/test_console.py b/tests/test_console.py index 6eb6cf4..36c2eaa 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -11,8 +11,8 @@ import pytest from click.testing import CliRunner -from odmdm_fleet import config -from odmdm_fleet.console import cli_group +from odmdm_connector import config +from odmdm_connector.console import cli_group from .test_fleet import _Fleet, _host, _mdm @@ -51,7 +51,7 @@ def test_a_template_and_domain_are_required(command: list[str], monkeypatch: pyt result = CliRunner().invoke(cli_group, command) assert result.exit_code == 1 - assert "ODMDM_FLEET_TEMPLATE" in result.output + assert "ODMDM_TEMPLATE" in result.output def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -115,7 +115,7 @@ def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: result = CliRunner().invoke(cli_group, ["phones"]) assert result.exit_code == 1 - assert "ODMDM_FLEET_URL" in result.output + assert "ODMDM_MDM_URL" in result.output NO_NAME = ( diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 2f1b3ba..955402d 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -12,9 +12,9 @@ import httpx import pytest -from odmdm_fleet.fleet import FleetError, FleetMdm -from odmdm_fleet.icon import launcher_icon -from odmdm_fleet.template import App, Certificate, LinkApp, MdmTemplate +from odmdm_connector.fleet import FleetError, FleetMdm +from odmdm_connector.icon import launcher_icon +from odmdm_connector.template import App, Certificate, LinkApp, MdmTemplate TEMPLATE = MdmTemplate( apps=( diff --git a/tests/test_odmdm_fleet.py b/tests/test_odmdm_connector.py similarity index 78% rename from tests/test_odmdm_fleet.py rename to tests/test_odmdm_connector.py index 196f9d6..2eb40f5 100644 --- a/tests/test_odmdm_fleet.py +++ b/tests/test_odmdm_connector.py @@ -1,6 +1,6 @@ """Package level tests""" -from odmdm_fleet import __version__ +from odmdm_connector import __version__ def test_version() -> None: diff --git a/tests/test_template.py b/tests/test_template.py index fc7b553..315fcb1 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -9,7 +9,7 @@ import pytest -from odmdm_fleet.template import TemplateError, load +from odmdm_connector.template import TemplateError, load GOOD = { "apps": [ diff --git a/uv.lock b/uv.lock index 5185487..18040f2 100644 --- a/uv.lock +++ b/uv.lock @@ -713,7 +713,7 @@ wheels = [ ] [[package]] -name = "odmdm-fleet" +name = "odmdm-connector" version = "0.1.0+261031" source = { editable = "." } dependencies = [ From 45a89e5f6847b07ca3ee9b0c0f31ebb0acc909ff Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:03:35 +0200 Subject: [PATCH 021/104] chore!: remove the docker image, the tool is installed with uv --- .dockerignore | 55 ---------- .github/workflows/pull_request.yml | 45 -------- .github/workflows/push_to_main.yml | 20 ---- Dockerfile | 160 ----------------------------- README.rst | 13 --- docker/entrypoint-test.sh | 20 ---- docker/entrypoint.sh | 6 -- docker/pre_commit_init.sh | 10 -- tox.ini | 2 +- 9 files changed, 1 insertion(+), 330 deletions(-) delete mode 100644 .dockerignore delete mode 100644 Dockerfile delete mode 100755 docker/entrypoint-test.sh delete mode 100755 docker/entrypoint.sh delete mode 100755 docker/pre_commit_init.sh diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 2e70504..0000000 --- a/.dockerignore +++ /dev/null @@ -1,55 +0,0 @@ -# General good ideas to ignore -.idea -.git -.cache -.venv - -# docker build files (so just changing them does not invalidate *all* caches) -.dockerignore -Dockerfile - -# Byte-compiled / optimized / DLL files -**/__pycache__/ -**/*.py[cod] -**/*$py.class - -# Distribution / packaging -**/.Python -**/build/ -**/develop-eggs/ -**/dist/ -**/downloads/ -**/eggs/ -**/.eggs/ -**/lib/ -**/lib64/ -**/parts/ -**/sdist/ -**/var/ -**/wheels/ -**/pip-wheel-metadata/ -**/share/python-wheels/ -**/*.egg-info/ -**/.installed.cfg -**/*.egg - -# Unit test / coverage reports -**/htmlcov/ -**/.tox/ -**/.nox/ -**/.coverage -**/.coverage.* -**/.cache -**/nosetests.xml -**/coverage.xml -**/*.cover -**/*.py,cover -**/.hypothesis/ -**/.pytest_cache/ - -# mypy -**/.mypy_cache/ -**/.ruff_cache/ -.prettier_cache -**/.dmypy.json -**/dmypy.json diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index e89b6bc..79b4e77 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -62,48 +62,3 @@ jobs: with: snyk-org: deployapp-core-services snyk-token: ${{ secrets.SNYK_TOKEN }} - - docker-build-and-verify: - name: Build Docker images - runs-on: ubuntu-latest # arc-runner-set - steps: - # The base images come from Docker Hub, whose anonymous pull limit is shared across all of - # GitHub's egress, so an unauthenticated build fails at random. - - name: Log in to Docker Hub - uses: docker/login-action@v3 - with: - username: ${{ vars.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - uses: actions/checkout@v6 - - name: Build test target - run: docker build --target test -t odmdm-fleet:test . - - name: Build production target - run: docker build --target production -t odmdm-fleet:production . - - publish: - name: Publish Docker image - needs: - [ - "general-checks", - "pre-commit", - "test", - "snyk-test", - "docker-build-and-verify", - ] - runs-on: arc-runner-set - permissions: - contents: read - packages: write - steps: - - uses: actions/checkout@v6 - - name: Publish Docker image - uses: pvarki/config-ci-library/.github/actions/publish-image@main - with: - product: odmdm-fleet - component: server - dockerhub-username: ${{ vars.DOCKERHUB_USERNAME }} - dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} - github-token: ${{ secrets.GITHUB_TOKEN }} - acr-repo: ${{ vars.ACR_REPO }} - acr-username: ${{ vars.ACR_USERNAME }} - acr-token: ${{ secrets.ACR_TOKEN }} diff --git a/.github/workflows/push_to_main.yml b/.github/workflows/push_to_main.yml index c21aaf8..ea01d18 100644 --- a/.github/workflows/push_to_main.yml +++ b/.github/workflows/push_to_main.yml @@ -17,23 +17,3 @@ jobs: with: snyk-org: deployapp-core-services snyk-token: ${{ secrets.SNYK_TOKEN }} - - publish: - name: Publish Docker image - runs-on: arc-runner-set - permissions: - contents: read - packages: write - steps: - - uses: actions/checkout@v6 - - name: Publish Docker image - uses: pvarki/config-ci-library/.github/actions/publish-image@main - with: - product: odmdm-fleet - component: server - dockerhub-username: ${{ vars.DOCKERHUB_USERNAME }} - dockerhub-token: ${{ secrets.DOCKERHUB_TOKEN }} - github-token: ${{ secrets.GITHUB_TOKEN }} - acr-repo: ${{ vars.ACR_REPO }} - acr-username: ${{ vars.ACR_USERNAME }} - acr-token: ${{ secrets.ACR_TOKEN }} diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index f5d32ec..0000000 --- a/Dockerfile +++ /dev/null @@ -1,160 +0,0 @@ -# syntax=docker/dockerfile:1.1.7-experimental -############################################# -# Tox testsuite for multiple python version # -############################################# -FROM advian/tox-base:debian-bookworm AS tox -ARG PYTHON_VERSIONS="3.11 3.12" -ARG UV_VERSION="0.11.6" -RUN export RESOLVED_VERSIONS=`pyenv_resolve $PYTHON_VERSIONS` \ - && echo RESOLVED_VERSIONS=$RESOLVED_VERSIONS \ - && for pyver in $RESOLVED_VERSIONS; do pyenv install -s $pyver; done \ - && pyenv global $RESOLVED_VERSIONS \ - && pip install -U "uv==$UV_VERSION" tox tox-uv \ - && apt-get update && apt-get install -y \ - git \ - musl-dev \ - ca-certificates curl gnupg \ - && rm -rf /var/lib/apt/lists/* \ - && ln -s /usr/lib/x86_64-linux-musl/libc.so /lib/libc.musl-$(uname -m).so.1 \ - # Fix git runtime fatal: - # unsafe repository ('/app' is owned by someone else) - && git config --global --add safe.directory /app \ - && true -COPY ./uv.lock ./pyproject.toml ./README.rst ./.pre-commit-config.yaml /app/ -COPY ./docker /app/docker/ -WORKDIR /app -RUN uv sync --frozen \ - && rm -rf .venv - - -###################### -# Base builder image # -###################### -FROM python:3.11-bookworm AS builder_base -COPY --from=ghcr.io/astral-sh/uv:0.11.6 /uv /uvx /usr/local/bin/ - -ENV \ - # locale - LC_ALL=C.UTF-8 \ - # python: - PYTHONFAULTHANDLER=1 \ - PYTHONUNBUFFERED=1 \ - PYTHONHASHSEED=random \ - # pip: - PIP_NO_CACHE_DIR=off \ - PIP_DISABLE_PIP_VERSION_CHECK=on \ - PIP_DEFAULT_TIMEOUT=100 \ - PIP_INDEX_URL=https://nexus.dev.pvarki.fi/repository/python/simple \ - # uv: - UV_DEFAULT_INDEX=https://nexus.dev.pvarki.fi/repository/python/simple \ - UV_PROJECT_ENVIRONMENT=/.venv \ - UV_LINK_MODE=copy - -RUN apt-get update && apt-get install -y \ - curl \ - git \ - bash \ - build-essential \ - libffi-dev \ - libssl-dev \ - tini \ - openssh-client \ - cargo \ - pkg-config \ - && apt-get autoremove -y \ - && rm -rf /var/lib/apt/lists/* \ - # githublab ssh - && mkdir -p -m 0700 ~/.ssh && ssh-keyscan gitlab.com github.com | sort > ~/.ssh/known_hosts \ - && true - -SHELL ["/bin/bash", "-lc"] - - -# Copy only requirements, to cache them in docker layer: -WORKDIR /pysetup -COPY ./uv.lock ./pyproject.toml ./README.rst /pysetup/ -# Install runtime dependencies into /.venv (without the project itself) -RUN --mount=type=ssh uv venv /.venv \ - && echo 'source /.venv/bin/activate' >>/root/.profile \ - && uv sync --frozen --no-install-project --no-dev \ - && true - - -#################################### -# Base stage for production builds # -#################################### -FROM builder_base AS production_build -# Copy entrypoint scripts -COPY ./docker/entrypoint.sh /docker-entrypoint.sh -# Only files needed by production setup -COPY ./uv.lock ./pyproject.toml ./README.rst /app/ -COPY ./src /app/src/ -WORKDIR /app -# Build the wheel package with uv -RUN --mount=type=ssh source /.venv/bin/activate \ - && mkdir -p /tmp/wheelhouse \ - && uv build --wheel --out-dir /tmp/wheelhouse \ - && chmod a+x /docker-entrypoint.sh \ - && true - - -######################### -# Main production build # -######################### -FROM python:3.11-slim-bookworm AS production -COPY --from=production_build /tmp/wheelhouse /tmp/wheelhouse -COPY --from=production_build /docker-entrypoint.sh /docker-entrypoint.sh -WORKDIR /app -# Install system level deps for running the package (not devel versions for building wheels) -# and install the wheels we built in the previous step. -RUN --mount=type=ssh apt-get update && apt-get install -y \ - bash \ - libffi8 \ - tini \ - && apt-get autoremove -y \ - && rm -rf /var/lib/apt/lists/* \ - && chmod a+x /docker-entrypoint.sh \ - && WHEELFILE=`echo /tmp/wheelhouse/odmdm_fleet-*.whl` \ - && pip3 install --index-url https://nexus.dev.pvarki.fi/repository/python/simple "$WHEELFILE" \ - && rm -rf /tmp/wheelhouse/ \ - && true -ENTRYPOINT ["/usr/bin/tini", "--", "/docker-entrypoint.sh"] - - -##################################### -# Base stage for development builds # -##################################### -FROM builder_base AS devel_build -# Install deps -COPY . /app -WORKDIR /app -RUN --mount=type=ssh source /.venv/bin/activate \ - && uv sync --frozen \ - && true - - -############# -# Run tests # -############# -FROM devel_build AS test -WORKDIR /app -ENTRYPOINT ["/usr/bin/tini", "--", "docker/entrypoint-test.sh"] -# Re run install to get the service itself installed -RUN --mount=type=ssh source /.venv/bin/activate \ - && uv sync --frozen \ - && true - - -########### -# Hacking # -########### -FROM devel_build AS devel_shell -# Copy everything to the image -COPY . /app -WORKDIR /app -RUN apt-get update && apt-get install -y zsh jq vim \ - && sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" \ - && echo "source /root/.profile" >>/root/.zshrc \ - && pip3 install git-up \ - && true -ENTRYPOINT ["/bin/zsh", "-l"] diff --git a/README.rst b/README.rst index c3d18d7..2ff6d71 100644 --- a/README.rst +++ b/README.rst @@ -164,19 +164,6 @@ What Fleet does that you would not guess challenge. A taken name is never freed, not even by revoking it, so give the phone another with ``name``. For the challenge, ``challenge`` and then ``resend``. -Docker ------- - -The ``production`` target runs the CLI:: - - docker build --ssh default --target production -t odmdm-connector:latest . - docker run --rm -e ODMDM_MDM_URL -e ODMDM_TOKEN_FILE=/run/token \ - -v "$PWD/fleet.token:/run/token:ro" -v "$PWD/template.json:/run/template.json:ro" \ - -e ODMDM_TEMPLATE=/run/template.json -e ODMDM_DOMAIN \ - odmdm-connector:latest odmdm-connector apply - -For the test suite in docker use the ``tox`` target, and for a development shell ``devel_shell``. - Development ----------- diff --git a/docker/entrypoint-test.sh b/docker/entrypoint-test.sh deleted file mode 100755 index a983925..0000000 --- a/docker/entrypoint-test.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/bash -l -set -e -# shellcheck disable=SC1091 -source /.venv/bin/activate -if [ "$#" -eq 0 ]; then - # Kill cache, pytest complains about it if running local and docker tests in mapped volume - find tests -type d -name '__pycache__' -print0 | xargs -0 rm -rf {} - # Make sure the service itself is installed - uv sync --frozen - # Make sure pre-commit checks were not missed because reasons. Via the init script because - # .git is not in the image and prek needs a repository. - docker/pre_commit_init.sh - # Then run the tests - pytest --junitxml=pytest.xml tests/ - # If prek does not run these, enable them - # mypy src tests - # bandit --skip=B101 -r src -else - exec "$@" -fi diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh deleted file mode 100755 index 22c2644..0000000 --- a/docker/entrypoint.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash -l -set -e -if [ "$#" -eq 0 ]; then - exec odmdm-fleet --help -fi -exec "$@" diff --git a/docker/pre_commit_init.sh b/docker/pre_commit_init.sh deleted file mode 100755 index 0dc8161..0000000 --- a/docker/pre_commit_init.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash -l -if [ ! -d .git ] -then - git init - git checkout -b precommit_init - git add . -fi -set -e -uv run prek install -uv run prek run --all-files diff --git a/tox.ini b/tox.ini index 79e6235..6213311 100644 --- a/tox.ini +++ b/tox.ini @@ -13,7 +13,7 @@ passenv = SSH_AUTH_SOCK SKIP commands = - uv run docker/pre_commit_init.sh # also runs pre-commit + uv run prek run --all-files uv run pytest --junitxml=pytest-{envname}.xml tests/ # if pre-commit does not run these (or you don't run pre-commit here) enable at least these checks # uv run mypy src tests From f0f55b25878eb8fc80c89a3c8c1cafe5917f46fa Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:04:41 +0200 Subject: [PATCH 022/104] ci: test on linux, windows and macos, pin actions by sha, tag and release --- .github/actionlint.yaml | 5 --- .github/workflows/pull_request.yml | 66 ++++++++++++++---------------- .github/workflows/push_to_main.yml | 30 ++++++++++++-- 3 files changed, 58 insertions(+), 43 deletions(-) delete mode 100644 .github/actionlint.yaml diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml deleted file mode 100644 index 6e69775..0000000 --- a/.github/actionlint.yaml +++ /dev/null @@ -1,5 +0,0 @@ -# Configuration related to self-hosted runner. -self-hosted-runner: - # Labels of self-hosted runner in array of strings. - labels: - - arc-runner-set diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 79b4e77..fae683b 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -2,63 +2,59 @@ on: pull_request: workflow_dispatch: # Allow manual triggering +permissions: + contents: read + jobs: - # Only the bumpversion half. The library's prek job is checkout + prek-action with no venv, and - # the generated python config ends in a local mypy hook that resolves from PATH, so it cannot - # run there. Every sibling runs prek itself, after setup-python. - general-checks: - name: General checks - uses: pvarki/config-ci-library/.github/workflows/general-check.yml@main - with: - run-prek: false + # The library's general-check runs prek without a venv, and the generated python config ends in a + # local mypy hook that resolves from PATH, so prek runs here after setup-python instead. + bumpversion-check: + name: Validate .bumpversion.toml + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/validate-bumpversion@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 pre-commit: name: Run pre-commit checks runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: - python-version: "3.11" + python-version: "3.12" - name: Do pre-commit checks - run: | - uv run prek run --all-files + run: uv run prek run --all-files test: - name: Run tests - runs-on: ubuntu-latest - permissions: - contents: write - pull-requests: write - checks: write + name: Test (${{ matrix.os }}, Python ${{ matrix.python-version }}) + runs-on: ${{ matrix.os }} strategy: + fail-fast: false matrix: - python-version: ["3.11"] + os: [ubuntu-latest, windows-latest, macos-latest] + python-version: ["3.12"] + include: + - os: ubuntu-latest + python-version: "3.11" steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: python-version: ${{ matrix.python-version }} - - name: Test with pytest - run: | - uv run py.test -v --junitxml=pytest.xml - - name: Publish Test Report - uses: mikepenz/action-junit-report@v4 - if: success() || failure() # always run even if the previous step fails - with: - report_paths: "**/pytest*.xml" - detailed_summary: true - check_name: "JUnit report (local)" + - name: Test with pytest, coverage floor in pyproject.toml + run: uv run pytest -v snyk-test: name: Run Snyk test runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: python-version: "3.11" - - uses: pvarki/config-ci-library/.github/actions/snyk-test@main + - uses: pvarki/config-ci-library/.github/actions/snyk-test@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: snyk-org: deployapp-core-services snyk-token: ${{ secrets.SNYK_TOKEN }} diff --git a/.github/workflows/push_to_main.yml b/.github/workflows/push_to_main.yml index ea01d18..6f0d3bf 100644 --- a/.github/workflows/push_to_main.yml +++ b/.github/workflows/push_to_main.yml @@ -4,16 +4,40 @@ on: - main workflow_dispatch: # Allow manual triggering +permissions: + contents: read + jobs: snyk-monitor: name: Run Snyk monitor runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - uses: pvarki/config-ci-library/.github/actions/setup-python@main + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: python-version: "3.11" - - uses: pvarki/config-ci-library/.github/actions/snyk-monitor@main + - uses: pvarki/config-ci-library/.github/actions/snyk-monitor@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 with: snyk-org: deployapp-core-services snyk-token: ${{ secrets.SNYK_TOKEN }} + + release: + name: Tag the current version and release it + runs-on: ubuntu-latest + permissions: + contents: write + packages: read + pull-requests: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + - uses: pvarki/config-ci-library/.github/actions/tag-release@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + id: tag + - uses: pvarki/config-ci-library/.github/actions/release-notes@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + if: steps.tag.outputs.tag != '' + with: + ref: ${{ steps.tag.outputs.tag }} + release: ${{ steps.tag.outputs.version }} + product: odmdm-connector + attach-to-release: "true" From 736ae026b94db5e6fee5e5042d9647e177d873fc Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:04:54 +0200 Subject: [PATCH 023/104] chore: bump version to 1.0.0+261121 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/odmdm_connector/__init__.py | 2 +- tests/test_odmdm_connector.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 0f8a5d7..e2cebe9 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.1.0+261031" +current_version = "1.0.0+261121" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index afa1eb8..e60b395 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "0.1.0+261031" +version = "1.0.0+261121" description = "Connects FleetDM to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index 5ea4aca..afc294a 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ """Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" -__version__ = "0.1.0+261031" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.0.0+261121" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index 2eb40f5..35e897c 100644 --- a/tests/test_odmdm_connector.py +++ b/tests/test_odmdm_connector.py @@ -5,4 +5,4 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "0.1.0+261031" + assert __version__ == "1.0.0+261121" diff --git a/uv.lock b/uv.lock index 18040f2..c0569e9 100644 --- a/uv.lock +++ b/uv.lock @@ -714,7 +714,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "0.1.0+261031" +version = "1.0.0+261121" source = { editable = "." } dependencies = [ { name = "click" }, From 7c04f7a07c3493fd6fb079f0446e43e712eeeed9 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:05:18 +0200 Subject: [PATCH 024/104] docs: agent commands, version bump rule and crown jewels --- AGENTS.md | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3505944..33dc6b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,21 @@ Names already in use on live Fleets are identities, not cosmetics: the policy pr certificate template name (the Android keystore alias). Changing either duplicates the profile or strands every enrolled phone's key. -## Checks - -`uv run pytest` needs no network, no Fleet and no phone. `uv run prek run --all-files` before -committing. +## Commands + +- Setup: `uv sync` +- Test: `uv run pytest` (coverage floor: 65%, set in `pyproject.toml`). Needs no network, no Fleet + and no phone. +- Hooks, before every commit: `uv run prek run --all-files`. Once per clone: + `uv run prek install --hook-type pre-commit --hook-type commit-msg` +- Version bump, once per pull request, in its own commit: `uv run bump-my-version bump patch|minor|major` + +## Crown jewels + +- **The MDM API token** (today a Fleet global admin token): it can change what every enrolled + phone of every team installs and trusts. The only place that reads it is `_fleet` in + `src/odmdm_connector/console.py`, from the file `ODMDM_TOKEN_FILE` names; `FleetMdm` keeps it in + memory and sends it only as the `Authorization` header to the MDM URL. +- The tool never logs it, prints it, takes it as an option or argument, or writes it to a file. + Keep it that way: no `--token` option, no token in an environment variable, no token in an error + message. `.gitignore` ignores `*.token` so a token file in the checkout cannot be committed. From bb325d5f9fc166204731669326a2ad2be4ec83c6 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:05:21 +0200 Subject: [PATCH 025/104] chore: ignore token files, keep the token outside the checkout --- .gitignore | 4 ++++ README.rst | 2 ++ 2 files changed, 6 insertions(+) diff --git a/.gitignore b/.gitignore index 8b1dd4b..45d0186 100644 --- a/.gitignore +++ b/.gitignore @@ -138,3 +138,7 @@ dmypy.json # Pre-commit / prettier cache .prettier_cache .ruff_cache/ + +# MDM API tokens and local template copies: keep them outside the checkout, never commit them +*.token +/template*.json diff --git a/README.rst b/README.rst index 2ff6d71..b6cdd6b 100644 --- a/README.rst +++ b/README.rst @@ -87,6 +87,8 @@ All configuration is via environment variables: ``ODMDM_TOKEN_FILE`` A file holding the Fleet API token. Changing the certificate authority's challenge needs a global admin token, because Fleet keeps certificate authorities outside teams. + Keep the file outside this checkout, readable only by you: the token can change every + enrolled phone. The tool reads it and never prints, logs or writes it. ``ODMDM_TEAM`` The team phones enrol into and get the certificate in. Default ``Deploy App``. From 2e25d09e7f2ff2b4ada6143c6a52b58d733fd7ae Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:07:55 +0200 Subject: [PATCH 026/104] feat!: refuse templates that hand the key out or name phones by serial The example template now lets only its named apps use the key, disallows unknown sources and grants no permission by default. --- .secrets.baseline | 4 +- README.rst | 11 ++++- examples/template.json | 17 ++++---- src/odmdm_connector/template.py | 37 +++++++++++++++++ tests/test_console.py | 7 +++- tests/test_template.py | 73 ++++++++++++++++++++++++++++++++- 6 files changed, 133 insertions(+), 16 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index 1b227b5..02ee3f5 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -139,9 +139,9 @@ "filename": "tests/test_template.py", "hashed_secret": "4190096e3d9edbcb774caa4770639409d73ecac6", "is_verified": false, - "line_number": 45 + "line_number": 47 } ] }, - "generated_at": "2026-10-31T22:02:07Z" + "generated_at": "2026-11-21T04:07:40Z" } diff --git a/README.rst b/README.rst index b6cdd6b..4821113 100644 --- a/README.rst +++ b/README.rst @@ -118,9 +118,18 @@ beginning with ``_`` are comments and never reach Fleet. ``examples/template.jso for Deploy App, with its reasoning in the comments. The certificate subject is the contract with the deployment. Its common name becomes the callsign: -3 to 32 letters, digits or hyphens, no hyphen at either end. For named phones:: +3 to 32 letters, digits or hyphens, no hyphen at either end. It is the name ``name`` gives the +phone, optionally followed by Fleet's id for the host, and the tool refuses any other:: CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART + CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID + +A name the phone supplies, such as its serial number, would make a leaked enrolment link enough +for an identity. + +The tool also refuses a policy that lets an app use the key without being named in +``packageNames``, lets the user pick a key for any app (``privateKeySelectionEnabled``), or +allows installs from unknown sources (``untrustedAppsPolicy`` other than ``DISALLOW_INSTALL``). The order that works -------------------- diff --git a/examples/template.json b/examples/template.json index 582f9d6..5eef1b7 100644 --- a/examples/template.json +++ b/examples/template.json @@ -38,9 +38,10 @@ "certificate": { "_comment": [ "The template Fleet fills in per phone. Its common name becomes the phone's callsign: 3-32", - "letters, digits or inner hyphens. This is the name `odmdm-connector name` gives a phone. To skip", - "naming, CN=$FLEET_VAR_HOST_HARDWARE_SERIAL works for company-owned phones only.", - "The name becomes the Android keystore alias, so it is per deployment, not per phone." + "letters, digits or inner hyphens. This is the name `odmdm-connector name` gives a phone, and", + "the connector refuses any other common name: one the phone supplies, such as its serial", + "number, would make a leaked enrolment link enough for an identity. OU=$FLEET_VAR_HOST_UUID", + "may follow it. The name becomes the Android keystore alias, so it is per deployment." ], "authority": "RMSCEP", "name": "{key_alias}", @@ -53,14 +54,11 @@ }, "policy": { "_comment_key": "urlPattern is a java.util.regex pattern matched against the WHOLE string the app passes. Chrome passes host:port with no scheme (mtls.example.fi:443), so a pattern starting https:// matches nothing, the device offers no key, and the server answers mtls_fail exactly as if no certificate existed. This one takes both forms and still only the mTLS host.", + "_comment_safety": "Only the named apps may use the key, the user cannot hand it to another app, nothing installs from unknown sources, and apps ask for their permissions as usual. The connector refuses a template that loosens the first three.", "advancedSecurityOverrides": { - "untrustedAppsPolicy": "ALLOW_INSTALL_DEVICE_WIDE" + "untrustedAppsPolicy": "DISALLOW_INSTALL" }, "choosePrivateKeyRules": [ - { - "privateKeyAlias": "{key_alias}", - "urlPattern": "(https://)?mtls\\.{domain}(:443)?(/.*)?" - }, { "packageNames": [ "com.android.chrome", @@ -71,7 +69,6 @@ "urlPattern": "(https://)?mtls\\.{domain}(:443)?(/.*)?" } ], - "defaultPermissionPolicy": "GRANT", - "privateKeySelectionEnabled": true + "privateKeySelectionEnabled": false } } diff --git a/src/odmdm_connector/template.py b/src/odmdm_connector/template.py index 9a7a469..c11d21e 100644 --- a/src/odmdm_connector/template.py +++ b/src/odmdm_connector/template.py @@ -16,6 +16,7 @@ import json import logging +import re from dataclasses import dataclass, field from pathlib import Path from typing import Any @@ -27,6 +28,38 @@ class TemplateError(ValueError): """The document is not something we can act on""" +#: The callsign as the common name, from the name the operator gives the phone, and optionally the +#: MDM's own device id beside it. Anything the phone or the enrolment link supplies, a serial +#: number for one, would let whoever holds a leaked enrolment link pick an identity. +SUBJECT = re.compile(r"CN=\$FLEET_VAR_HOST_END_USER_IDP_USERNAME(_LOCAL_PART)?(\s*,\s*OU=\$FLEET_VAR_HOST_UUID)?") + + +def _unsafe(policy: dict[str, Any], certificate: dict[str, Any] | None) -> str: + """Why this policy and certificate would hand out more than the deployment means to, or empty + + Shapes and a few safety rules only. Which apps are named is the template's business. + """ + if certificate is not None and not SUBJECT.fullmatch(str(certificate.get("subject", ""))): + return ( + "the certificate subject must be CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, optionally " + "followed by OU=$FLEET_VAR_HOST_UUID, so the callsign is the name the operator gave the phone" + ) + rules = policy.get("choosePrivateKeyRules", []) + if not isinstance(rules, list): + return "choosePrivateKeyRules must be a list" + for rule in rules: + names = rule.get("packageNames") if isinstance(rule, dict) else None + if not isinstance(names, list) or not names or not all(isinstance(n, str) and n for n in names): + return "every choosePrivateKeyRules entry must name its apps in packageNames, or any app may use the key" + if policy.get("privateKeySelectionEnabled") is True: + return "privateKeySelectionEnabled must not be true, or the user can hand the key to any app" + overrides = policy.get("advancedSecurityOverrides") or {} + untrusted = str(overrides.get("untrustedAppsPolicy", "")) if isinstance(overrides, dict) else "" + if untrusted.startswith("ALLOW_") or policy.get("installUnknownSourcesAllowed") is True: + return "the policy must not allow installs from unknown sources (untrustedAppsPolicy DISALLOW_INSTALL)" + return "" + + @dataclass(frozen=True) class App: """One application the deployment wants on its devices""" @@ -159,4 +192,8 @@ def load(path: Path, domain: str, key_alias: str) -> MdmTemplate: name=str(entry["name"]), subject=str(entry["subject"]), authority=str(entry["authority"]) ) + unsafe = _unsafe(policy, raw.get("certificate") or None) + if unsafe: + raise TemplateError(unsafe) + return MdmTemplate(apps=tuple(apps), policy=policy, link_app=link, certificate=certificate) diff --git a/tests/test_console.py b/tests/test_console.py index 36c2eaa..9834e1f 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -16,6 +16,9 @@ from .test_fleet import _Fleet, _host, _mdm +#: The certificate subject the template loader accepts: the callsign the operator gave the phone +NAMED = "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" + @pytest.fixture def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: @@ -29,7 +32,7 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: monkeypatch.setattr(config, "TOKEN_FILE", token) monkeypatch.setattr(config, "TEAM", "rmscep") stub = _Fleet() - stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$VAR", "certificate_authority_id": 3}] + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": NAMED, "certificate_authority_id": 3}] stub.profiles = [ { "name": "rmscep-policy", @@ -61,7 +64,7 @@ def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: { "apps": [{"package": "com.example.one"}], "policy": {"defaultPermissionPolicy": "GRANT"}, - "certificate": {"name": "{key_alias}", "subject": "CN=$VAR", "authority": "RMSCEP"}, + "certificate": {"name": "{key_alias}", "subject": NAMED, "authority": "RMSCEP"}, } ), encoding="utf-8", diff --git a/tests/test_template.py b/tests/test_template.py index 315fcb1..674ecd4 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -22,7 +22,9 @@ ], "link_app": {"title": "Deploy App", "url": "{mtls_url}/"}, "policy": { - "choosePrivateKeyRules": [{"urlPattern": "{mtls_url}", "privateKeyAlias": "{key_alias}"}], + "choosePrivateKeyRules": [ + {"urlPattern": "{mtls_url}", "privateKeyAlias": "{key_alias}", "packageNames": ["com.example.two"]} + ], "defaultPermissionPolicy": "GRANT", }, } @@ -65,6 +67,70 @@ def test_a_malformed_document_is_refused(tmp_path: Path, body: object, because: load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") +NAMED = "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" + + +def _with(policy: dict[str, object] | None = None, subject: str = NAMED) -> dict[str, object]: + """GOOD with a certificate, and with these policy keys changed""" + certificate = {"name": "{key_alias}", "subject": subject, "authority": "RMSCEP"} + return {**GOOD, "certificate": certificate, "policy": {**GOOD["policy"], **(policy or {})}} # type: ignore[dict-item] + + +@pytest.mark.parametrize( + "subject", + [ + NAMED, + "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME", + "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID", + "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME,OU=$FLEET_VAR_HOST_UUID", + ], +) +def test_the_callsign_is_the_name_the_operator_gave(tmp_path: Path, subject: str) -> None: + template = load(_write(tmp_path, _with(subject=subject)), domain="example.fi", key_alias="rmscep") + assert template.certificate is not None and template.certificate.subject == subject + + +@pytest.mark.parametrize( + ("body", "says"), + [ + (_with(subject="CN=$FLEET_VAR_HOST_HARDWARE_SERIAL"), "certificate subject must be CN="), + (_with(subject="CN=OTTER1"), "certificate subject must be CN="), + (_with(subject=NAMED + ", OU=$FLEET_VAR_HOST_HARDWARE_SERIAL"), "certificate subject must be CN="), + (_with(subject="OU=$FLEET_VAR_HOST_UUID, " + NAMED), "certificate subject must be CN="), + ( + _with({"choosePrivateKeyRules": [{"urlPattern": "x", "privateKeyAlias": "rmscep"}]}), + "must name its apps in packageNames", + ), + ( + _with({"choosePrivateKeyRules": [{"urlPattern": "x", "packageNames": []}]}), + "must name its apps in packageNames", + ), + (_with({"choosePrivateKeyRules": {"packageNames": ["a"]}}), "choosePrivateKeyRules must be a list"), + (_with({"privateKeySelectionEnabled": True}), "privateKeySelectionEnabled must not be true"), + ( + _with({"advancedSecurityOverrides": {"untrustedAppsPolicy": "ALLOW_INSTALL_DEVICE_WIDE"}}), + "must not allow installs from unknown sources", + ), + ( + _with({"advancedSecurityOverrides": {"untrustedAppsPolicy": "ALLOW_INSTALL_IN_PERSONAL_PROFILE_ONLY"}}), + "must not allow installs from unknown sources", + ), + (_with({"installUnknownSourcesAllowed": True}), "must not allow installs from unknown sources"), + ], +) +def test_a_template_that_hands_out_too_much_is_refused(tmp_path: Path, body: object, says: str) -> None: + """A named phone's key for named apps only, and no side door onto the phone""" + with pytest.raises(TemplateError, match=says): + load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep") + + +def test_safe_settings_are_accepted(tmp_path: Path) -> None: + body = _with( + {"privateKeySelectionEnabled": False, "advancedSecurityOverrides": {"untrustedAppsPolicy": "DISALLOW_INSTALL"}} + ) + assert load(_write(tmp_path, body), domain="example.fi", key_alias="rmscep").certificate is not None + + def test_a_missing_file_is_refused(tmp_path: Path) -> None: with pytest.raises(TemplateError): load(tmp_path / "nope.json", domain="example.fi", key_alias="rmscep") @@ -110,3 +176,8 @@ def test_the_example_is_a_template_we_accept() -> None: assert template.certificate is not None assert template.certificate.name == "rmscep", "the keystore alias comes from the setting" assert not [p for p in ("{domain}", "{mtls_url}", "{key_alias}") if p in json.dumps(template.policy)] + assert template.policy["advancedSecurityOverrides"]["untrustedAppsPolicy"] == "DISALLOW_INSTALL" + assert template.policy["privateKeySelectionEnabled"] is False + assert "defaultPermissionPolicy" not in template.policy, "nothing granted to every app" + rules = template.policy["choosePrivateKeyRules"] + assert [r["packageNames"] for r in rules] == [["com.android.chrome", "com.atakmap.app.civ", "im.vector.app"]] From caa8203bdb56623c7dec78bc1c3a125ad2a79743 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:22:14 +0200 Subject: [PATCH 027/104] fix: require https for the MDM address --- README.rst | 2 +- src/odmdm_connector/console.py | 7 +++++++ tests/test_console.py | 11 +++++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 4821113..d833c9e 100644 --- a/README.rst +++ b/README.rst @@ -82,7 +82,7 @@ Configuration All configuration is via environment variables: ``ODMDM_MDM_URL`` - Base URL of Fleet's API. + Base URL of Fleet's API. Only https: the token goes with every request. ``ODMDM_TOKEN_FILE`` A file holding the Fleet API token. Changing the certificate authority's challenge needs a diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index e2a7636..d85f0aa 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -3,6 +3,7 @@ import logging import re from pathlib import Path +from urllib.parse import urlparse import click from libadvian.logging import init_logging @@ -49,6 +50,12 @@ def _fleet(ctx: click.Context, url: str | None) -> FleetMdm | None: click.echo("Give --mdm-url or set ODMDM_MDM_URL", err=True) ctx.exit(1) return None + if urlparse(the_url).scheme != "https": + click.echo( + "The MDM address must start with https://, or the API token would cross the network readable", err=True + ) + ctx.exit(1) + return None if not config.TOKEN_FILE or not config.TOKEN_FILE.is_file(): click.echo("Set ODMDM_TOKEN_FILE to a file holding the Fleet API token", err=True) ctx.exit(1) diff --git a/tests/test_console.py b/tests/test_console.py index 9834e1f..add3063 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -568,3 +568,14 @@ def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str]) assert result.exit_code == 1 assert "no team named Typo" in result.output assert not _changes(fleet) + + +def test_the_mdm_address_must_be_https(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """The token goes with every request, so it must not cross the network readable""" + monkeypatch.setattr(config, "URL", "http://mdm.test") + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 1 + assert "must start with https://" in result.output + assert not fleet.calls From 643b2466ff42138d72a67fee1bad7d104d11cc6c Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:22:24 +0200 Subject: [PATCH 028/104] fix: number name --all from 1 or more --- README.rst | 6 +++--- src/odmdm_connector/console.py | 6 +++++- tests/test_console.py | 9 +++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index d833c9e..06ae08b 100644 --- a/README.rst +++ b/README.rst @@ -69,9 +69,9 @@ Commands odmdm-connector resend [HOST_ID ...] # ask again; without ids, every named phone that failed ``name --all`` numbers in enrolment order from one above the highest ``OTTER`` in the team, or -from ``--start N``. It sees only this team's phones, and Deploy App never gives a callsign out -twice: where callsigns were used by phones no longer in the team, give ``--start`` above the -highest ever used. ``name`` changes nothing at all if a callsign is malformed, given twice or +from ``--start N``, 1 or more. It sees only this team's phones, and Deploy App never gives a +callsign out twice: where callsigns were used by phones no longer in the team, give ``--start`` +above the highest ever used. ``name`` changes nothing at all if a callsign is malformed, given twice or already another phone's, or if a host is not in the team. A phone that already has its certificate under the name is left alone. Renaming a phone that has its certificate says which old callsign to revoke. diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index d85f0aa..6e165b4 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -272,7 +272,11 @@ def _policy_again(fleet: FleetMdm, team_id: int, found: dict[int, Phone]) -> Non help="Name every phone that has no name PREFIX, in enrolment order", ) @click.option( - "--start", type=int, metavar="N", default=None, help="The first n for --all (default: one above the highest in use)" + "--start", + type=click.IntRange(min=1), + metavar="N", + default=None, + help="The first n for --all (default: one above the highest in use)", ) @click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") @click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") diff --git a/tests/test_console.py b/tests/test_console.py index add3063..b53c6be 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -579,3 +579,12 @@ def test_the_mdm_address_must_be_https(fleet: _Fleet, monkeypatch: pytest.Monkey assert result.exit_code == 1 assert "must start with https://" in result.output assert not fleet.calls + + +@pytest.mark.parametrize("start", ["0", "-3"]) +def test_name_all_starts_from_one_or_more(fleet: _Fleet, start: str) -> None: + """Callsigns are numbered from 1""" + result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER", "--start", start]) + + assert result.exit_code == 2 + assert not fleet.calls From 9b0eb2d3f7d70bfab9396384aa63766879cf8621 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:22:43 +0200 Subject: [PATCH 029/104] fix: read every page of a team's hosts --- src/odmdm_connector/fleet.py | 15 +++++++++++++-- tests/test_console.py | 13 +++++++++++++ tests/test_fleet.py | 5 ++++- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index 36a81b4..b5f70f4 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -28,6 +28,9 @@ class FleetError(RuntimeError): """Fleet refused, or answered something we cannot use""" +#: Fleet's hosts listing answers in pages; Fleet's page numbers start from 0 +HOSTS_PER_PAGE = 500 + #: Google refuses a managed web app title of 30 characters or more MAX_WEB_APP_TITLE = 29 @@ -471,8 +474,16 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str) # --- naming --------------------------------------------------------------- def _hosts(self, team: int) -> list[dict[str, Any]]: - """The devices in a team""" - return self._call("GET", f"/api/latest/fleet/hosts?team_id={team}&per_page=500").get("hosts") or [] + """The devices in a team, every page of them""" + found: list[dict[str, Any]] = [] + page = 0 + while True: + query = urlencode({"team_id": team, "page": page, "per_page": HOSTS_PER_PAGE}) + batch = self._call("GET", f"/api/latest/fleet/hosts?{query}").get("hosts") or [] + found.extend(batch) + if len(batch) < HOSTS_PER_PAGE: + return found + page += 1 def phones(self, team: int, certificate: str) -> list[Phone]: """The team's devices in enrolment order, each with its name and its certificate row diff --git a/tests/test_console.py b/tests/test_console.py index b53c6be..1ca5f97 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -12,6 +12,7 @@ from click.testing import CliRunner from odmdm_connector import config +from odmdm_connector import fleet as fleet_module from odmdm_connector.console import cli_group from .test_fleet import _Fleet, _host, _mdm @@ -588,3 +589,15 @@ def test_name_all_starts_from_one_or_more(fleet: _Fleet, start: str) -> None: assert result.exit_code == 2 assert not fleet.calls + + +@pytest.mark.parametrize("count", [4, 5]) +def test_phones_reads_every_page_of_hosts(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, count: int) -> None: + """A team bigger than one page is listed whole, also when the last page is full""" + monkeypatch.setattr(fleet_module, "HOSTS_PER_PAGE", 2) + fleet.hosts = [_host(31 + n, "verified", f"OTTER{n + 1}") for n in range(count)] + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 0, result.output + assert [line.split()[0] for line in result.output.splitlines()] == [str(31 + n) for n in range(count)] diff --git a/tests/test_fleet.py b/tests/test_fleet.py index 955402d..d6db636 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -45,7 +45,10 @@ def handler(self, request: httpx.Request) -> httpx.Response: path = request.url.path self.calls.append((request.method, path)) if path.endswith("/hosts") and request.method == "GET": - return httpx.Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts]}) + # Fleet answers one page at a time, the first being page 0 + per_page = int(request.url.params.get("per_page", "100")) + first = int(request.url.params.get("page", "0")) * per_page + return httpx.Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts[first : first + per_page]]}) if path.endswith("/device_mapping") and request.method == "PUT": # The name shows in the host detail as its IdP user, which is what the certificate reads found = next(h for h in self.hosts if h["id"] == int(path.split("/")[-2])) From 6e93cbbec15835ca8e0a0fda33659f9c855ff5f2 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:23:09 +0200 Subject: [PATCH 030/104] fix: say which phones were named when a batch stops --- src/odmdm_connector/console.py | 10 +++++++--- src/odmdm_connector/fleet.py | 12 +++++------- tests/test_console.py | 22 ++++++++++++++++++++++ 3 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 6e165b4..04591e7 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -308,6 +308,7 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments fleet = _fleet(ctx, mdm_url) if not fleet: return + named: list[str] = [] try: team_id = fleet.team_id(team or config.TEAM) found = {phone.id: phone for phone in fleet.phones(team_id, config.KEY_ALIAS)} @@ -323,15 +324,16 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx.exit(0) return template = fleet.certificate_template(team_id, config.KEY_ALIAS) - named = False for host, callsign in wanted: old = found[host] # Asked again under the name it holds, it is refused as taken: a working phone then shows as refused if old.status == "verified" and old.callsign.lower() == callsign.lower(): click.echo(f"Host {host} is already {old.callsign}") continue - fleet.name_host(host, callsign, template if old.status else None) - named = True + fleet.name_host(host, callsign) + named.append(f"{host}={callsign}") + if old.status: + fleet.resend(host, template) line = f"Host {host} is {callsign}" if not old.status: line += ". Fleet has no certificate request for it, so nothing was sent" @@ -342,6 +344,8 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments _policy_again(fleet, team_id, found) except FleetError as exc: click.echo(f"Fleet refused: {exc}", err=True) + if named: + click.echo(f"Already named before it stopped: {' '.join(named)}. phones shows where each is", err=True) ctx.exit(1) return ctx.exit(0) diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index b5f70f4..b5f9bec 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -519,17 +519,15 @@ def certificate_template(self, team: int, name: str) -> int: return int(template["id"]) raise FleetError(f"team {team} has no certificate template named {name}: run apply first") - def name_host(self, host: int, callsign: str, template: int | None) -> None: - """Give the host its callsign, and have Fleet ask for its certificate again under it + def name_host(self, host: int, callsign: str) -> None: + """Give the host its callsign A phone enrols before anybody can name it, so its first request has already failed for - want of a name, and naming it does not send that request again by itself. A host with no - request yet gets no template: Fleet has none to send again (404, read in Fleet 4.90.1's - source), and fills the name in when it makes one. + want of a name, and naming it does not send that request again by itself: follow with + resend. Not for a host with no request yet: Fleet has none to send again (404, read in + Fleet 4.90.1's source), and fills the name in when it makes one. """ self._call("PUT", f"/api/latest/fleet/hosts/{host}/device_mapping", {"email": callsign, "source": "idp"}) - if template: - self.resend(host, template) def resend(self, host: int, template: int) -> None: """Have Fleet send the host its certificate request again, for one more attempt diff --git a/tests/test_console.py b/tests/test_console.py index 1ca5f97..2db33e0 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -601,3 +601,25 @@ def test_phones_reads_every_page_of_hosts(fleet: _Fleet, monkeypatch: pytest.Mon assert result.exit_code == 0, result.output assert [line.split()[0] for line in result.output.splitlines()] == [str(31 + n) for n in range(count)] + + +def test_a_batch_stopped_half_way_says_which_phones_are_named(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """So the operator names only the rest, rather than guessing""" + answer = fleet.handler + + def refusing(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/hosts/32/certificates/81/resend"): + return httpx.Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] + + result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER"]) + + assert result.exit_code == 1 + assert result.stdout.splitlines() == ["Host 31 is OTTER1"] + assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.output + assert "Already named before it stopped: 31=OTTER1 32=OTTER2. phones shows where each is" in result.output + assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: ""} From c2fc41190e7d7fa449c8dca122ad30b143f531db Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:10:39 +0200 Subject: [PATCH 031/104] feat: take Deploy App's ODMDM1 settings line in challenge and apply --- README.rst | 30 ++++++++++-- src/odmdm_connector/console.py | 52 ++++++++++++++++----- src/odmdm_connector/settings.py | 63 +++++++++++++++++++++++++ tests/data/settings-line-v1.txt | 1 + tests/test_console.py | 83 ++++++++++++++++++++++++++++++++- tests/test_settings.py | 77 ++++++++++++++++++++++++++++++ 6 files changed, 290 insertions(+), 16 deletions(-) create mode 100644 src/odmdm_connector/settings.py create mode 100644 tests/data/settings-line-v1.txt create mode 100644 tests/test_settings.py diff --git a/README.rst b/README.rst index 06ae08b..9a97553 100644 --- a/README.rst +++ b/README.rst @@ -24,8 +24,8 @@ them, and each gets its certificate once it has a name. odmdm-connector apply -2. Open enrolment in Deploy App (**User management → MDM**) and give Fleet the new challenge. It - asks for it, and changes nothing else:: +2. Open enrolment in Deploy App (**User management → MDM**), copy its settings line or its + challenge, and give Fleet the new challenge. It asks for it, and changes nothing else:: odmdm-connector challenge @@ -100,8 +100,8 @@ All configuration is via environment variables: The deployment's DNS name. ``ODMDM_CHALLENGE`` - The challenge on Deploy App's MDM page, for ``challenge`` and a first ``apply``. New for every - enrolment window. + The settings line or the bare challenge from Deploy App's MDM page, for ``challenge`` and a + first ``apply``. New for every enrolment window. ``ODMDM_KEY_ALIAS`` The certificate template's name, which becomes the Android keystore alias. Default ``rmscep``, @@ -131,6 +131,28 @@ The tool also refuses a policy that lets an app use the key without being named ``packageNames``, lets the user pick a key for any app (``privateKeySelectionEnabled``), or allows installs from unknown sources (``untrustedAppsPolicy`` other than ``DISALLOW_INSTALL``). +The settings line +----------------- + +Deploy App's MDM page copies one line for the connector. It is the same for every MDM, and it +carries no list of names: phones are named in the MDM. Version 1 is exactly four fields +separated by whitespace:: + + ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z + +1. The mark ``ODMDM1``. +2. The SCEP URL. It must be https. +3. The challenge: 32 lowercase hex characters. It is a secret, and the tool never prints or logs it. +4. When the enrolment window closes, in UTC, as ``YYYY-MM-DDTHH:MM:SSZ``. + +Whitespace and line breaks before and after the line are ignored. A line with another mark or +another number of fields, a URL that is not https, a malformed challenge or time, or a window that +has already closed is refused. A value with whitespace inside it is read as a line, never as a +bare challenge, so a damaged paste is refused instead of being sent to Fleet. ``challenge`` takes +the line at its prompt, from ``--challenge`` or from ``ODMDM_CHALLENGE``, refuses one whose SCEP +URL is not on ``ODMDM_DOMAIN``, and says until when the window is open. The line above is the +shared test vector, in ``tests/data/settings-line-v1.txt``. + The order that works -------------------- diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 04591e7..7841ad0 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -1,5 +1,6 @@ """CLI entrypoints for odmdm-connector""" +import datetime import logging import re from pathlib import Path @@ -10,7 +11,7 @@ from odmdm_connector import __version__ -from . import config, template +from . import config, settings, template from .fleet import FleetError, FleetMdm, Phone LOGGER = logging.getLogger(__name__) @@ -79,6 +80,32 @@ def _template(ctx: click.Context, path: str | None, domain: str | None) -> templ return None +def _now() -> datetime.datetime: + return datetime.datetime.now(datetime.UTC) + + +def _window(ctx: click.Context, value: str, domain: str) -> tuple[str, str, str] | None: + """The SCEP URL, the challenge and until when the window is open, from a challenge or a settings line + + None after saying why not. A bare challenge says nothing of the window. The challenge is never + in a message. + """ + if not settings.is_line(value): + return f"https://{domain}/scep", value.strip(), "" + try: + line = settings.parse(value, _now()) + except settings.SettingsError as exc: + click.echo(str(exc), err=True) + ctx.exit(1) + return None + host = urlparse(line.scep_url).hostname or "" + if host != domain.lower(): + click.echo(f"The settings line is for {host}, not {domain}: copy it from this deployment's MDM page", err=True) + ctx.exit(1) + return None + return line.scep_url, line.challenge, f"{line.closes:%Y-%m-%d %H:%M} UTC" + + @cli_group.command(name="apply") @click.pass_context @click.option("--template", "path", default=None, help="What to install (default: ODMDM_TEMPLATE)") @@ -120,16 +147,15 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx.exit(0) return + window = _window(ctx, config.CHALLENGE, domain or config.DOMAIN) + if not window: + return fleet = _fleet(ctx, mdm_url) if not fleet: return try: result = fleet.apply( - team or config.TEAM, - wanted, - force_policy=force_policy, - scep_url=f"https://{domain or config.DOMAIN}/scep", - challenge=config.CHALLENGE, + team or config.TEAM, wanted, force_policy=force_policy, scep_url=window[0], challenge=window[1] ) except FleetError as exc: click.echo(f"Fleet refused: {exc}", err=True) @@ -145,9 +171,9 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments "--challenge", "value", envvar="ODMDM_CHALLENGE", - prompt="Challenge from Deploy App's MDM page", + prompt="Settings line or challenge from Deploy App's MDM page", hide_input=True, - help="The new window's challenge (default: ODMDM_CHALLENGE, else asked for)", + help="The new window's settings line or challenge (default: ODMDM_CHALLENGE, else asked for)", ) @click.option("--template", "path", default=None, help="What to install (default: ODMDM_TEMPLATE)") @click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") @@ -159,7 +185,7 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen Every opening makes a new one. Only the certificate authority changes, so phones still installing apps are left alone. Asked for rather than taken as an argument, so it stays out of - shell history. + shell history. Given the whole settings line, its SCEP URL must be on this deployment's domain. """ wanted = _template(ctx, path, domain) if not wanted: @@ -168,16 +194,20 @@ def challenge( # pylint: disable=too-many-arguments,too-many-positional-argumen click.echo("The template states no certificate, so there is no authority to give it to", err=True) ctx.exit(1) return + window = _window(ctx, value, domain or config.DOMAIN) + if not window: + return fleet = _fleet(ctx, mdm_url) if not fleet: return try: - fleet.ensure_authority(wanted.certificate.authority, f"https://{domain or config.DOMAIN}/scep", value) + fleet.ensure_authority(wanted.certificate.authority, window[0], window[1]) except FleetError as exc: click.echo(f"Fleet refused: {exc}", err=True) ctx.exit(1) return - click.echo(f"{wanted.certificate.authority} has the new challenge") + until = f". The enrolment window is open until {window[2]}" if window[2] else "" + click.echo(f"{wanted.certificate.authority} has the new challenge{until}") ctx.exit(0) diff --git a/src/odmdm_connector/settings.py b/src/odmdm_connector/settings.py new file mode 100644 index 0000000..3002eee --- /dev/null +++ b/src/odmdm_connector/settings.py @@ -0,0 +1,63 @@ +"""The settings line Deploy App's MDM page copies for the connector + +Version 1 is four fields separated by whitespace:: + + ODMDM1 + +It is the same for every MDM and carries no names. The challenge is a secret: nothing here puts it +in a message. +""" + +import datetime +import re +from dataclasses import dataclass, field +from urllib.parse import urlsplit + +MARK = "ODMDM1" +CHALLENGE = re.compile(r"[0-9a-f]{32}") +CLOSES = "%Y-%m-%dT%H:%M:%SZ" + + +class SettingsError(ValueError): + """The line is not one the connector can use""" + + +@dataclass(frozen=True) +class Settings: + """What one enrolment window gives the MDM""" + + scep_url: str + challenge: str = field(repr=False) + closes: datetime.datetime + + +def is_line(value: str) -> bool: + """Whether the value is meant as a settings line rather than a bare challenge + + A challenge is one word, so a value with whitespace inside it, or with the mark in any case, + is meant as a line. + """ + return len(value.split()) > 1 or value.strip().upper().startswith("ODMDM") + + +def parse(line: str, now: datetime.datetime) -> Settings: + """The line's values, or SettingsError saying why not + + now is the current time with its time zone, given by the caller. + """ + fields = line.split() + if len(fields) != 4 or fields[0] != MARK: + raise SettingsError(f"This is not a settings line: it has four parts and starts with {MARK}.") + _, url, challenge, closes = fields + parts = urlsplit(url) + if parts.scheme != "https" or not parts.hostname: + raise SettingsError("The SCEP URL in the settings line must start with https://.") + if not CHALLENGE.fullmatch(challenge): + raise SettingsError("The challenge in the settings line must be 32 lowercase hex characters.") + try: + when = datetime.datetime.strptime(closes, CLOSES).replace(tzinfo=datetime.UTC) + except ValueError as exc: + raise SettingsError(f"The closing time {closes!r} is not YYYY-MM-DDTHH:MM:SSZ.") from exc + if when <= now: + raise SettingsError(f"The enrolment window closed at {closes}: open a new one in Deploy App.") + return Settings(scep_url=url, challenge=challenge, closes=when) diff --git a/tests/data/settings-line-v1.txt b/tests/data/settings-line-v1.txt new file mode 100644 index 0000000..88a888d --- /dev/null +++ b/tests/data/settings-line-v1.txt @@ -0,0 +1 @@ +ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z diff --git a/tests/test_console.py b/tests/test_console.py index 2db33e0..6f61e17 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -4,6 +4,7 @@ to say why, rather than end in a traceback. """ +import datetime import json from pathlib import Path @@ -11,7 +12,7 @@ import pytest from click.testing import CliRunner -from odmdm_connector import config +from odmdm_connector import config, console from odmdm_connector import fleet as fleet_module from odmdm_connector.console import cli_group @@ -623,3 +624,83 @@ def refusing(request: httpx.Request) -> httpx.Response: assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.output assert "Already named before it stopped: 31=OTTER1 32=OTTER2. phones shows where each is" in result.output assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: ""} + + +LINE = (Path(__file__).parent / "data" / "settings-line-v1.txt").read_text(encoding="utf-8").strip() +SECRET = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret + + +@pytest.fixture +def window(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: + """The stub Fleet, a template, the vector's domain, and a clock before its window closes""" + _template(tmp_path, monkeypatch) + monkeypatch.setattr(config, "DOMAIN", "unit.example.fi") + monkeypatch.setattr(console, "_now", lambda: datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC)) + return fleet + + +@pytest.mark.parametrize( + ("arguments", "typed", "env"), + [ + ([], LINE + "\n", {}), + (["--challenge", LINE], None, {}), + ([], None, {"ODMDM_CHALLENGE": LINE}), + ], +) +def test_challenge_takes_the_settings_line( + window: _Fleet, caplog: pytest.LogCaptureFixture, arguments: list[str], typed: str | None, env: dict[str, str] +) -> None: + """Typed at the hidden prompt, given as an option or from the environment""" + result = CliRunner().invoke(cli_group, ["-vv", "challenge", *arguments], input=typed, env=env) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines()[-1] == ( + "RMSCEP has the new challenge. The enrolment window is open until 2026-11-21 14:00 UTC" + ) + assert window.authorities[0]["challenge"] == SECRET + assert window.authorities[0]["url"] == "https://unit.example.fi/scep" + assert SECRET not in result.output + assert SECRET not in caplog.text + + +@pytest.mark.parametrize( + ("line", "says"), + [ + (LINE.replace("unit.example.fi", "other.example.fi"), "is for other.example.fi, not unit.example.fi"), + (LINE.replace("https://", "http://"), "must start with https://"), + (LINE.replace("2026-11-21T14", "2026-11-21T11"), "closed at 2026-11-21T11:00:00Z"), + (LINE.replace("ODMDM1", "ODMDM2"), "not a settings line"), + (LINE.replace("ODMDM1", "odmdm1"), "not a settings line"), + (LINE.split(None, 1)[1], "not a settings line"), + ('"' + LINE + '"', "not a settings line"), + ], +) +def test_challenge_refuses_a_line_it_cannot_use(window: _Fleet, line: str, says: str) -> None: + """Before Fleet is asked anything, and without the challenge in the message""" + result = CliRunner().invoke(cli_group, ["challenge"], input=line + "\n") + + assert result.exit_code == 1 + assert says in result.output + assert SECRET not in result.output + assert not window.calls + + +def test_apply_takes_the_settings_line_from_the_environment(window: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """ODMDM_CHALLENGE may hold the line; apply must not send the whole line as the challenge""" + monkeypatch.setattr(config, "CHALLENGE", LINE) + + result = CliRunner().invoke(cli_group, ["apply"]) + + assert result.exit_code == 0, result.output + assert window.authorities[0]["challenge"] == SECRET + assert SECRET not in result.output + + +def test_apply_refuses_a_line_for_another_deployment(window: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(config, "CHALLENGE", LINE.replace("unit.example.fi", "other.example.fi")) + + result = CliRunner().invoke(cli_group, ["apply"]) + + assert result.exit_code == 1 + assert "is for other.example.fi" in result.output + assert not window.calls diff --git a/tests/test_settings.py b/tests/test_settings.py new file mode 100644 index 0000000..f6f7583 --- /dev/null +++ b/tests/test_settings.py @@ -0,0 +1,77 @@ +"""The settings line Deploy App's MDM page copies, version 1 + +The same line for every MDM, so the vector in tests/data is shared with Deploy App. +""" + +import datetime +from pathlib import Path + +import pytest + +from odmdm_connector.settings import Settings, SettingsError, is_line, parse + +VECTOR = (Path(__file__).parent / "data" / "settings-line-v1.txt").read_text(encoding="utf-8") +CHALLENGE = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret +BEFORE = datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC) +CLOSES = datetime.datetime(2026, 11, 21, 14, 0, tzinfo=datetime.UTC) + + +def test_the_shared_vector() -> None: + assert VECTOR.split() == ["ODMDM1", "https://unit.example.fi/scep", CHALLENGE, "2026-11-21T14:00:00Z"] + assert parse(VECTOR, BEFORE) == Settings("https://unit.example.fi/scep", CHALLENGE, CLOSES) + + +@pytest.mark.parametrize("around", [" {} ", "\n{}\r\n", "\t{}\n\n"]) +def test_whitespace_and_line_breaks_around_it_are_ignored(around: str) -> None: + assert parse(around.format(VECTOR.strip()), BEFORE).challenge == CHALLENGE + + +def test_the_challenge_never_shows_in_its_repr() -> None: + assert CHALLENGE not in repr(parse(VECTOR, BEFORE)) + + +@pytest.mark.parametrize( + ("line", "says"), + [ + ("", "not a settings line"), + ("ODMDM2 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "not a settings line"), + ("odmdm1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE, "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z OTTER1", "not a settings line"), + ("ODMDM1 http://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "must start with https://"), + ("ODMDM1 https:///scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "must start with https://"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE.upper() + " 2026-11-21T14:00:00Z", "32 lowercase hex"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE[:-1] + " 2026-11-21T14:00:00Z", "32 lowercase hex"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE[:-1] + "g 2026-11-21T14:00:00Z", "32 lowercase hex"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00", "is not YYYY-MM-DDTHH:MM:SSZ"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21 14:00:00Z", "not a settings line"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-31T14:00:00Z", "is not YYYY-MM-DDTHH:MM:SSZ"), + ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00+00:00", "is not YYYY-MM-DD"), + ], +) +def test_a_line_that_cannot_be_used_says_why(line: str, says: str) -> None: + with pytest.raises(SettingsError, match=says) as raised: + parse(line, BEFORE) + assert CHALLENGE[:-1] not in str(raised.value), "the challenge is never in a message" + + +@pytest.mark.parametrize("now", [CLOSES, CLOSES + datetime.timedelta(seconds=1)]) +def test_a_closed_window_is_refused(now: datetime.datetime) -> None: + with pytest.raises(SettingsError, match="closed at 2026-11-21T14:00:00Z: open a new one in Deploy App"): + parse(VECTOR, now) + + +@pytest.mark.parametrize( + ("value", "line"), + [ + (VECTOR, True), + (" ODMDM2 x", True), + ("odmdm1 x", True), + (VECTOR.split(None, 1)[1], True), + (CHALLENGE, False), + (" " + CHALLENGE + "\n", False), + ("", False), + ], +) +def test_a_line_is_told_from_a_bare_challenge(value: str, line: bool) -> None: + assert is_line(value) is line From 932f7805b87c446ad88bf814e2f67c99dde92c78 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:23:40 +0200 Subject: [PATCH 032/104] ci: release only from main --- .github/workflows/push_to_main.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/push_to_main.yml b/.github/workflows/push_to_main.yml index 6f0d3bf..5d72964 100644 --- a/.github/workflows/push_to_main.yml +++ b/.github/workflows/push_to_main.yml @@ -23,6 +23,7 @@ jobs: release: name: Tag the current version and release it + if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest permissions: contents: write From 12e13b50daede87e7e6fa73a21d1a2683512dbbb Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:23:50 +0200 Subject: [PATCH 033/104] docs: say how to install with uv --- README.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.rst b/README.rst index 9a97553..3566490 100644 --- a/README.rst +++ b/README.rst @@ -14,6 +14,17 @@ Run it from an operator's machine, never inside the deployment: it holds a Fleet something that can reach every device a unit owns has no business running next to an internet facing service. +Install +------- + +Install it with uv (https://docs.astral.sh/uv/getting-started/installation/); git must be +installed too:: + + uv tool install git+https://github.com/pvarki/python-odmdm-fleet + odmdm-connector --help + +From a checkout, ``uv tool install .`` does the same. + Enrolling phones ---------------- From 9394b237a6be44567a469450e9fbe3727f3b9b5d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:31:01 +0200 Subject: [PATCH 034/104] feat: state the MDM contract --- src/odmdm_connector/mdm.py | 148 ++++++++++++++++++++++++++++++++ src/odmdm_connector/settings.py | 7 +- tests/test_mdm.py | 22 +++++ 3 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 src/odmdm_connector/mdm.py create mode 100644 tests/test_mdm.py diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py new file mode 100644 index 0000000..fbc2088 --- /dev/null +++ b/src/odmdm_connector/mdm.py @@ -0,0 +1,148 @@ +"""What the connector needs an MDM to be able to do: the one contract every MDM plugin implements + +Standard library only, so a plugin depends on nothing but this package. A plugin is a class that +satisfies Mdm, published under the entry point group ``odmdm_connector.mdm``. The connector checks +the class's API_VERSION before it uses it. + +Every sentence a plugin hands back, a Step's message, a line from name or ask_again, an MdmError, +is shown to the operator as it is. The SCEP challenge is never in one. +""" + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass +from enum import Enum +from typing import ClassVar, Protocol + +from .settings import Settings + +API_VERSION = 1 + +#: The capabilities an MDM may lack, as named in Mdm.missing +SETUP = "setup" +SET_CHALLENGE = "set_challenge" +ASK_AGAIN = "ask_again" +CAPABILITIES = (SETUP, SET_CHALLENGE, ASK_AGAIN) + + +class State(Enum): + """Where a phone's certificate is, its value being the sentence shown to the operator""" + + NO_REQUEST = "no certificate requested" + NEEDS_NAME = "waiting for a name" + NOT_ASKED = "named, but its certificate was not asked for again" + WAITING = "requested, waiting for the phone" + READY = "has its certificate" + REFUSED = "refused by Deploy App" + UNREACHABLE = "could not reach Deploy App" + #: A failure that is neither a refusal nor Deploy App out of reach + FAILED = "failed" + + +@dataclass(frozen=True) +class Phone: + """A phone in the MDM's group for one Deploy App""" + + #: The MDM's own id for it, opaque to the connector + id: str + #: Empty while nobody has named it + callsign: str + model: str + #: When it joined, as an ISO time + joined: str + state: State + #: The plugin's own extra words for the operator, shown after the state; may be empty + detail: str = "" + + +@dataclass(frozen=True) +class Field: + """A setup value a plugin needs, such as its MDM's address + + A secret is never taken from an option or a plain environment variable, only from a file. + """ + + key: str + label: str + secret: bool = False + default: str = "" + help: str = "" + + +@dataclass(frozen=True) +class Step: + """One step of setup, as it is reported""" + + label: str + done: bool + message: str = "" + + +class MdmError(Exception): + """The one error a plugin raises, its text a sentence for the operator + + named holds the phones a batch had already named when it stopped, by id, so the operator names + only the rest. lines holds the lines already due to the operator when it stopped, such as which + old callsign to revoke, shown before the error. + """ + + def __init__(self, message: str, named: Mapping[str, str] | None = None, lines: Sequence[str] = ()) -> None: + super().__init__(message) + self.named: dict[str, str] = dict(named or {}) + self.lines: list[str] = list(lines) + + +class Mdm(Protocol): + """One MDM, configured for one Deploy App's group of phones""" + + API_VERSION: ClassVar[int] + #: The MDM's name as an operator knows it + title: ClassVar[str] + fields: ClassVar[tuple[Field, ...]] + #: For each capability in CAPABILITIES this MDM lacks, what to tell the operator instead + missing: ClassVar[Mapping[str, str]] + + def __init__(self, values: Mapping[str, str]) -> None: + """values: the fields' values by key""" + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + """Set the MDM up for this Deploy App, first time or again + + Idempotent. Never replaces a certificate template on a group that has phones. dry_run + checks what would be stated and stops before the MDM is changed. + """ + + def set_challenge(self, window: Settings) -> None: + """Give the MDM the challenge of the enrolment window just opened, and change nothing else""" + + def phones(self) -> list[Phone]: + """The group's phones, oldest first""" + + def name(self, names: Mapping[str, str]) -> list[str]: + """Give phones their callsigns, by id, and do what the MDM needs for their certificates + + Answers the lines to show the operator. Raises MdmError for an id not in the group, and with + named filled in when it stopped half-way. + """ + + def ask_again(self, ids: Sequence[str]) -> list[str]: + """Have the phones ask for their certificates again + + No ids means every named phone whose state is NOT_ASKED, REFUSED, UNREACHABLE or FAILED. + Answers the lines to show the operator, none when nothing was asked. + """ + + +__all__ = [ + "API_VERSION", + "ASK_AGAIN", + "CAPABILITIES", + "SETUP", + "SET_CHALLENGE", + "Field", + "Mdm", + "MdmError", + "Phone", + "Settings", + "State", + "Step", +] diff --git a/src/odmdm_connector/settings.py b/src/odmdm_connector/settings.py index 3002eee..b0265d2 100644 --- a/src/odmdm_connector/settings.py +++ b/src/odmdm_connector/settings.py @@ -24,11 +24,14 @@ class SettingsError(ValueError): @dataclass(frozen=True) class Settings: - """What one enrolment window gives the MDM""" + """What one enrolment window gives the MDM + + closes is None for a bare challenge typed without its line, which says nothing of the window. + """ scep_url: str challenge: str = field(repr=False) - closes: datetime.datetime + closes: datetime.datetime | None = None def is_line(value: str) -> bool: diff --git a/tests/test_mdm.py b/tests/test_mdm.py new file mode 100644 index 0000000..7db67f0 --- /dev/null +++ b/tests/test_mdm.py @@ -0,0 +1,22 @@ +"""The MDM contract""" + +from odmdm_connector import mdm + + +def test_an_error_carries_the_phones_named_before_it() -> None: + """So the operator names only the rest""" + named = {"31": "OTTER1"} + + error = mdm.MdmError("stopped", named) + named["32"] = "OTTER2" + + assert str(error) == "stopped" + assert error.named == {"31": "OTTER1"} + assert not mdm.MdmError("stopped").named + + +def test_every_state_is_a_sentence_and_every_capability_is_named() -> None: + """The state's value is what the operator reads""" + assert all(state.value and state.value == state.value.strip() for state in mdm.State) + assert set(mdm.CAPABILITIES) == {"setup", "set_challenge", "ask_again"} + assert mdm.API_VERSION == 1 From 9695d3a28c7589c183a2692583c9688631a3e800 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:31:25 +0200 Subject: [PATCH 035/104] refactor: state the naming rules apart from any MDM --- src/odmdm_connector/core.py | 58 +++++++++++++++++++++++++++++++++++++ tests/test_core.py | 50 ++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 src/odmdm_connector/core.py create mode 100644 tests/test_core.py diff --git a/src/odmdm_connector/core.py b/src/odmdm_connector/core.py new file mode 100644 index 0000000..7e02cdd --- /dev/null +++ b/src/odmdm_connector/core.py @@ -0,0 +1,58 @@ +"""The rules for naming phones, the same whatever the MDM""" + +import re +from collections.abc import Sequence + +from .mdm import Phone + +#: The deployment's rule for a device callsign, checked here only so a typo is refused now rather +#: than as a failed certificate twenty minutes later. The deployment still decides. +CALLSIGN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{1,30}[A-Za-z0-9]") + + +def pairs(values: Sequence[str]) -> list[tuple[str, str]]: + """ID=CALLSIGN arguments, as ids and callsigns; ValueError saying which one is not""" + found = [] + for value in values: + phone, _, callsign = value.partition("=") + if not phone or not callsign: + raise ValueError(f"{value!r} is not ID=CALLSIGN, the id being what phones prints") + found.append((phone, callsign)) + return found + + +def numbered(phones: Sequence[Phone], prefix: str, start: int | None) -> list[tuple[str, str]]: + """PREFIX for every phone without a name, in the order given + + Numbered from start, else from one above the highest PREFIX already in use. + """ + if start is None: + used = (re.fullmatch(re.escape(prefix) + r"(\d+)", phone.callsign, re.IGNORECASE) for phone in phones) + start = max((int(match.group(1)) for match in used if match), default=0) + 1 + waiting = [phone.id for phone in phones if not phone.callsign] + return [(phone, f"{prefix}{start + n}") for n, phone in enumerate(waiting)] + + +def refusal(phones: Sequence[Phone], wanted: Sequence[tuple[str, str]]) -> str: + """Why these names cannot all be given, or empty when they can + + Callsigns are compared without case, as the deployment compares them. + """ + found = {phone.id: phone for phone in phones} + ids: set[str] = set() + callsigns: set[str] = set() + for phone, callsign in wanted: + if phone not in found: + return f"host {phone} is not in the team" + if phone in ids: + return f"host {phone} is named twice" + if not CALLSIGN.fullmatch(callsign): + return f"{callsign}: a callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen" + if callsign.lower() in callsigns: + return f"{callsign} is given twice" + owner = next((p.id for p in phones if p.id != phone and p.callsign.lower() == callsign.lower()), "") + if owner: + return f"{callsign} already belongs to host {owner}" + ids.add(phone) + callsigns.add(callsign.lower()) + return "" diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000..c664342 --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,50 @@ +"""The naming rules, without an MDM""" + +import pytest + +from odmdm_connector import core +from odmdm_connector.mdm import Phone, State + + +def _phone(phone: str, callsign: str = "") -> Phone: + return Phone(phone, callsign, "a phone", "2026-11-01T08:00:00Z", State.READY if callsign else State.NEEDS_NAME) + + +def test_ids_are_whatever_the_mdm_calls_its_phones() -> None: + """Opaque strings, split at the first =""" + assert core.pairs(["31=OTTER4", "a-b=OTTER5"]) == [("31", "OTTER4"), ("a-b", "OTTER5")] + + +@pytest.mark.parametrize("value", ["OTTER4", "=OTTER4", "31="]) +def test_a_pair_without_both_halves_is_refused(value: str) -> None: + with pytest.raises(ValueError, match="is not ID=CALLSIGN"): + core.pairs([value]) + + +def test_numbering_goes_on_from_the_highest_in_use() -> None: + """In the order the phones are given, skipping the named ones""" + phones = [_phone("a", "otter7"), _phone("b"), _phone("c", "KETTU9"), _phone("d")] + + assert core.numbered(phones, "OTTER", None) == [("b", "OTTER8"), ("d", "OTTER9")] + assert core.numbered(phones, "OTTER", 20) == [("b", "OTTER20"), ("d", "OTTER21")] + + +@pytest.mark.parametrize( + ("wanted", "says"), + [ + ([("a", "OTTER4")], ""), + ([("x", "OTTER4")], "host x is not in the team"), + ([("a", "OTTER4"), ("a", "OTTER5")], "host a is named twice"), + ([("a", "-OTTER")], "-OTTER: a callsign is 3-32 letters"), + ([("a", "OTTER4"), ("b", "otter4")], "otter4 is given twice"), + ([("a", "otter9")], "otter9 already belongs to host c"), + ([("c", "otter9")], ""), + ], +) +def test_a_batch_is_refused_whole(wanted: list[tuple[str, str]], says: str) -> None: + """Callsigns compared without case; a phone may keep its own""" + phones = [_phone("a"), _phone("b"), _phone("c", "OTTER9")] + + refused = core.refusal(phones, wanted) + + assert refused.startswith(says) if says else not refused From 079ed08ddfc1b843071695c599b59ec7cf821b48 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:31:59 +0200 Subject: [PATCH 036/104] feat: ship the example template inside the package --- README.rst | 4 ++-- examples/README.rst | 6 ++++++ {examples => src/odmdm_connector}/template.json | 3 ++- src/odmdm_connector/template.py | 3 +++ tests/test_template.py | 6 ++---- 5 files changed, 15 insertions(+), 7 deletions(-) create mode 100644 examples/README.rst rename {examples => src/odmdm_connector}/template.json (96%) diff --git a/README.rst b/README.rst index 3566490..029760c 100644 --- a/README.rst +++ b/README.rst @@ -125,8 +125,8 @@ The template What to install is a property of the deployment, so it is a document rather than code: the apps, their managed configuration, the Android Management API device policy, a launcher link, and the certificate template. ``{domain}``, ``{mtls_url}`` and ``{key_alias}`` are filled in. Keys -beginning with ``_`` are comments and never reach Fleet. ``examples/template.json`` is a working one -for Deploy App, with its reasoning in the comments. +beginning with ``_`` are comments and never reach Fleet. ``src/odmdm_connector/template.json``, shipped +in the package, is a working one for Deploy App, with its reasoning in the comments. The certificate subject is the contract with the deployment. Its common name becomes the callsign: 3 to 32 letters, digits or hyphens, no hyphen at either end. It is the name ``name`` gives the diff --git a/examples/README.rst b/examples/README.rst new file mode 100644 index 0000000..c158a08 --- /dev/null +++ b/examples/README.rst @@ -0,0 +1,6 @@ +======== +Examples +======== + +The example template moved into the package, so an installed connector carries it: +``src/odmdm_connector/template.json``. Copy it from there to change what a deployment installs. diff --git a/examples/template.json b/src/odmdm_connector/template.json similarity index 96% rename from examples/template.json rename to src/odmdm_connector/template.json index 5eef1b7..1680e0f 100644 --- a/examples/template.json +++ b/src/odmdm_connector/template.json @@ -1,6 +1,7 @@ { "_comment": [ - "What a Deploy App deployment's phones need. Copy it, change what to install, and apply it with", + "What a Deploy App deployment's phones need. apply states this one unless given another: copy it,", + "change what to install, and apply it with", " odmdm-connector apply --template template.json --domain ", "", "Placeholders filled in at apply time: {domain}, {mtls_url}, {key_alias}.", diff --git a/src/odmdm_connector/template.py b/src/odmdm_connector/template.py index c11d21e..152b662 100644 --- a/src/odmdm_connector/template.py +++ b/src/odmdm_connector/template.py @@ -23,6 +23,9 @@ LOGGER = logging.getLogger(__name__) +#: The template shipped with the package: what a Deploy App deployment's phones need +EXAMPLE = Path(__file__).with_name("template.json") + class TemplateError(ValueError): """The document is not something we can act on""" diff --git a/tests/test_template.py b/tests/test_template.py index 674ecd4..b1eaf9c 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -9,7 +9,7 @@ import pytest -from odmdm_connector.template import TemplateError, load +from odmdm_connector.template import EXAMPLE, TemplateError, load GOOD = { "apps": [ @@ -169,9 +169,7 @@ def test_annotations_never_reach_the_device(tmp_path: Path) -> None: def test_the_example_is_a_template_we_accept() -> None: """Operators start from it, so it must never drift out of what load() takes""" - example = Path(__file__).resolve().parent.parent / "examples" / "template.json" - - template = load(example, domain="example.fi", key_alias="rmscep") + template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") assert template.certificate is not None assert template.certificate.name == "rmscep", "the keystore alias comes from the setting" From df7a09de305377339c9b70c9d7c24412011fde46 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:33:54 +0200 Subject: [PATCH 037/104] feat: put Fleet behind the MDM contract as the built-in plugin --- pyproject.toml | 3 + src/odmdm_connector/fleet_plugin.py | 224 ++++++++++++++++++++++++++++ tests/test_fleet_plugin.py | 144 ++++++++++++++++++ 3 files changed, 371 insertions(+) create mode 100644 src/odmdm_connector/fleet_plugin.py create mode 100644 tests/test_fleet_plugin.py diff --git a/pyproject.toml b/pyproject.toml index e60b395..fa57cec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,6 +21,9 @@ repository = "https://github.com/pvarki/python-odmdm-fleet" [project.scripts] odmdm-connector = "odmdm_connector.console:odmdm_connector_cli" +[project.entry-points."odmdm_connector.mdm"] +fleet = "odmdm_connector.fleet_plugin:FleetPlugin" + [dependency-groups] dev = [ "pytest>=8.0,<9.0", diff --git a/src/odmdm_connector/fleet_plugin.py b/src/odmdm_connector/fleet_plugin.py new file mode 100644 index 0000000..bd050f5 --- /dev/null +++ b/src/odmdm_connector/fleet_plugin.py @@ -0,0 +1,224 @@ +"""Fleet behind the MDM contract: the plugin built into the connector + +Registered under the entry point group odmdm_connector.mdm as fleet, as a plugin from another +package would be. What Fleet does on the wire is fleet.FleetMdm's; this turns it into the +contract's phones, states, steps and sentences. +""" + +from collections.abc import Iterator, Mapping, Sequence +from pathlib import Path +from typing import ClassVar +from urllib.parse import urlparse + +from . import template +from .fleet import FleetError, FleetMdm +from .fleet import Phone as FleetPhone +from .mdm import API_VERSION, Field, MdmError, Phone, State, Step +from .settings import Settings + +#: A phone acts on a request at its next check-in, every 15 minutes +CHECK_IN = "up to 15 minutes" + + +def _state(phone: FleetPhone) -> tuple[State, str]: + """Where the certificate is, and Fleet's words beside it + + The details matched are the ones seen on a live Fleet 4.90.1. After a failure a phone reports, + Fleet asks again by itself up to three times, and that request keeps the failure's detail while + it waits. + """ + if not phone.status: + return State.NO_REQUEST, "" + if phone.status == "verified": + return State.READY, "" + if phone.status == "failed": + return _failure(phone) + if not phone.detail: + return State.WAITING, CHECK_IN + state, detail = _failure(phone) + return State.WAITING, f"{CHECK_IN}; last time: {state.value}{': ' + detail if detail else ''}" + + +def _failure(phone: FleetPhone) -> tuple[State, str]: + """What Fleet's detail on a failed request means""" + if "does not have an IDP user" in phone.detail: + # Naming does not send the request again, so a name beside this detail was given without a resend + return (State.NOT_ASKED, "run resend") if phone.callsign else (State.NEEDS_NAME, "") + if "SCEP enrollment failed" in phone.detail: + return State.REFUSED, "name taken or not allowed, enrolment closed, or Fleet has an old challenge" + if "Network error" in phone.detail: + return State.UNREACHABLE, "" + # Nothing seen on a live Fleet yet: Fleet's own words, as a failure the phone can be asked again after + return State.FAILED, phone.detail + + +class FleetPlugin: + """FleetDM, one team per Deploy App""" + + API_VERSION: ClassVar[int] = API_VERSION + title: ClassVar[str] = "Fleet" + fields: ClassVar[tuple[Field, ...]] = ( + Field("mdm_url", "Fleet address", help="Base URL of Fleet's API, https only"), + Field( + "token", + "API token", + secret=True, + help="A Fleet API token. Giving Fleet a challenge needs a global admin's", + ), + Field("team", "Team", default="Deploy App", help="The team phones enrol into and get the certificate in"), + Field("template", "Template", help="A template file; without one, the one shipped with the connector"), + Field( + "key_alias", + "Key alias", + default="rmscep", + help="The certificate template's name, the Android keystore alias. Never change it for a deployment", + ), + ) + missing: ClassVar[Mapping[str, str]] = {} + + def __init__(self, values: Mapping[str, str]) -> None: + given = {item.key: values.get(item.key) or item.default for item in self.fields} + self._url = given["mdm_url"] + self._token = given["token"] + self.team = given["team"] + self.template = Path(given["template"]) if given["template"] else template.EXAMPLE + self.key_alias = given["key_alias"] + self._api: FleetMdm | None = None + self._team_id = 0 + + def _fleet(self) -> FleetMdm: + """Fleet's API, checked only once it is needed, so a dry run needs no token""" + if self._api: + return self._api + if not self._url: + raise MdmError("Give --mdm-url or set ODMDM_MDM_URL") + if urlparse(self._url).scheme != "https": + raise MdmError( + "The MDM address must start with https://, or the API token would cross the network readable" + ) + if not self._token: + raise MdmError("Set ODMDM_TOKEN_FILE to a file holding the Fleet API token") + self._api = FleetMdm(self._url, self._token) + return self._api + + def _template(self, window: Settings) -> template.MdmTemplate: + """The template with this deployment's values filled in""" + try: + return template.load( + self.template, domain=urlparse(window.scep_url).hostname or "", key_alias=self.key_alias + ) + except template.TemplateError as exc: + raise MdmError(f"Template refused: {exc}") from exc + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + """State what the template says, in the order FleetMdm.apply knows works + + force sends the policy again even if Fleet's copy is unchanged, to reach a phone that just + joined. + """ + wanted = self._template(window) + lines = [f" {app.package}{' (at enrolment)' if app.preinstall else ' (on demand)'}" for app in wanted.apps] + if wanted.link_app: + lines.append(f" launcher link {wanted.link_app.title!r} -> {wanted.link_app.url}") + label = f"Template names {len(wanted.apps)} apps, {len(wanted.preinstall_packages)} installed at enrolment" + yield Step(label, True, "\n".join(lines)) + if dry_run: + return + try: + result = self._fleet().apply( + self.team, wanted, force_policy=force, scep_url=window.scep_url, challenge=window.challenge + ) + except FleetError as exc: + raise MdmError(f"Fleet refused: {exc}") from exc + yield Step(f"Applied to team {result['team_id']}: {len(result['assigned'])} apps assigned", True) + + def set_challenge(self, window: Settings) -> None: + """Repoint the template's certificate authority, and change nothing else""" + wanted = self._template(window) + if not wanted.certificate: + raise MdmError("The template states no certificate, so there is no authority to give it to") + try: + self._fleet().ensure_authority(wanted.certificate.authority, window.scep_url, window.challenge) + except FleetError as exc: + raise MdmError(f"Fleet refused: {exc}") from exc + + def _phones(self) -> dict[str, FleetPhone]: + """The team's phones by id, read now: never kept between calls, so nothing shown is stale""" + api = self._fleet() + try: + self._team_id = api.team_id(self.team) + return {str(phone.id): phone for phone in api.phones(self._team_id, self.key_alias)} + except FleetError as exc: + raise MdmError(f"Fleet refused: {exc}") from exc + + def phones(self) -> list[Phone]: + return [ + Phone(key, phone.callsign, phone.model, phone.enrolled, *_state(phone)) + for key, phone in self._phones().items() + ] + + def _policy_again(self, found: dict[str, FleetPhone]) -> list[str]: + """Send the policy again if a phone enrolled after it was last sent, as Fleet may have overwritten it there""" + later = self._fleet().resend_policy(self._team_id, list(found.values())) + if not later: + return [] + return [f"Policy sent again: {later} phone{'' if later == 1 else 's'} enrolled after it was last sent"] + + def name(self, names: Mapping[str, str]) -> list[str]: + """Name each host, have Fleet send its certificate request again, then the policy if needed + + A phone that has its certificate under the name is left alone: asked again under the name + it holds, it is refused as taken, and a working phone then shows as refused. + """ + found = self._phones() + unknown = [key for key in names if key not in found] + if unknown: + raise MdmError(f"Nothing named: host {unknown[0]} is not in the team") + api = self._fleet() + lines: list[str] = [] + named: dict[str, str] = {} + try: + certificate = api.certificate_template(self._team_id, self.key_alias) + for key, callsign in names.items(): + old = found[key] + if old.status == "verified" and old.callsign.lower() == callsign.lower(): + lines.append(f"Host {key} is already {old.callsign}") + continue + api.name_host(old.id, callsign) + named[key] = callsign + if old.status: + api.resend(old.id, certificate) + line = f"Host {key} is {callsign}" + if not old.status: + line += ". Fleet has no certificate request for it, so nothing was sent" + elif old.status == "verified" and old.callsign: + line += ( + f". It was {old.callsign} and still has that certificate: revoke {old.callsign} in Deploy App." + ) + lines.append(line) + if named: + lines += self._policy_again(found) + except FleetError as exc: + raise MdmError(f"Fleet refused: {exc}", named, lines) from exc + return lines + + def ask_again(self, ids: Sequence[str]) -> list[str]: + """Resend the hosts' certificate requests; no ids: every named phone whose request failed""" + found = self._phones() + unknown = [key for key in ids if key not in found] + if unknown: + raise MdmError(f"Nothing sent: host {unknown[0]} is not in the team") + chosen = list(ids) or [key for key, phone in found.items() if phone.status == "failed" and phone.callsign] + if not chosen: + return [] + api = self._fleet() + lines: list[str] = [] + try: + certificate = api.certificate_template(self._team_id, self.key_alias) + for key in chosen: + api.resend(found[key].id, certificate) + lines.append(f"Host {key} ({found[key].callsign or 'no name'}): certificate asked for again") + lines += self._policy_again(found) + except FleetError as exc: + raise MdmError(f"Fleet refused: {exc}", lines=lines) from exc + return lines diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py new file mode 100644 index 0000000..d2aa2da --- /dev/null +++ b/tests/test_fleet_plugin.py @@ -0,0 +1,144 @@ +"""Fleet behind the MDM contract, against the stubbed Fleet""" + +import datetime + +import httpx +import pytest + +from odmdm_connector.fleet_plugin import FleetPlugin +from odmdm_connector.mdm import Mdm, MdmError, State +from odmdm_connector.settings import Settings + +from .test_fleet import _Fleet, _host, _mdm + +NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" +REFUSED = "SCEP enrollment failed: Enrollment failed with SCEP failInfo: badMessageCheck" +UNREACHED = "Network error during SCEP enrollment: Failed to communicate with SCEP server" +WINDOW = Settings("https://example.fi/scep", "new-window", datetime.datetime(2026, 11, 21, 14, tzinfo=datetime.UTC)) + + +@pytest.fixture +def fleet(monkeypatch: pytest.MonkeyPatch) -> _Fleet: + """A stubbed Fleet whose team has its certificate template""" + stub = _Fleet() + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$X", "certificate_authority_id": 3}] + _mdm(stub, monkeypatch) + return stub + + +def _plugin(**values: str) -> Mdm: + return FleetPlugin({"mdm_url": "https://mdm.test", "token": "token", "team": "rmscep", **values}) + + +@pytest.mark.parametrize( + ("status", "callsign", "detail", "state", "words"), + [ + ("", "", "", State.NO_REQUEST, ""), + ("verified", "OTTER4", "", State.READY, ""), + ("failed", "", NO_NAME, State.NEEDS_NAME, ""), + ("failed", "OTTER4", NO_NAME, State.NOT_ASKED, "run resend"), + ("failed", "OTTER4", REFUSED, State.REFUSED, "name taken or not allowed"), + ("failed", "OTTER4", UNREACHED, State.UNREACHABLE, ""), + ("failed", "OTTER4", "Something new", State.FAILED, "Something new"), + ("pending", "OTTER4", "", State.WAITING, "up to 15 minutes"), + ("delivered", "OTTER4", UNREACHED, State.WAITING, "up to 15 minutes; last time: could not reach Deploy App"), + ], +) +def test_fleets_status_and_detail_become_a_state( + fleet: _Fleet, status: str, callsign: str, detail: str, state: State, words: str +) -> None: + """Fleet's words are kept beside the state as its detail""" + fleet.hosts = [_host(31, status, callsign, detail)] + + [phone] = _plugin().phones() + + assert (phone.id, phone.callsign, phone.joined) == ("31", callsign, "2026-11-01T19:38:12Z") + assert phone.state is state + assert phone.detail.startswith(words) if words else not phone.detail + + +def _listings(fleet: _Fleet) -> int: + return len([path for _, path in fleet.calls if path.endswith("/hosts")]) + + +def test_name_answers_its_lines_and_reads_the_phones_once(fleet: _Fleet) -> None: + """Read once, and the phones checked are the ones named""" + fleet.hosts = [_host(31, "failed", detail=NO_NAME), _host(32)] + + lines = _plugin().name({"32": "OTTER5", "31": "OTTER4"}) + + assert lines == [ + "Host 32 is OTTER5. Fleet has no certificate request for it, so nothing was sent", + "Host 31 is OTTER4", + ] + assert _listings(fleet) == 1 + + +def test_phones_are_read_afresh_on_every_call(fleet: _Fleet) -> None: + """A refresh never shows what an earlier one read""" + fleet.hosts = [_host(31)] + plugin = _plugin() + + first = plugin.phones() + fleet.hosts.append(_host(32)) + second = plugin.phones() + + assert ([p.id for p in first], [p.id for p in second]) == (["31"], ["31", "32"]) + assert _listings(fleet) == 2 + + +@pytest.mark.parametrize("call", ["name", "ask_again"]) +def test_an_id_not_in_the_team_changes_nothing(fleet: _Fleet, call: str) -> None: + fleet.hosts = [_host(31, "failed", detail=NO_NAME)] + plugin = _plugin() + + with pytest.raises(MdmError, match="host 99 is not in the team"): + plugin.name({"99": "OTTER4"}) if call == "name" else plugin.ask_again(["99"]) + + assert not [method for method, _ in fleet.calls if method != "GET"] + + +def test_a_batch_stopped_half_way_names_the_phones_named(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + answer = fleet.handler + + def refusing(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/hosts/32/certificates/81/resend"): + return httpx.Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] + + with pytest.raises(MdmError, match="Fleet refused: POST .*/hosts/32/.* answered 500") as raised: + _plugin().name({"31": "OTTER1", "32": "OTTER2", "33": "OTTER3"}) + + assert raised.value.named == {"31": "OTTER1", "32": "OTTER2"} + + +@pytest.mark.parametrize( + ("values", "says"), + [ + ({"mdm_url": ""}, "ODMDM_MDM_URL"), + ({"mdm_url": "http://mdm.test"}, "must start with https://"), + ({"token": ""}, "ODMDM_TOKEN_FILE"), + ], +) +def test_fleet_is_reached_only_when_configured(fleet: _Fleet, values: dict[str, str], says: str) -> None: + """Said when Fleet is first needed, so a dry run needs no token""" + plugin = _plugin(**values) + + [step] = plugin.setup(WINDOW, dry_run=True) + with pytest.raises(MdmError, match=says): + plugin.phones() + + assert step.label == "Template names 3 apps, 3 installed at enrolment" + assert "launcher link 'Deploy App' -> https://mtls.example.fi/" in step.message + assert not fleet.calls + + +def test_ask_again_without_ids_and_nobody_failed_answers_nothing(fleet: _Fleet) -> None: + fleet.hosts = [_host(31, "verified", "OTTER4")] + + assert _plugin().ask_again([]) == [] + assert not [method for method, _ in fleet.calls if method != "GET"] From 798f430ba4266f7d02954f85cb85a4fa7761b6ee Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:36:24 +0200 Subject: [PATCH 038/104] refactor: drive the MDM through its contract, chosen with --mdm and set with --set --- README.rst | 2 +- src/odmdm_connector/config.py | 22 +- src/odmdm_connector/console.py | 456 ++++++++++++++------------------- src/odmdm_connector/core.py | 11 +- src/odmdm_connector/fleet.py | 31 --- tests/test_console.py | 182 +++++++++++-- tests/test_core.py | 6 +- 7 files changed, 370 insertions(+), 340 deletions(-) diff --git a/README.rst b/README.rst index 029760c..827c881 100644 --- a/README.rst +++ b/README.rst @@ -83,7 +83,7 @@ Commands from ``--start N``, 1 or more. It sees only this team's phones, and Deploy App never gives a callsign out twice: where callsigns were used by phones no longer in the team, give ``--start`` above the highest ever used. ``name`` changes nothing at all if a callsign is malformed, given twice or -already another phone's, or if a host is not in the team. A phone that already has its certificate +already another phone's, or if a phone is not in the team. A phone that already has its certificate under the name is left alone. Renaming a phone that has its certificate says which old callsign to revoke. diff --git a/src/odmdm_connector/config.py b/src/odmdm_connector/config.py index 067ed48..b24e90b 100644 --- a/src/odmdm_connector/config.py +++ b/src/odmdm_connector/config.py @@ -1,10 +1,10 @@ """Configuration, from the environment -Every setting is prefixed ODMDM_. +Every setting is prefixed ODMDM_. These are the deployment's; the MDM's own come from its plugin's +fields, read by the command line as ODMDM_. """ import os -from pathlib import Path def _env(name: str, default: str = "") -> str: @@ -13,26 +13,8 @@ def _env(name: str, default: str = "") -> str: LOG_LEVEL: int = int(_env("LOG_LEVEL", "20")) -#: Where Fleet's API answers -URL: str = _env("MDM_URL") - -#: A file holding the Fleet API token. A path rather than the value, so it can be a mounted secret -#: and never appears in a process environment. -TOKEN_FILE: Path | None = Path(_env("TOKEN_FILE")) if _env("TOKEN_FILE") else None - -#: The team whose devices get the deployment's certificate -TEAM: str = _env("TEAM", "Deploy App") - -#: What this deployment wants installed, as a document. See odmdm_connector.template. -TEMPLATE: Path | None = Path(_env("TEMPLATE")) if _env("TEMPLATE") else None - #: The deployment's DNS name, which the template substitutes into URLs DOMAIN: str = _env("DOMAIN") #: The challenge shown on Deploy App's MDM page. It is new for every enrolment window. CHALLENGE: str = _env("CHALLENGE") - -#: The certificate template name, which becomes the Android keystore alias the certificate lands -#: under. Installing a second key under an existing alias fails, so it never changes for a -#: deployment; the default is what the first deployments were set up with. -KEY_ALIAS: str = _env("KEY_ALIAS", "rmscep") diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 7841ad0..340faf5 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -1,9 +1,16 @@ -"""CLI entrypoints for odmdm-connector""" +"""CLI entrypoints for odmdm-connector + +Knows the MDM only through the contract in mdm.py: the chosen MDM is the one entry point of the +group odmdm_connector.mdm named by --mdm, Fleet being the one built in. +""" import datetime import logging -import re +import os +from collections.abc import Mapping +from importlib.metadata import entry_points from pathlib import Path +from typing import NoReturn from urllib.parse import urlparse import click @@ -11,23 +18,38 @@ from odmdm_connector import __version__ -from . import config, settings, template -from .fleet import FleetError, FleetMdm, Phone +from . import config, core, settings +from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError +from .settings import Settings LOGGER = logging.getLogger(__name__) -#: The deployment's rule for a device callsign, checked here only so a typo is refused now rather -#: than as a failed certificate twenty minutes later. The deployment still decides. -CALLSIGN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{1,30}[A-Za-z0-9]") +#: Where MDM plugins are found, the built-in one among them +GROUP = "odmdm_connector.mdm" @click.group() @click.version_option(version=__version__) @click.pass_context @click.option("-v", "--verbose", count=True, help="Shorthand for info/debug loglevel (-v/-vv)") -def cli_group(ctx: click.Context, verbose: int) -> None: - """Connect FleetDM to an OpenDefence deployment's device enrolment""" - _ = ctx +@click.option( + "--mdm", + "chosen", + envvar="ODMDM_MDM", + default="fleet", + show_default=True, + metavar="NAME", + help="The MDM to talk to (default: ODMDM_MDM, else fleet)", +) +@click.option( + "--set", + "given", + multiple=True, + metavar="KEY=VALUE", + help="A setting of the MDM, such as mdm_url; never a secret, which is read from the file ODMDM__FILE names", +) +def cli_group(ctx: click.Context, verbose: int, chosen: str, given: tuple[str, ...]) -> None: + """Connect an MDM, Fleet built in, to an OpenDefence deployment's device enrolment""" loglevel = config.LOG_LEVEL if verbose == 1: loglevel = 20 @@ -35,8 +57,15 @@ def cli_group(ctx: click.Context, verbose: int) -> None: loglevel = 10 init_logging(loglevel) LOGGER.setLevel(loglevel) - # One line per Fleet request buries what the command says; -vv brings them back + # One line per MDM request buries what the command says; -vv brings them back logging.getLogger("httpx").setLevel(max(loglevel, logging.WARNING) if verbose < 2 else loglevel) + sets: dict[str, str] = {} + for value in given: + key, equals, setting = value.partition("=") + if not key or not equals: + raise click.UsageError("--set takes KEY=VALUE") + sets[key] = setting + ctx.obj = {"mdm": chosen, "set": sets} def odmdm_connector_cli() -> None: @@ -44,74 +73,101 @@ def odmdm_connector_cli() -> None: cli_group() # pylint: disable=no-value-for-parameter -def _fleet(ctx: click.Context, url: str | None) -> FleetMdm | None: - """Fleet's API, or None after saying what is missing""" - the_url = url or config.URL - if not the_url: - click.echo("Give --mdm-url or set ODMDM_MDM_URL", err=True) - ctx.exit(1) - return None - if urlparse(the_url).scheme != "https": - click.echo( - "The MDM address must start with https://, or the API token would cross the network readable", err=True - ) - ctx.exit(1) - return None - if not config.TOKEN_FILE or not config.TOKEN_FILE.is_file(): - click.echo("Set ODMDM_TOKEN_FILE to a file holding the Fleet API token", err=True) - ctx.exit(1) - return None - return FleetMdm(the_url, config.TOKEN_FILE.read_text(encoding="utf-8").strip()) +def _fail(ctx: click.Context, message: str) -> NoReturn: + click.echo(message, err=True) + ctx.exit(1) -def _template(ctx: click.Context, path: str | None, domain: str | None) -> template.MdmTemplate | None: - """The deployment's template with its values filled in, or None after saying why not""" - the_path = Path(path) if path else config.TEMPLATE - the_domain = domain or config.DOMAIN - if not the_path or not the_domain: - click.echo("Give --template and --domain or set ODMDM_TEMPLATE and ODMDM_DOMAIN", err=True) - ctx.exit(1) - return None +def _chosen(name: str) -> type[Mdm]: + """The class of the MDM of that name, loading that one entry point and no other""" + found = entry_points(group=GROUP, name=name) + if not found: + raise click.UsageError(f"No MDM named {name} is installed") + loaded: type[Mdm] = next(iter(found)).load() + return loaded + + +def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str]) -> dict[str, str]: + """The fields' values: from --set, else ODMDM_, else the default + + A secret only ever from the file ODMDM__FILE names, so it stays out of shell history and + process environments. No value is ever in a message. + """ + keys = sorted(item.key for item in fields) + unknown = sorted(set(given) - set(keys)) + if unknown: + raise click.UsageError(f"{name} has no setting {unknown[0]}; it has {', '.join(keys)}") + values: dict[str, str] = {} + for item in fields: + env = f"ODMDM_{item.key.upper()}" + if item.secret: + if item.key in given: + raise click.UsageError(f"{item.key} is a secret: put it in a file and set {env}_FILE to that file") + path = os.environ.get(f"{env}_FILE", "") + values[item.key] = Path(path).read_text(encoding="utf-8").strip() if path and Path(path).is_file() else "" + else: + values[item.key] = given[item.key] if item.key in given else os.environ.get(env, item.default) + return values + + +def _mdm(ctx: click.Context, capability: str = "", **shorthands: str | None) -> Mdm: + """The chosen MDM, configured; or the MDM's sentence for lacking the capability, and exit + + The shorthands are the per-command options such as --team, each the same as --set team=... + """ + name = str(ctx.obj["mdm"]) + chosen = _chosen(name) + if capability in chosen.missing: + _fail(ctx, chosen.missing[capability]) + given = {**ctx.obj["set"], **{key: value for key, value in shorthands.items() if value is not None}} try: - return template.load(the_path, domain=the_domain, key_alias=config.KEY_ALIAS) - except template.TemplateError as exc: - click.echo(f"Template refused: {exc}", err=True) - ctx.exit(1) - return None + return chosen(_values(name, chosen.fields, given)) + except MdmError as exc: + _fail(ctx, str(exc)) + + +def _domain(ctx: click.Context, domain: str | None) -> str: + the_domain = domain or config.DOMAIN + if not the_domain: + _fail(ctx, "Give --domain or set ODMDM_DOMAIN") + return the_domain def _now() -> datetime.datetime: return datetime.datetime.now(datetime.UTC) -def _window(ctx: click.Context, value: str, domain: str) -> tuple[str, str, str] | None: - """The SCEP URL, the challenge and until when the window is open, from a challenge or a settings line +def _window(ctx: click.Context, value: str, domain: str) -> Settings: + """The enrolment window, from a settings line or a bare challenge, or exit after saying why not - None after saying why not. A bare challenge says nothing of the window. The challenge is never - in a message. + A bare challenge says nothing of when the window closes. The challenge is never in a message. """ if not settings.is_line(value): - return f"https://{domain}/scep", value.strip(), "" + return Settings(f"https://{domain}/scep", value.strip()) try: line = settings.parse(value, _now()) except settings.SettingsError as exc: - click.echo(str(exc), err=True) - ctx.exit(1) - return None + _fail(ctx, str(exc)) host = urlparse(line.scep_url).hostname or "" if host != domain.lower(): - click.echo(f"The settings line is for {host}, not {domain}: copy it from this deployment's MDM page", err=True) - ctx.exit(1) - return None - return line.scep_url, line.challenge, f"{line.closes:%Y-%m-%d %H:%M} UTC" + _fail(ctx, f"The settings line is for {host}, not {domain}: copy it from this deployment's MDM page") + return line + + +MDM_URL = click.option("--mdm-url", default=None, help="The MDM's address, as --set mdm_url (default: ODMDM_MDM_URL)") +TEAM = click.option("--team", default=None, help="The team the phones are in, as --set team (default: ODMDM_TEAM)") +TEMPLATE = click.option( + "--template", "path", default=None, help="What to install, as --set template (default: ODMDM_TEMPLATE)" +) +DOMAIN = click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_DOMAIN)") @cli_group.command(name="apply") @click.pass_context -@click.option("--template", "path", default=None, help="What to install (default: ODMDM_TEMPLATE)") -@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") -@click.option("--team", default=None, help="The team devices get the certificate in (default: ODMDM_TEAM)") -@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_DOMAIN)") +@TEMPLATE +@MDM_URL +@TEAM +@DOMAIN @click.option( "--force-policy", is_flag=True, help="Re-upload the policy even if unchanged, to reach a host that just joined" ) @@ -125,7 +181,7 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments force_policy: bool, dry_run: bool, ) -> None: - """Tell Fleet what this deployment's devices need + """Tell the MDM what this deployment's devices need Run it when a deployment is set up and whenever its template changes. A changed policy stops apps installing on phones that are enrolling at that moment, so a new enrolment window is @@ -135,33 +191,16 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments device that has already joined will not pick up a template applied afterwards -- it has to enrol again, under a callsign that has not been spent. """ - wanted = _template(ctx, path, domain) - if not wanted: - return - click.echo(f"Template names {len(wanted.apps)} apps, {len(wanted.preinstall_packages)} installed at enrolment") - for app in wanted.apps: - click.echo(f" {app.package}{' (at enrolment)' if app.preinstall else ' (on demand)'}") - if wanted.link_app: - click.echo(f" launcher link {wanted.link_app.title!r} -> {wanted.link_app.url}") - if dry_run: - ctx.exit(0) - return - - window = _window(ctx, config.CHALLENGE, domain or config.DOMAIN) - if not window: - return - fleet = _fleet(ctx, mdm_url) - if not fleet: - return + the_domain = _domain(ctx, domain) + window = Settings(f"https://{the_domain}/scep", "") if dry_run else _window(ctx, config.CHALLENGE, the_domain) + mdm = _mdm(ctx, SETUP, mdm_url=mdm_url, team=team, template=path) try: - result = fleet.apply( - team or config.TEAM, wanted, force_policy=force_policy, scep_url=window[0], challenge=window[1] - ) - except FleetError as exc: - click.echo(f"Fleet refused: {exc}", err=True) - ctx.exit(1) - return - click.echo(f"Applied to team {result['team_id']}: {len(result['assigned'])} apps assigned") + for step in mdm.setup(window, force=force_policy, dry_run=dry_run): + click.echo(step.label if step.done else f"{step.label} (not done)") + if step.message: + click.echo(step.message) + except MdmError as exc: + _fail(ctx, str(exc)) ctx.exit(0) @@ -171,129 +210,62 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments "--challenge", "value", envvar="ODMDM_CHALLENGE", - prompt="Settings line or challenge from Deploy App's MDM page", - hide_input=True, + default=None, help="The new window's settings line or challenge (default: ODMDM_CHALLENGE, else asked for)", ) -@click.option("--template", "path", default=None, help="What to install (default: ODMDM_TEMPLATE)") -@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") -@click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_DOMAIN)") +@TEMPLATE +@MDM_URL +@DOMAIN def challenge( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, value: str, path: str | None, mdm_url: str | None, domain: str | None + ctx: click.Context, value: str | None, path: str | None, mdm_url: str | None, domain: str | None ) -> None: - """Give Fleet the challenge of the enrolment window just opened + """Give the MDM the challenge of the enrolment window just opened Every opening makes a new one. Only the certificate authority changes, so phones still installing apps are left alone. Asked for rather than taken as an argument, so it stays out of shell history. Given the whole settings line, its SCEP URL must be on this deployment's domain. """ - wanted = _template(ctx, path, domain) - if not wanted: - return - if not wanted.certificate: - click.echo("The template states no certificate, so there is no authority to give it to", err=True) - ctx.exit(1) - return - window = _window(ctx, value, domain or config.DOMAIN) - if not window: - return - fleet = _fleet(ctx, mdm_url) - if not fleet: - return + the_domain = _domain(ctx, domain) + mdm = _mdm(ctx, SET_CHALLENGE, mdm_url=mdm_url, template=path) + if value is None: + value = str(click.prompt("Settings line or challenge from Deploy App's MDM page", hide_input=True)) + window = _window(ctx, value, the_domain) try: - fleet.ensure_authority(wanted.certificate.authority, window[0], window[1]) - except FleetError as exc: - click.echo(f"Fleet refused: {exc}", err=True) - ctx.exit(1) - return - until = f". The enrolment window is open until {window[2]}" if window[2] else "" - click.echo(f"{wanted.certificate.authority} has the new challenge{until}") + mdm.set_challenge(window) + except MdmError as exc: + _fail(ctx, str(exc)) + until = f". The enrolment window is open until {window.closes:%Y-%m-%d %H:%M} UTC" if window.closes else "" + click.echo(f"{mdm.title} has the new challenge{until}") ctx.exit(0) @cli_group.command(name="phones") @click.pass_context -@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") -@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") +@MDM_URL +@TEAM def phones(ctx: click.Context, mdm_url: str | None, team: str | None) -> None: """List the team's phones and where each one's certificate is - One line each: the host id that name and resend take, the callsign, the model, the day it + One line each: the id that name and resend take, the callsign, the model, the day it enrolled, and the certificate in plain words. """ - fleet = _fleet(ctx, mdm_url) - if not fleet: - return + mdm = _mdm(ctx, mdm_url=mdm_url, team=team) try: - found = fleet.phones(fleet.team_id(team or config.TEAM), config.KEY_ALIAS) - except FleetError as exc: - click.echo(f"Fleet refused: {exc}", err=True) - ctx.exit(1) - return + found = mdm.phones() + except MdmError as exc: + _fail(ctx, str(exc)) for phone in found: - click.echo(f"{phone.id:<5} {phone.callsign or '-':<12} {phone.model:<26} {phone.enrolled[:10]} {phone.state}") + click.echo( + f"{phone.id:<5} {phone.callsign or '-':<12} {phone.model:<26} {phone.joined[:10]} {core.said(phone)}" + ) if not found: click.echo("No phones in the team") ctx.exit(0) -def _pairs(values: tuple[str, ...]) -> list[tuple[int, str]]: - """HOST=CALLSIGN arguments, as host ids and callsigns""" - pairs = [] - for value in values: - host, _, callsign = value.partition("=") - if not host.isdigit() or not callsign: - raise click.UsageError(f"{value!r} is not HOST=CALLSIGN, the host being the id that phones prints") - pairs.append((int(host), callsign)) - return pairs - - -def _numbered(found: list[Phone], prefix: str, start: int | None) -> list[tuple[int, str]]: - """PREFIX for every phone without a name, in enrolment order - - Numbered from start, else from one above the highest PREFIX already in the team. - """ - if start is None: - used = (re.fullmatch(re.escape(prefix) + r"(\d+)", phone.callsign, re.IGNORECASE) for phone in found) - start = max((int(match.group(1)) for match in used if match), default=0) + 1 - waiting = [phone.id for phone in found if not phone.callsign] - return [(host, f"{prefix}{start + n}") for n, host in enumerate(waiting)] - - -def _refusal(found: dict[int, Phone], wanted: list[tuple[int, str]]) -> str: - """Why these names cannot all be given, or empty when they can - - Callsigns are compared without case, as the deployment compares them. - """ - hosts: set[int] = set() - callsigns: set[str] = set() - for host, callsign in wanted: - if host not in found: - return f"host {host} is not in the team" - if host in hosts: - return f"host {host} is named twice" - if not CALLSIGN.fullmatch(callsign): - return f"{callsign}: a callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen" - if callsign.lower() in callsigns: - return f"{callsign} is given twice" - owner = next((p.id for p in found.values() if p.id != host and p.callsign.lower() == callsign.lower()), 0) - if owner: - return f"{callsign} already belongs to host {owner}" - hosts.add(host) - callsigns.add(callsign.lower()) - return "" - - -def _policy_again(fleet: FleetMdm, team_id: int, found: dict[int, Phone]) -> None: - """Send the policy again if a phone enrolled after it was last sent, as Fleet may have overwritten it there""" - later = fleet.resend_policy(team_id, list(found.values())) - if later: - click.echo(f"Policy sent again: {later} phone{'' if later == 1 else 's'} enrolled after it was last sent") - - @cli_group.command(name="name") @click.pass_context -@click.argument("pairs", nargs=-1, metavar="[HOST=CALLSIGN]...") +@click.argument("pairs", nargs=-1, metavar="[ID=CALLSIGN]...") @click.option( "--all", "prefix", @@ -308,8 +280,8 @@ def _policy_again(fleet: FleetMdm, team_id: int, found: dict[int, Phone]) -> Non default=None, help="The first n for --all (default: one above the highest in use)", ) -@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") -@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") +@MDM_URL +@TEAM def name( # pylint: disable=too-many-arguments,too-many-positional-arguments ctx: click.Context, pairs: tuple[str, ...], @@ -318,110 +290,78 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments mdm_url: str | None, team: str | None, ) -> None: - """Name phones, and have Fleet send them certificates + """Name phones, and have the MDM send them certificates - HOST=CALLSIGN for as many phones as you like, in any order, the host being the id that phones - prints. Or --all PREFIX, which numbers every phone that has no name yet. Each phone gets its - certificate at its next check-in, within about 15 minutes. A phone that already has its - certificate under the name is left alone. + ID=CALLSIGN for as many phones as you like, in any order, the id being what phones prints. Or + --all PREFIX, which numbers every phone that has no name yet. Each phone gets its certificate + at its next check-in, within about 15 minutes. A phone that already has its certificate under + the name is left alone. Nothing is changed if a name is not a callsign, is given twice or belongs to another phone in - the team, or if a host is not in the team. + the team, or if a phone is not in the team. - The team's policy is sent again, to every phone in it, if a phone enrolled after it was last - sent, because Fleet can overwrite a new phone's policy. So name phones once every phone in the + With Fleet, the team's policy is sent again, to every phone in it, if a phone enrolled after it + was last sent, because Fleet can overwrite a new phone's policy. So name phones once every phone in the team has its apps. """ if bool(pairs) == bool(prefix) or (start is not None and not prefix): - raise click.UsageError("Give HOST=CALLSIGN for each phone, or --all PREFIX") - wanted = _pairs(pairs) - fleet = _fleet(ctx, mdm_url) - if not fleet: - return - named: list[str] = [] + raise click.UsageError("Give ID=CALLSIGN for each phone, or --all PREFIX") + try: + wanted = core.pairs(pairs) + except ValueError as exc: + raise click.UsageError(str(exc)) from exc + mdm = _mdm(ctx, mdm_url=mdm_url, team=team) try: - team_id = fleet.team_id(team or config.TEAM) - found = {phone.id: phone for phone in fleet.phones(team_id, config.KEY_ALIAS)} + found = mdm.phones() if prefix: - wanted = _numbered(list(found.values()), prefix, start) - refused = _refusal(found, wanted) + wanted = core.numbered(found, prefix, start) + refused = core.refusal(found, wanted) if refused: - click.echo(f"Nothing named: {refused}", err=True) - ctx.exit(1) - return + _fail(ctx, f"Nothing named: {refused}") if not wanted: click.echo("Nothing to name") ctx.exit(0) - return - template = fleet.certificate_template(team_id, config.KEY_ALIAS) - for host, callsign in wanted: - old = found[host] - # Asked again under the name it holds, it is refused as taken: a working phone then shows as refused - if old.status == "verified" and old.callsign.lower() == callsign.lower(): - click.echo(f"Host {host} is already {old.callsign}") - continue - fleet.name_host(host, callsign) - named.append(f"{host}={callsign}") - if old.status: - fleet.resend(host, template) - line = f"Host {host} is {callsign}" - if not old.status: - line += ". Fleet has no certificate request for it, so nothing was sent" - elif old.status == "verified" and old.callsign: - line += f". It was {old.callsign} and still has that certificate: revoke {old.callsign} in Deploy App." + lines = mdm.name(dict(wanted)) + except MdmError as exc: + for line in exc.lines: click.echo(line) - if named: - _policy_again(fleet, team_id, found) - except FleetError as exc: - click.echo(f"Fleet refused: {exc}", err=True) - if named: - click.echo(f"Already named before it stopped: {' '.join(named)}. phones shows where each is", err=True) + click.echo(str(exc), err=True) + if exc.named: + done = " ".join(f"{phone}={callsign}" for phone, callsign in exc.named.items()) + click.echo(f"Already named before it stopped: {done}. phones shows where each is", err=True) ctx.exit(1) - return + for line in lines: + click.echo(line) ctx.exit(0) @cli_group.command(name="resend") @click.pass_context -@click.argument("hosts", nargs=-1, type=int) -@click.option("--mdm-url", default=None, help="Base URL of Fleet's API (default: ODMDM_MDM_URL)") -@click.option("--team", default=None, help="The team the phones are in (default: ODMDM_TEAM)") -def resend(ctx: click.Context, hosts: tuple[int, ...], mdm_url: str | None, team: str | None) -> None: - """Have Fleet send phones their certificate requests again +@click.argument("ids", nargs=-1) +@MDM_URL +@TEAM +def resend(ctx: click.Context, ids: tuple[str, ...], mdm_url: str | None, team: str | None) -> None: + """Have phones ask for their certificates again For a refused phone once the cause is fixed, such as enrolment opened again and its new - challenge given to Fleet. A taken name is not one of those: Deploy App never frees a name, so - give the phone another with name, which sends the request itself. Without host ids, every phone + challenge given to the MDM. A taken name is not one of those: Deploy App never frees a name, so + give the phone another with name, which sends the request itself. Without ids, every phone that has a name and whose certificate failed. Each acts on it at its next check-in, within about 15 minutes. - A host id is asked whatever its state. A phone that has its certificate asks again under the + An id is asked whatever its state. A phone that has its certificate asks again under the name it holds and is refused, and reads as refused from then on though that certificate still works. As with name, the team's policy is sent again if a phone enrolled after it was last sent. """ - fleet = _fleet(ctx, mdm_url) - if not fleet: - return + mdm = _mdm(ctx, ASK_AGAIN, mdm_url=mdm_url, team=team) try: - team_id = fleet.team_id(team or config.TEAM) - found = {phone.id: phone for phone in fleet.phones(team_id, config.KEY_ALIAS)} - unknown = [host for host in hosts if host not in found] - if unknown: - click.echo(f"Nothing sent: host {unknown[0]} is not in the team", err=True) - ctx.exit(1) - return - chosen = list(hosts) or [phone.id for phone in found.values() if phone.status == "failed" and phone.callsign] - if not chosen: - click.echo("Nothing to resend") - ctx.exit(0) - return - template = fleet.certificate_template(team_id, config.KEY_ALIAS) - for host in chosen: - fleet.resend(host, template) - click.echo(f"Host {host} ({found[host].callsign or 'no name'}): certificate asked for again") - _policy_again(fleet, team_id, found) - except FleetError as exc: - click.echo(f"Fleet refused: {exc}", err=True) - ctx.exit(1) - return + lines = mdm.ask_again(list(ids)) + except MdmError as exc: + for line in exc.lines: + click.echo(line) + _fail(ctx, str(exc)) + for line in lines: + click.echo(line) + if not lines: + click.echo("Nothing to resend") ctx.exit(0) diff --git a/src/odmdm_connector/core.py b/src/odmdm_connector/core.py index 7e02cdd..f5c6970 100644 --- a/src/odmdm_connector/core.py +++ b/src/odmdm_connector/core.py @@ -43,16 +43,21 @@ def refusal(phones: Sequence[Phone], wanted: Sequence[tuple[str, str]]) -> str: callsigns: set[str] = set() for phone, callsign in wanted: if phone not in found: - return f"host {phone} is not in the team" + return f"phone {phone} is not in the group" if phone in ids: - return f"host {phone} is named twice" + return f"phone {phone} is named twice" if not CALLSIGN.fullmatch(callsign): return f"{callsign}: a callsign is 3-32 letters, digits or hyphens, and does not start or end with a hyphen" if callsign.lower() in callsigns: return f"{callsign} is given twice" owner = next((p.id for p in phones if p.id != phone and p.callsign.lower() == callsign.lower()), "") if owner: - return f"{callsign} already belongs to host {owner}" + return f"{callsign} already belongs to phone {owner}" ids.add(phone) callsigns.add(callsign.lower()) return "" + + +def said(phone: Phone) -> str: + """Where the phone's certificate is, as the operator reads it: the state, then the plugin's words""" + return f"{phone.state.value}: {phone.detail}" if phone.detail else phone.state.value diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index b5f9bec..696b98d 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -53,37 +53,6 @@ class Phone: status: str detail: str - @property - def state(self) -> str: - """Where the certificate is, in words an operator can act on - - The details matched are the ones seen on a live Fleet 4.90.1. A phone acts on a request at - its next check-in, every 15 minutes. After a failure a phone reports, Fleet asks again by - itself up to three times, and that request keeps the failure's detail while it waits. - """ - if not self.status: - return "no certificate requested" - if self.status == "verified": - return "has its certificate" - if self.status == "failed": - return self._failure - waiting = "requested, waiting for the phone (up to 15 minutes)" - return f"{waiting}; last time: {self._failure}" if self.detail else waiting - - @property - def _failure(self) -> str: - """What Fleet's detail on a failed request means""" - if "does not have an IDP user" in self.detail: - # Naming does not send the request again, so a name beside this detail was given without a resend - if self.callsign: - return "named, but its certificate was not asked for again: run resend" - return "waiting for a name" - if "SCEP enrollment failed" in self.detail: - return "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old challenge" - if "Network error" in self.detail: - return "could not reach Deploy App" - return self.detail or "failed" - def _moment(value: str) -> datetime.datetime: """A time Fleet wrote, as a time diff --git a/tests/test_console.py b/tests/test_console.py index 6f61e17..e201642 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -15,6 +15,7 @@ from odmdm_connector import config, console from odmdm_connector import fleet as fleet_module from odmdm_connector.console import cli_group +from odmdm_connector.fleet_plugin import FleetPlugin from .test_fleet import _Fleet, _host, _mdm @@ -30,9 +31,9 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: """ token = tmp_path / "token" token.write_text("token\n", encoding="utf-8") - monkeypatch.setattr(config, "URL", "https://mdm.test") - monkeypatch.setattr(config, "TOKEN_FILE", token) - monkeypatch.setattr(config, "TEAM", "rmscep") + monkeypatch.setenv("ODMDM_MDM_URL", "https://mdm.test") + monkeypatch.setenv("ODMDM_TOKEN_FILE", str(token)) + monkeypatch.setenv("ODMDM_TEAM", "rmscep") stub = _Fleet() stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": NAMED, "certificate_authority_id": 3}] stub.profiles = [ @@ -49,14 +50,14 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: @pytest.mark.parametrize("command", [["apply"], ["challenge", "--challenge", "new-window"]]) -def test_a_template_and_domain_are_required(command: list[str], monkeypatch: pytest.MonkeyPatch) -> None: - """Without them there is nothing to state to Fleet""" - monkeypatch.setattr(config, "TEMPLATE", None) +def test_a_domain_is_required(command: list[str], monkeypatch: pytest.MonkeyPatch) -> None: + """Without it there is nothing to state to Fleet; the template defaults to the one shipped""" + monkeypatch.setattr(config, "DOMAIN", "") result = CliRunner().invoke(cli_group, command) assert result.exit_code == 1 - assert "ODMDM_TEMPLATE" in result.output + assert "ODMDM_DOMAIN" in result.output def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -71,7 +72,7 @@ def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: ), encoding="utf-8", ) - monkeypatch.setattr(config, "TEMPLATE", path) + monkeypatch.setenv("ODMDM_TEMPLATE", str(path)) monkeypatch.setattr(config, "DOMAIN", "example.fi") @@ -115,7 +116,7 @@ def test_a_new_window_touches_only_the_authority( def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: """No Fleet configured is a sentence, not a traceback""" - monkeypatch.setattr(config, "URL", "") + monkeypatch.delenv("ODMDM_MDM_URL", raising=False) result = CliRunner().invoke(cli_group, ["phones"]) @@ -136,15 +137,35 @@ def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: [ ("", "", "no certificate requested"), ("failed", NO_NAME, "named, but its certificate was not asked for again: run resend"), - ("pending", "", "requested, waiting for the phone (up to 15 minutes)"), - ("delivering", "", "requested, waiting for the phone (up to 15 minutes)"), - ("delivered", "", "requested, waiting for the phone (up to 15 minutes)"), - ("pending", REFUSED, "requested, waiting for the phone (up to 15 minutes); last time: refused by Deploy App"), - ("delivered", UNREACHED, "waiting for the phone (up to 15 minutes); last time: could not reach Deploy App"), + ("pending", "", "requested, waiting for the phone: up to 15 minutes"), + ("delivering", "", "requested, waiting for the phone: up to 15 minutes"), + ("delivered", "", "requested, waiting for the phone: up to 15 minutes"), + ( + "pending", + REFUSED, + ( + "requested, waiting for the phone: up to 15 minutes; last time: refused by Deploy App: " + "name taken or not allowed, enrolment closed, or Fleet has an old challenge" + ), + ), + ( + "delivered", + UNREACHED, + "requested, waiting for the phone: up to 15 minutes; last time: could not reach Deploy App", + ), ("verified", "", "has its certificate"), - ("failed", REFUSED, "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old"), + ( + "failed", + REFUSED, + "refused by Deploy App: name taken or not allowed, enrolment closed, or Fleet has an old challenge", + ), ("failed", UNREACHED, "could not reach Deploy App"), - ("failed", "Something Fleet says that nobody has seen yet", "Something Fleet says that nobody has seen yet"), + ("failed", "", "failed"), + ( + "failed", + "Something Fleet says that nobody has seen yet", + "failed: Something Fleet says that nobody has seen yet", + ), ], ) def test_phones_says_where_each_certificate_is(fleet: _Fleet, status: str, detail: str, says: str) -> None: @@ -155,8 +176,7 @@ def test_phones_says_where_each_certificate_is(fleet: _Fleet, status: str, detai assert result.exit_code == 0, result.output assert result.output.split()[:4] == ["31", "OTTER4", "Google", "sdk_gphone64_arm64"] - assert "2026-11-01" in result.output - assert says in result.output + assert result.output.rstrip("\n").split("2026-11-01 ", 1)[1] == says def test_a_phone_fresh_from_enrolment_waits_for_a_name(fleet: _Fleet) -> None: @@ -305,10 +325,10 @@ def test_name_all_with_every_phone_named_names_nothing(fleet: _Fleet) -> None: (["31=OTTER-"], "OTTER-: a callsign is 3-32 letters"), (["--all", "O"], "O1: a callsign is 3-32 letters"), (["31=OTTER4", "32=otter4"], "otter4 is given twice"), - (["31=OTTER4", "31=OTTER5"], "host 31 is named twice"), - (["31=otter9"], "otter9 already belongs to host 33"), - (["--all", "OTTER", "--start", "9"], "OTTER9 already belongs to host 33"), - (["31=OTTER4", "99=OTTER5"], "host 99 is not in the team"), + (["31=OTTER4", "31=OTTER5"], "phone 31 is named twice"), + (["31=otter9"], "otter9 already belongs to phone 33"), + (["--all", "OTTER", "--start", "9"], "OTTER9 already belongs to phone 33"), + (["31=OTTER4", "99=OTTER5"], "phone 99 is not in the group"), ], ) def test_name_changes_nothing_unless_every_name_can_be_given(fleet: _Fleet, arguments: list[str], says: str) -> None: @@ -574,7 +594,7 @@ def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str]) def test_the_mdm_address_must_be_https(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: """The token goes with every request, so it must not cross the network readable""" - monkeypatch.setattr(config, "URL", "http://mdm.test") + monkeypatch.setenv("ODMDM_MDM_URL", "http://mdm.test") result = CliRunner().invoke(cli_group, ["phones"]) @@ -626,6 +646,48 @@ def refusing(request: httpx.Request) -> httpx.Response: assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: ""} +def test_a_rename_stopped_half_way_still_says_what_to_revoke(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """Nothing shows the old callsign afterwards, so its line must not be lost with the error""" + answer = fleet.handler + + def refusing(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/hosts/32/certificates/81/resend"): + return httpx.Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "verified", "OTTER3"), _host(32, "failed", detail=NO_NAME)] + + result = CliRunner().invoke(cli_group, ["name", "31=OTTER4", "32=OTTER5"]) + + assert result.exit_code == 1 + assert result.stdout.splitlines() == [ + "Host 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." + ] + assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.output + + +def test_a_resend_stopped_half_way_says_what_was_asked(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """The phones asked before the error are said as on success""" + answer = fleet.handler + + def refusing(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/hosts/34/certificates/81/resend"): + return httpx.Response(500, text="database is locked") + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", "OTTER31", REFUSED), _host(34, "failed", "OTTER34", REFUSED)] + + result = CliRunner().invoke(cli_group, ["resend"]) + + assert result.exit_code == 1 + assert result.stdout.splitlines() == ["Host 31 (OTTER31): certificate asked for again"] + assert "Fleet refused: POST /api/latest/fleet/hosts/34/certificates/81/resend answered 500" in result.output + + LINE = (Path(__file__).parent / "data" / "settings-line-v1.txt").read_text(encoding="utf-8").strip() SECRET = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret @@ -655,7 +717,7 @@ def test_challenge_takes_the_settings_line( assert result.exit_code == 0, result.output assert result.stdout.splitlines()[-1] == ( - "RMSCEP has the new challenge. The enrolment window is open until 2026-11-21 14:00 UTC" + "Fleet has the new challenge. The enrolment window is open until 2026-11-21 14:00 UTC" ) assert window.authorities[0]["challenge"] == SECRET assert window.authorities[0]["url"] == "https://unit.example.fi/scep" @@ -704,3 +766,75 @@ def test_apply_refuses_a_line_for_another_deployment(window: _Fleet, monkeypatch assert result.exit_code == 1 assert "is for other.example.fi" in result.output assert not window.calls + + +@pytest.mark.parametrize( + ("options", "env", "says"), + [ + (["--mdm", "nope"], {}, "No MDM named nope is installed"), + ([], {"ODMDM_MDM": "nope"}, "No MDM named nope is installed"), + (["--set", "nope=1"], {}, "fleet has no setting nope; it has key_alias, mdm_url, team, template, token"), + (["--set", "team"], {}, "--set takes KEY=VALUE"), + (["--set", f"token={SECRET}"], {}, "token is a secret: put it in a file and set ODMDM_TOKEN_FILE"), + ], +) +def test_the_mdm_and_its_settings_are_checked_first( + fleet: _Fleet, options: list[str], env: dict[str, str], says: str +) -> None: + """Before the MDM is asked anything, and without a value in the message""" + result = CliRunner().invoke(cli_group, [*options, "phones"], env=env) + + assert result.exit_code == 2 + assert says in result.output + assert SECRET not in result.output + assert not fleet.calls + + +def test_set_gives_an_mdm_setting(fleet: _Fleet) -> None: + """The same as the command's own shorthand, here --team""" + result = CliRunner().invoke(cli_group, ["--set", "team=Typo", "phones"]) + + assert result.exit_code == 1 + assert "no team named Typo" in result.output + + +def test_a_secret_is_never_read_from_a_plain_variable(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """Only from the file its _FILE variable names""" + monkeypatch.delenv("ODMDM_TOKEN_FILE") + + result = CliRunner().invoke(cli_group, ["phones"], env={"ODMDM_TOKEN": "token"}) + + assert result.exit_code == 1 + assert "Set ODMDM_TOKEN_FILE" in result.output + assert not fleet.calls + + +@pytest.mark.parametrize( + ("command", "capability"), + [(["challenge"], "set_challenge"), (["apply"], "setup"), (["resend"], "ask_again")], +) +def test_a_capability_the_mdm_lacks_is_its_sentence( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str], capability: str +) -> None: + """Said instead of calling the MDM, and before a challenge is asked for""" + _template(tmp_path, monkeypatch) + monkeypatch.setattr(FleetPlugin, "missing", {capability: "Paste the challenge in the MDM's console by hand"}) + + result = CliRunner().invoke(cli_group, command) + + assert result.exit_code == 1 + assert result.output == "Paste the challenge in the MDM's console by hand\n" + assert not fleet.calls + + +def test_a_dry_run_needs_no_mdm(monkeypatch: pytest.MonkeyPatch) -> None: + """The template shipped with the connector, checked with nothing configured but the domain""" + for setting in ("MDM_URL", "TOKEN_FILE", "TEMPLATE"): + monkeypatch.delenv(f"ODMDM_{setting}", raising=False) + monkeypatch.setattr(config, "DOMAIN", "example.fi") + + result = CliRunner().invoke(cli_group, ["apply", "--dry-run"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines()[0] == "Template names 3 apps, 3 installed at enrolment" + assert result.stdout.splitlines()[-1] == " launcher link 'Deploy App' -> https://mtls.example.fi/" diff --git a/tests/test_core.py b/tests/test_core.py index c664342..7212173 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -33,11 +33,11 @@ def test_numbering_goes_on_from_the_highest_in_use() -> None: ("wanted", "says"), [ ([("a", "OTTER4")], ""), - ([("x", "OTTER4")], "host x is not in the team"), - ([("a", "OTTER4"), ("a", "OTTER5")], "host a is named twice"), + ([("x", "OTTER4")], "phone x is not in the group"), + ([("a", "OTTER4"), ("a", "OTTER5")], "phone a is named twice"), ([("a", "-OTTER")], "-OTTER: a callsign is 3-32 letters"), ([("a", "OTTER4"), ("b", "otter4")], "otter4 is given twice"), - ([("a", "otter9")], "otter9 already belongs to host c"), + ([("a", "otter9")], "otter9 already belongs to phone c"), ([("c", "otter9")], ""), ], ) From 7ca84f614cccf591891b32a6045afc81320262c5 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:36:51 +0200 Subject: [PATCH 039/104] docs: the MDM contract's layout, --set and where the token is read --- AGENTS.md | 20 +++++++++++++++++--- README.rst | 7 +++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 33dc6b6..21967ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,18 @@ Fleet. Keep it that way in both directions: needs handling is handled here. - No product knowledge in code. What a deployment installs arrives in the template. +## Layout + +The command line knows an MDM only through one contract; Fleet is the plugin built in. + +- `src/odmdm_connector/mdm.py`: the contract (`Mdm`, `Phone`, `State`, `Field`, `Step`, `MdmError`), + standard library only. +- `core.py`: the naming rules, the same for every MDM. `console.py`: the command line. Neither + imports anything from `fleet.py` or `fleet_plugin.py`: the command line loads the MDM chosen with + `--mdm` through the entry point group `odmdm_connector.mdm`. +- `fleet_plugin.py`: Fleet behind the contract, registered in `pyproject.toml` as `fleet`. `fleet.py`: + Fleet's HTTP dialect. `template.py` and the shipped `template.json`: what a deployment's phones need. + ## Facts measured against a live Fleet Comments in `fleet.py` say what each request shape and wait was measured against. Keep that habit: @@ -36,9 +48,11 @@ strands every enrolled phone's key. ## Crown jewels - **The MDM API token** (today a Fleet global admin token): it can change what every enrolled - phone of every team installs and trusts. The only place that reads it is `_fleet` in - `src/odmdm_connector/console.py`, from the file `ODMDM_TOKEN_FILE` names; `FleetMdm` keeps it in - memory and sends it only as the `Authorization` header to the MDM URL. + phone of every team installs and trusts. The only place that reads it is `_values` in + `src/odmdm_connector/console.py`, from the file `ODMDM_TOKEN_FILE` names: a plugin field marked + secret is read only from the file `ODMDM__FILE` names, never from `--set` or a plain variable. + The chosen plugin gets it in memory; `FleetPlugin` hands it to `FleetMdm`, which sends it only as + the `Authorization` header to the MDM URL. - The tool never logs it, prints it, takes it as an option or argument, or writes it to a file. Keep it that way: no `--token` option, no token in an environment variable, no token in an error message. `.gitignore` ignores `*.token` so a token file in the checkout cannot be committed. diff --git a/README.rst b/README.rst index 827c881..e29f75c 100644 --- a/README.rst +++ b/README.rst @@ -90,7 +90,10 @@ revoke. Configuration ------------- -All configuration is via environment variables: +All configuration is via environment variables. ``--set KEY=VALUE`` before the command sets one +of the MDM's own for one run, ``mdm_url``, ``team``, ``template`` or ``key_alias`` for Fleet, as +does ``--mdm-url``, ``--team`` or ``--template`` after it. A secret, the token, is only ever read +from the file its ``_FILE`` variable names: ``ODMDM_MDM_URL`` Base URL of Fleet's API. Only https: the token goes with every request. @@ -105,7 +108,7 @@ All configuration is via environment variables: The team phones enrol into and get the certificate in. Default ``Deploy App``. ``ODMDM_TEMPLATE`` - The document saying what to install, see below. + The document saying what to install, see below. Default: the one shipped with the connector. ``ODMDM_DOMAIN`` The deployment's DNS name. From 5eaed7c37b7b3a68db562d072889983cf30eeadd Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:40:32 +0200 Subject: [PATCH 040/104] feat: find MDM plugins through their entry points --- src/odmdm_connector/plugins.py | 99 ++++++++++++++++++++++++++++++++++ tests/test_plugins.py | 95 ++++++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 src/odmdm_connector/plugins.py create mode 100644 tests/test_plugins.py diff --git a/src/odmdm_connector/plugins.py b/src/odmdm_connector/plugins.py new file mode 100644 index 0000000..5ac52c2 --- /dev/null +++ b/src/odmdm_connector/plugins.py @@ -0,0 +1,99 @@ +"""The MDM plugins installed, found through the entry point group odmdm_connector.mdm + +Fleet is registered there by this package, exactly as a plugin from another package is. Listing +imports nothing; loading imports the one entry point chosen and no other, because a plugin is code +that sees the MDM token. +""" + +import re +from dataclasses import dataclass, field +from importlib.metadata import EntryPoint, entry_points + +from .mdm import API_VERSION, Mdm + +GROUP = "odmdm_connector.mdm" +#: The distribution whose plugins are built in +CONNECTOR = "odmdm-connector" +#: What a plugin class declares besides its API_VERSION, read before any instance is made +DECLARED = ("title", "fields", "missing") + + +class PluginError(Exception): + """An installed plugin the connector cannot use, said in a sentence for the operator""" + + +class NotInstalled(PluginError): + """No plugin of that name is installed""" + + +@dataclass(frozen=True) +class Plugin: + """One installed MDM plugin, as its package declares it""" + + name: str + #: The distribution that declares it, and its version + package: str + version: str + entry: EntryPoint = field(repr=False, compare=False) + + @property + def built_in(self) -> bool: + """Whether it comes with the connector itself""" + return re.sub(r"[-_.]+", "-", self.package).lower() == CONNECTOR + + +def _declared() -> list[Plugin]: + """Every entry point of the group, without importing any; tests replace this""" + return [ + Plugin(entry.name, entry.dist.name if entry.dist else "", entry.dist.version if entry.dist else "", entry) + for entry in entry_points(group=GROUP) + ] + + +def installed() -> list[Plugin]: + """The installed plugins, the built-in ones first; PluginError when two packages claim one name""" + found: dict[str, Plugin] = {} + for plugin in _declared(): + other = found.get(plugin.name) + if other: + raise PluginError( + f"Two packages declare the MDM {plugin.name}: {other.package} {other.version} and " + f"{plugin.package} {plugin.version}. Uninstall one" + ) + found[plugin.name] = plugin + return sorted(found.values(), key=lambda plugin: (not plugin.built_in, plugin.name)) + + +def find(name: str) -> Plugin: + """The installed plugin of that name, not imported; NotInstalled if there is none""" + for plugin in installed(): + if plugin.name == name: + return plugin + raise NotInstalled(f"No MDM named {name} is installed") + + +def load(name: str) -> type[Mdm]: + """The class of the MDM of that name, importing that one entry point and no other + + PluginError when it cannot be imported, speaks another version of the contract, or does not + declare its title, fields and missing. + """ + plugin = find(name) + try: + loaded = plugin.entry.load() + except (ImportError, AttributeError) as exc: + raise PluginError(f"The MDM {name} from {plugin.package} {plugin.version} cannot be loaded: {exc}") from exc + version = getattr(loaded, "API_VERSION", None) + if version != API_VERSION: + raise PluginError( + f"The MDM {name} from {plugin.package} {plugin.version} needs a connector that speaks MDM API " + f"version {version}; this one speaks version {API_VERSION}" + ) + lacking = [attribute for attribute in DECLARED if not hasattr(loaded, attribute)] + if lacking: + raise PluginError( + f"The MDM {name} from {plugin.package} {plugin.version} does not declare {', '.join(lacking)}, " + "so it cannot be used" + ) + chosen: type[Mdm] = loaded + return chosen diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000..bd96917 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,95 @@ +"""Finding MDM plugins through their entry points""" + +from importlib.metadata import EntryPoint + +import pytest + +from odmdm_connector import plugins +from odmdm_connector.fleet_plugin import FleetPlugin + +#: A module that does not exist, so importing it fails the test that does +NEVER = "odmdm_connector_never_imported:Mdm" + + +class Old: + """A plugin written for another version of the contract""" + + API_VERSION = 2 + + +class Bare: + """A plugin that speaks the contract's version and declares nothing else""" + + API_VERSION = 1 + + +def _plugin(name: str, value: str, package: str = "odmdm-connector-demo", version: str = "1.0.0") -> plugins.Plugin: + return plugins.Plugin(name, package, version, EntryPoint(name, value, plugins.GROUP)) + + +@pytest.fixture +def declared(monkeypatch: pytest.MonkeyPatch) -> list[plugins.Plugin]: + """The entry points the plugins module sees, whatever is installed""" + found: list[plugins.Plugin] = [] + monkeypatch.setattr(plugins, "_declared", lambda: found) + return found + + +def test_fleet_is_registered_as_a_plugin_would_be() -> None: + """Through the package's own entry point, read from the installed metadata""" + fleet = plugins.find("fleet") + + assert (fleet.package, fleet.built_in) == ("odmdm-connector", True) + assert plugins.load("fleet") is FleetPlugin + + +def test_listing_imports_no_plugin(declared: list[plugins.Plugin]) -> None: + """Built-in first, then by name""" + declared += [_plugin("zeta", NEVER), _plugin("demo", NEVER), _plugin("fleet", NEVER, "odmdm_connector", "1.1.0")] + + found = plugins.installed() + + assert [(p.name, p.built_in) for p in found] == [("fleet", True), ("demo", False), ("zeta", False)] + + +def test_loading_imports_only_the_one_chosen(declared: list[plugins.Plugin]) -> None: + declared += [_plugin("demo", NEVER), _plugin("fleet", "odmdm_connector.fleet_plugin:FleetPlugin")] + + assert plugins.load("fleet") is FleetPlugin + with pytest.raises(plugins.PluginError, match="The MDM demo from odmdm-connector-demo 1.0.0 cannot be loaded"): + plugins.load("demo") + + +def test_two_packages_claiming_one_name_are_both_named(declared: list[plugins.Plugin]) -> None: + declared += [_plugin("demo", NEVER), _plugin("demo", NEVER, "odmdm-connector-other", "2.0.0")] + + for call in (plugins.installed, lambda: plugins.load("demo")): + with pytest.raises(plugins.PluginError) as raised: + call() + assert "odmdm-connector-demo 1.0.0 and odmdm-connector-other 2.0.0" in str(raised.value) + + +def test_another_contract_version_is_refused(declared: list[plugins.Plugin]) -> None: + declared.append(_plugin("old", "tests.test_plugins:Old")) + + with pytest.raises( + plugins.PluginError, match="needs a connector that speaks MDM API version 2; this one speaks version 1" + ): + plugins.load("old") + + +def test_an_unknown_name_is_not_installed(declared: list[plugins.Plugin]) -> None: + with pytest.raises(plugins.NotInstalled, match="No MDM named nope is installed"): + plugins.load("nope") + + +def test_a_class_declaring_too_little_is_refused(declared: list[plugins.Plugin]) -> None: + """Said before anything reads its title, fields or missing""" + declared.append(_plugin("bare", "tests.test_plugins:Bare")) + + with pytest.raises(plugins.PluginError) as raised: + plugins.load("bare") + + assert str(raised.value) == ( + "The MDM bare from odmdm-connector-demo 1.0.0 does not declare title, fields, missing, so it cannot be used" + ) From 6eacd7eef8e91b56c62b6413618dd6254427d77b Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:42:29 +0200 Subject: [PATCH 041/104] feat: ship a test kit for MDM plugins --- src/odmdm_connector/mdm.py | 3 +- src/odmdm_connector/testing/__init__.py | 5 + src/odmdm_connector/testing/contract.py | 171 ++++++++++++++++++++++++ src/odmdm_connector/testing/fake.py | 107 +++++++++++++++ tests/test_testing.py | 138 +++++++++++++++++++ 5 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 src/odmdm_connector/testing/__init__.py create mode 100644 src/odmdm_connector/testing/contract.py create mode 100644 src/odmdm_connector/testing/fake.py create mode 100644 tests/test_testing.py diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py index fbc2088..e13daaa 100644 --- a/src/odmdm_connector/mdm.py +++ b/src/odmdm_connector/mdm.py @@ -98,7 +98,8 @@ class Mdm(Protocol): #: The MDM's name as an operator knows it title: ClassVar[str] fields: ClassVar[tuple[Field, ...]] - #: For each capability in CAPABILITIES this MDM lacks, what to tell the operator instead + #: For each capability in CAPABILITIES this MDM lacks, what to tell the operator instead. The + #: command line never calls a capability listed here; called anyway, it raises MdmError. missing: ClassVar[Mapping[str, str]] def __init__(self, values: Mapping[str, str]) -> None: diff --git a/src/odmdm_connector/testing/__init__.py b/src/odmdm_connector/testing/__init__.py new file mode 100644 index 0000000..63e0e40 --- /dev/null +++ b/src/odmdm_connector/testing/__init__.py @@ -0,0 +1,5 @@ +"""A kit for MDM plugin authors: FakeMdm to drive the command line, contract to check a plugin""" + +from .fake import FakeMdm + +__all__ = ["FakeMdm"] diff --git a/src/odmdm_connector/testing/contract.py b/src/odmdm_connector/testing/contract.py new file mode 100644 index 0000000..9f87f5f --- /dev/null +++ b/src/odmdm_connector/testing/contract.py @@ -0,0 +1,171 @@ +"""The checks every MDM plugin must pass, for its own tests + +Each check takes a factory and raises AssertionError saying what is wrong. With pytest:: + + import pytest + from odmdm_connector.testing import contract + + @pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) + def test_the_contract(check: contract.Check) -> None: + check(my_factory) + +The factory answers a configured MDM whose group holds at least two phones without a name. Given +refuse_after, that MDM refuses to name any phone after that many, as an MDM failing half-way +through a batch would. Plain asserts are not used, so the checks hold under python -O too. +""" + +import datetime +import re +from collections.abc import Callable +from typing import Protocol + +from ..mdm import API_VERSION, ASK_AGAIN, CAPABILITIES, SET_CHALLENGE, SETUP, Mdm, MdmError, Phone, State, Step +from ..settings import Settings + +#: An enrolment window to hand the MDM; the challenge is not a real one +WINDOW = Settings( + "https://unit.example.fi/scep", "contract-check-challenge", datetime.datetime(2099, 1, 1, tzinfo=datetime.UTC) +) +#: A key has to fit an environment variable name, ODMDM_ +KEY = re.compile(r"[a-z][a-z0-9_]*") + + +class Factory(Protocol): + """Makes the MDM under test""" + + def __call__(self, refuse_after: int | None = None) -> Mdm: ... + + +Check = Callable[[Factory], None] + + +def _require(condition: object, message: str) -> None: + if not condition: + raise AssertionError(message) + + +def _unnamed(mdm: Mdm) -> list[str]: + ids = [phone.id for phone in mdm.phones() if not phone.callsign] + _require(len(ids) >= 2, "the factory's MDM must hold at least two phones without a name") + return ids + + +def _lines(lines: list[str], call: str) -> None: + _require(isinstance(lines, list), f"{call} must answer a list of lines") + _require(all(isinstance(line, str) and line for line in lines), f"{call}'s lines must be non-empty strings") + + +def _raises(call: Callable[[], object], message: str) -> None: + try: + call() + except MdmError: + return + raise AssertionError(message) + + +def _lacking(mdm: Mdm, capability: str, call: Callable[[], object]) -> bool: + """Whether the MDM lacks the capability, having checked that calling it then raises its sentence""" + if capability not in mdm.missing: + return False + try: + call() + except MdmError as exc: + _require(str(exc) == mdm.missing[capability], f"{capability}, lacking, must raise MdmError with its sentence") + return True + raise AssertionError(f"{capability} is listed as missing but did not raise MdmError") + + +def declares_the_contract_version(factory: Factory) -> None: + mdm = factory() + _require(mdm.API_VERSION == API_VERSION, f"API_VERSION must be {API_VERSION}") + _require(isinstance(mdm.title, str) and mdm.title, "title must be the MDM's name") + + +def declares_its_fields(factory: Factory) -> None: + fields = factory().fields + _require(isinstance(fields, tuple), "fields must be a tuple of Field") + keys = [item.key for item in fields] + labels = [item.label for item in fields] + _require(all(KEY.fullmatch(key) for key in keys), "a field's key is lower case letters, digits and _") + _require(len(set(keys)) == len(keys), "field keys must be unique") + _require(all(labels) and len(set(labels)) == len(labels), "field labels must be given and unique") + + +def says_what_it_lacks(factory: Factory) -> None: + missing = factory().missing + _require(set(missing) <= set(CAPABILITIES), f"missing names only capabilities among {', '.join(CAPABILITIES)}") + _require(all(isinstance(text, str) and text for text in missing.values()), "each lacking capability has a sentence") + + +def lists_its_phones(factory: Factory) -> None: + found = factory().phones() + _require(isinstance(found, list), "phones must answer a list") + for phone in found: + _require(isinstance(phone, Phone), "phones must answer Phone objects") + _require(isinstance(phone.id, str) and phone.id, "a phone's id is a non-empty string") + _require(isinstance(phone.state, State), "a phone's state is a State") + _require(isinstance(phone.callsign, str) and isinstance(phone.detail, str), "callsign and detail are strings") + try: + datetime.datetime.fromisoformat(phone.joined) + except ValueError as exc: + raise AssertionError(f"phone {phone.id} joined {phone.joined!r}, not an ISO time") from exc + + +def names_phones(factory: Factory) -> None: + mdm = factory() + first = _unnamed(mdm)[0] + _lines(mdm.name({first: "CONTRACT1"}), "name") + callsigns = {phone.id: phone.callsign for phone in mdm.phones()} + _require(callsigns.get(first) == "CONTRACT1", "a phone named must show its callsign in phones") + + +def refuses_an_unknown_id(factory: Factory) -> None: + mdm = factory() + before = mdm.phones() + _raises(lambda: mdm.name({"no-such-phone": "CONTRACT9"}), "name of an id not in the group must raise MdmError") + _raises(lambda: mdm.ask_again(["no-such-phone"]), "ask_again of an id not in the group must raise MdmError") + _require(mdm.phones() == before, "an id not in the group must change nothing") + + +def says_what_a_batch_stopped_half_way_named(factory: Factory) -> None: + mdm = factory(refuse_after=1) + first, second = _unnamed(mdm)[:2] + try: + mdm.name({first: "CONTRACT1", second: "CONTRACT2"}) + except MdmError as exc: + _require(exc.named == {first: "CONTRACT1"}, f"MdmError.named must be the phones named, not {exc.named}") + return + raise AssertionError("name must raise MdmError when the MDM refuses a phone half-way") + + +def asks_again(factory: Factory) -> None: + mdm = factory() + if not _lacking(mdm, ASK_AGAIN, lambda: mdm.ask_again([])): + _lines(mdm.ask_again([]), "ask_again") + + +def sets_the_challenge(factory: Factory) -> None: + mdm = factory() + if not _lacking(mdm, SET_CHALLENGE, lambda: mdm.set_challenge(WINDOW)): + mdm.set_challenge(WINDOW) + + +def sets_up(factory: Factory) -> None: + mdm = factory() + if not _lacking(mdm, SETUP, lambda: list(mdm.setup(WINDOW, dry_run=True))): + steps = list(mdm.setup(WINDOW, dry_run=True)) + _require(steps and all(isinstance(step, Step) for step in steps), "setup must report Steps") + + +CHECKS: tuple[Check, ...] = ( + declares_the_contract_version, + declares_its_fields, + says_what_it_lacks, + lists_its_phones, + names_phones, + refuses_an_unknown_id, + says_what_a_batch_stopped_half_way_named, + asks_again, + sets_the_challenge, + sets_up, +) diff --git a/src/odmdm_connector/testing/fake.py b/src/odmdm_connector/testing/fake.py new file mode 100644 index 0000000..97855f7 --- /dev/null +++ b/src/odmdm_connector/testing/fake.py @@ -0,0 +1,107 @@ +"""FakeMdm: an MDM in memory, implementing the whole contract, for tests""" + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace +from typing import ClassVar + +from ..mdm import API_VERSION, ASK_AGAIN, SET_CHALLENGE, SETUP, Field, MdmError, Phone, State, Step +from ..settings import Settings + +#: The group's phones when a test gives none: two waiting for a name, one with its certificate +PHONES = ( + Phone("a1", "", "Pretend Phone 7", "2026-11-01T09:00:00+00:00", State.NEEDS_NAME), + Phone("a2", "", "Pretend Phone 7", "2026-11-01T09:05:00+00:00", State.NEEDS_NAME), + Phone("a3", "OTTER1", "Pretend Tablet 2", "2026-11-01T09:10:00+00:00", State.READY), +) + +#: The states ask_again without ids picks, as the contract says +AGAIN = (State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +class FakeMdm: + """An MDM whose group is a list in memory + + calls records what it was asked, by method name. refuse_after makes name refuse the phone + after that many were named, as an MDM failing half-way through a batch does. lacking() gives a + class without some capabilities. + """ + + API_VERSION: ClassVar[int] = API_VERSION + title: ClassVar[str] = "Fake MDM" + fields: ClassVar[tuple[Field, ...]] = ( + Field("group", "Group", default="Deploy App", help="The group phones enrol into"), + Field("password", "Password", secret=True, help="Read from the file ODMDM_PASSWORD_FILE names"), + ) + missing: ClassVar[Mapping[str, str]] = {} + + def __init__( + self, values: Mapping[str, str], phones: Sequence[Phone] = PHONES, refuse_after: int | None = None + ) -> None: + self.values = dict(values) + self.group = list(phones) + self.refuse_after = refuse_after + self.calls: list[str] = [] + #: The challenge last given, kept so a test can see it arrived + self.challenge = "" + + @classmethod + def lacking(cls, *capabilities: str) -> type["FakeMdm"]: + """A FakeMdm class without these capabilities, each with a sentence saying so""" + missing = {capability: f"The fake MDM cannot {capability}" for capability in capabilities} + return type("LackingFakeMdm", (cls,), {"missing": missing}) + + def _able(self, capability: str) -> None: + self.calls.append(capability) + if capability in self.missing: + raise MdmError(self.missing[capability]) + + def _ids(self, ids: Sequence[str]) -> None: + known = {phone.id for phone in self.group} + unknown = [phone for phone in ids if phone not in known] + if unknown: + raise MdmError(f"Phone {unknown[0]} is not in the group") + + def _waiting(self, phone: str, callsign: str | None = None) -> None: + """The phone, under its new callsign if given, now waits for its certificate""" + self.group = [ + replace(each, callsign=each.callsign if callsign is None else callsign, state=State.WAITING) + if each.id == phone + else each + for each in self.group + ] + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + self._able(SETUP) + yield Step(f"Group {self.values.get('group', 'Deploy App')} enrols at {window.scep_url}", True) + if dry_run: + return + yield Step("Certificate template stated", True, "forced" if force else "") + + def set_challenge(self, window: Settings) -> None: + self._able(SET_CHALLENGE) + self.challenge = window.challenge + + def phones(self) -> list[Phone]: + self.calls.append("phones") + return list(self.group) + + def name(self, names: Mapping[str, str]) -> list[str]: + self.calls.append("name") + self._ids(list(names)) + named: dict[str, str] = {} + lines: list[str] = [] + for phone, callsign in names.items(): + if self.refuse_after is not None and len(named) >= self.refuse_after: + raise MdmError(f"The fake MDM refused phone {phone}", named, lines) + self._waiting(phone, callsign) + named[phone] = callsign + lines.append(f"Phone {phone} is {callsign}") + return lines + + def ask_again(self, ids: Sequence[str]) -> list[str]: + self._able(ASK_AGAIN) + self._ids(ids) + again = list(ids) or [phone.id for phone in self.group if phone.callsign and phone.state in AGAIN] + for phone in again: + self._waiting(phone) + return [f"Phone {phone}: certificate asked for again" for phone in again] diff --git a/tests/test_testing.py b/tests/test_testing.py new file mode 100644 index 0000000..0219d0c --- /dev/null +++ b/tests/test_testing.py @@ -0,0 +1,138 @@ +"""The plugin authors' test kit, run against the fake and against Fleet over the stub""" + +from collections.abc import Mapping, Sequence +from typing import ClassVar + +import httpx +import pytest + +from odmdm_connector.fleet_plugin import FleetPlugin +from odmdm_connector.mdm import CAPABILITIES, Mdm, MdmError, Phone, State +from odmdm_connector.testing import FakeMdm, contract + +from .test_fleet import _Fleet, _host, _mdm + +NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" +CHECKS = pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) + + +def _fake(refuse_after: int | None = None) -> Mdm: + return FakeMdm({}, refuse_after=refuse_after) + + +def _lacking(refuse_after: int | None = None) -> Mdm: + return FakeMdm.lacking(*CAPABILITIES)({}, refuse_after=refuse_after) + + +@pytest.fixture +def fleet(monkeypatch: pytest.MonkeyPatch) -> contract.Factory: + """Fleet over the stub, two phones waiting for a name and one with its certificate""" + + def factory(refuse_after: int | None = None) -> Mdm: + stub = _Fleet() + stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$X", "certificate_authority_id": 3}] + stub.hosts = [ + _host(31, "failed", detail=NO_NAME), + _host(32, "failed", detail=NO_NAME), + _host(33, "verified", "A"), + ] + answer = stub.handler + named: list[str] = [] + + def refusing(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/device_mapping"): + if refuse_after is not None and len(named) >= refuse_after: + return httpx.Response(500, text="database is locked") + named.append(request.url.path) + return answer(request) + + stub.handler = refusing # type: ignore[method-assign] + _mdm(stub, monkeypatch) + return FleetPlugin({"mdm_url": "https://mdm.test", "token": "token", "team": "rmscep"}) + + return factory + + +@CHECKS +def test_the_fake_keeps_the_contract(check: contract.Check) -> None: + check(_fake) + + +@CHECKS +def test_a_fake_lacking_every_capability_keeps_the_contract(check: contract.Check) -> None: + check(_lacking) + + +@CHECKS +def test_fleet_keeps_the_contract(check: contract.Check, fleet: contract.Factory) -> None: + check(fleet) + + +class _Careless(FakeMdm): + """Breaks the contract in every way a check looks for""" + + API_VERSION = 2 + title = "" + missing: ClassVar[Mapping[str, str]] = {"teleport": ""} + + def name(self, names: Mapping[str, str]) -> list[str]: + try: + return super().name(names) + except MdmError as exc: + raise MdmError(str(exc)) from exc + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return [""] + + +class _Lying(FakeMdm): + """Says it lacks asking again, then does it anyway""" + + missing: ClassVar[Mapping[str, str]] = {"ask_again": "Not here", "set_challenge": "Not here"} + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return [] + + def set_challenge(self, window: object) -> None: + raise MdmError("Something else") + + +@pytest.mark.parametrize( + ("factory", "check", "says"), + [ + (_Careless, contract.declares_the_contract_version, "API_VERSION must be 1"), + (_Careless, contract.says_what_it_lacks, "missing names only capabilities"), + (_Careless, contract.says_what_a_batch_stopped_half_way_named, "MdmError.named must be"), + (_Careless, contract.asks_again, "lines must be non-empty"), + (_Lying, contract.asks_again, "listed as missing but did not raise"), + (_Lying, contract.sets_the_challenge, "must raise MdmError with its sentence"), + ], +) +def test_a_plugin_breaking_the_contract_fails_its_check( + factory: type[FakeMdm], check: contract.Check, says: str +) -> None: + with pytest.raises(AssertionError, match=says): + check(lambda refuse_after=None: factory({}, refuse_after=refuse_after)) + + +def test_the_phones_a_check_needs() -> None: + """Times an operator can read, and enough phones to name""" + odd = [Phone("a1", "", "m", "yesterday", State.NEEDS_NAME)] + + with pytest.raises(AssertionError, match="not an ISO time"): + contract.lists_its_phones(lambda refuse_after=None: FakeMdm({}, odd)) + with pytest.raises(AssertionError, match="at least two phones without a name"): + contract.names_phones(lambda refuse_after=None: FakeMdm({}, odd)) + + +def test_a_name_that_does_not_stick_fails() -> None: + class Forgetful(FakeMdm): + def name(self, names: Mapping[str, str]) -> list[str]: + return ["Named"] + + with pytest.raises(AssertionError, match="must show its callsign"): + contract.names_phones(lambda refuse_after=None: Forgetful({})) + with pytest.raises(AssertionError, match="must raise MdmError when the MDM refuses"): + contract.says_what_a_batch_stopped_half_way_named(lambda refuse_after=None: Forgetful({})) + with pytest.raises(AssertionError, match="name of an id not in the group"): + contract.refuses_an_unknown_id(lambda refuse_after=None: Forgetful({})) From e208b4075cfff2dc6d0af8b63ce8ed642de9c7a1 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:43:13 +0200 Subject: [PATCH 042/104] feat: get the MDM only through plugins.load, list the installed ones with mdms --- src/odmdm_connector/console.py | 51 +++++++++++++++++------- src/odmdm_connector/plugins.py | 7 +++- tests/test_console.py | 73 +++++++++++++++++++++++++++++++++- tests/test_plugins.py | 13 +++++- 4 files changed, 125 insertions(+), 19 deletions(-) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 340faf5..be56e80 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -1,14 +1,14 @@ """CLI entrypoints for odmdm-connector -Knows the MDM only through the contract in mdm.py: the chosen MDM is the one entry point of the -group odmdm_connector.mdm named by --mdm, Fleet being the one built in. +Knows the MDM only through the contract in mdm.py, and gets it only through plugins.load: the +chosen MDM is the one entry point of the group odmdm_connector.mdm named by --mdm, Fleet being the +one built in. """ import datetime import logging import os from collections.abc import Mapping -from importlib.metadata import entry_points from pathlib import Path from typing import NoReturn from urllib.parse import urlparse @@ -18,15 +18,12 @@ from odmdm_connector import __version__ -from . import config, core, settings +from . import config, core, plugins, settings from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError from .settings import Settings LOGGER = logging.getLogger(__name__) -#: Where MDM plugins are found, the built-in one among them -GROUP = "odmdm_connector.mdm" - @click.group() @click.version_option(version=__version__) @@ -78,13 +75,20 @@ def _fail(ctx: click.Context, message: str) -> NoReturn: ctx.exit(1) -def _chosen(name: str) -> type[Mdm]: - """The class of the MDM of that name, loading that one entry point and no other""" - found = entry_points(group=GROUP, name=name) - if not found: - raise click.UsageError(f"No MDM named {name} is installed") - loaded: type[Mdm] = next(iter(found)).load() - return loaded +def _chosen(ctx: click.Context, name: str) -> type[Mdm]: + """The class of the MDM of that name, saying first whose code it is when it is not built in""" + try: + plugin = plugins.find(name) + if not plugin.built_in: + click.echo( + f"The MDM {name} is a plugin from {plugin.package} {plugin.version}: code that sees the MDM token", + err=True, + ) + return plugins.load(name) + except plugins.NotInstalled as exc: + raise click.UsageError(str(exc)) from exc + except plugins.PluginError as exc: + _fail(ctx, str(exc)) def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str]) -> dict[str, str]: @@ -116,7 +120,7 @@ def _mdm(ctx: click.Context, capability: str = "", **shorthands: str | None) -> The shorthands are the per-command options such as --team, each the same as --set team=... """ name = str(ctx.obj["mdm"]) - chosen = _chosen(name) + chosen = _chosen(ctx, name) if capability in chosen.missing: _fail(ctx, chosen.missing[capability]) given = {**ctx.obj["set"], **{key: value for key, value in shorthands.items() if value is not None}} @@ -365,3 +369,20 @@ def resend(ctx: click.Context, ids: tuple[str, ...], mdm_url: str | None, team: if not lines: click.echo("Nothing to resend") ctx.exit(0) + + +@cli_group.command(name="mdms") +@click.pass_context +def mdms(ctx: click.Context) -> None: + """List the MDMs installed: the name --mdm takes, the package and its version, built in or a plugin + + Lists them without loading any. A plugin is code that sees the MDM token: install only one you trust. + """ + try: + found = plugins.installed() + except plugins.PluginError as exc: + _fail(ctx, str(exc)) + for plugin in found: + kind = "built in" if plugin.built_in else "plugin" + click.echo(f"{plugin.name:<12} {plugin.package:<28} {plugin.version:<16} {kind}") + ctx.exit(0) diff --git a/src/odmdm_connector/plugins.py b/src/odmdm_connector/plugins.py index 5ac52c2..8eaae42 100644 --- a/src/odmdm_connector/plugins.py +++ b/src/odmdm_connector/plugins.py @@ -38,8 +38,11 @@ class Plugin: @property def built_in(self) -> bool: - """Whether it comes with the connector itself""" - return re.sub(r"[-_.]+", "-", self.package).lower() == CONNECTOR + """Whether it comes with the connector itself: declared by it, and code of its own package""" + module = self.entry.module + return re.sub(r"[-_.]+", "-", self.package).lower() == CONNECTOR and ( + module == __package__ or module.startswith(f"{__package__}.") + ) def _declared() -> list[Plugin]: diff --git a/tests/test_console.py b/tests/test_console.py index e201642..62f2f43 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -6,13 +6,14 @@ import datetime import json +from importlib.metadata import EntryPoint from pathlib import Path import httpx import pytest from click.testing import CliRunner -from odmdm_connector import config, console +from odmdm_connector import config, console, plugins from odmdm_connector import fleet as fleet_module from odmdm_connector.console import cli_group from odmdm_connector.fleet_plugin import FleetPlugin @@ -838,3 +839,73 @@ def test_a_dry_run_needs_no_mdm(monkeypatch: pytest.MonkeyPatch) -> None: assert result.exit_code == 0, result.output assert result.stdout.splitlines()[0] == "Template names 3 apps, 3 installed at enrolment" assert result.stdout.splitlines()[-1] == " launcher link 'Deploy App' -> https://mtls.example.fi/" + + +def _declare(monkeypatch: pytest.MonkeyPatch, *found: tuple[str, str, str]) -> None: + """These MDMs installed and no other, each as name, package and module:class""" + declared = [ + plugins.Plugin(name, package, "0.1.0", EntryPoint(name, value, plugins.GROUP)) for name, package, value in found + ] + monkeypatch.setattr(plugins, "_declared", lambda: declared) + + +FAKE = ("fake", "odmdm-connector-fake", "odmdm_connector.testing.fake:FakeMdm") + + +def test_mdms_lists_what_is_installed_without_loading_it(monkeypatch: pytest.MonkeyPatch) -> None: + _declare( + monkeypatch, + ("zeta", "odmdm-connector-zeta", "never_imported:Mdm"), + ("fleet", "odmdm-connector", "odmdm_connector.never_imported:Mdm"), + ) + + result = CliRunner().invoke(cli_group, ["mdms"]) + + assert result.exit_code == 0, result.output + assert [line.split() for line in result.stdout.splitlines()] == [ + ["fleet", "odmdm-connector", "0.1.0", "built", "in"], + ["zeta", "odmdm-connector-zeta", "0.1.0", "plugin"], + ] + + +def test_a_plugin_says_whose_code_it_is_before_it_runs(monkeypatch: pytest.MonkeyPatch) -> None: + """On stderr, so what the command prints stays the same""" + _declare(monkeypatch, FAKE) + + result = CliRunner().invoke(cli_group, ["--mdm", "fake", "phones"]) + + assert result.exit_code == 0, result.output + assert result.stderr == "The MDM fake is a plugin from odmdm-connector-fake 0.1.0: code that sees the MDM token\n" + assert [line.split()[:2] for line in result.stdout.splitlines()] == [["a1", "-"], ["a2", "-"], ["a3", "OTTER1"]] + + +def test_the_built_in_mdm_says_nothing_of_itself(fleet: _Fleet) -> None: + fleet.hosts = [_host(31)] + + result = CliRunner().invoke(cli_group, ["phones"]) + + assert result.exit_code == 0, result.output + assert not result.stderr + + +@pytest.mark.parametrize( + ("found", "command", "says"), + [ + ([FAKE, ("fake", "odmdm-connector-other", "never_imported:Mdm")], ["mdms"], "odmdm-connector-fake 0.1.0 and"), + ([FAKE, ("fake", "odmdm-connector-other", "never_imported:Mdm")], ["--mdm", "fake", "phones"], "Uninstall one"), + ( + [("old", "odmdm-connector-old", "tests.test_plugins:Old")], + ["--mdm", "old", "phones"], + "speaks MDM API version 2", + ), + ], +) +def test_a_plugin_the_connector_cannot_use_is_said( + monkeypatch: pytest.MonkeyPatch, found: list[tuple[str, str, str]], command: list[str], says: str +) -> None: + _declare(monkeypatch, *found) + + result = CliRunner().invoke(cli_group, command) + + assert result.exit_code == 1 + assert says in result.stderr diff --git a/tests/test_plugins.py b/tests/test_plugins.py index bd96917..3cddb7b 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -45,7 +45,11 @@ def test_fleet_is_registered_as_a_plugin_would_be() -> None: def test_listing_imports_no_plugin(declared: list[plugins.Plugin]) -> None: """Built-in first, then by name""" - declared += [_plugin("zeta", NEVER), _plugin("demo", NEVER), _plugin("fleet", NEVER, "odmdm_connector", "1.1.0")] + declared += [ + _plugin("zeta", NEVER), + _plugin("demo", NEVER), + _plugin("fleet", "odmdm_connector.never_imported:Mdm", "odmdm_connector", "1.1.0"), + ] found = plugins.installed() @@ -93,3 +97,10 @@ def test_a_class_declaring_too_little_is_refused(declared: list[plugins.Plugin]) assert str(raised.value) == ( "The MDM bare from odmdm-connector-demo 1.0.0 does not declare title, fields, missing, so it cannot be used" ) + + +def test_built_in_means_the_connectors_own_code_too() -> None: + """The connector's distribution name on an entry point outside its package is no proof""" + assert not _plugin("odd", NEVER, "odmdm-connector", "1.1.0").built_in + assert not _plugin("odd", "odmdm_connector_x.mdm:Mdm", "odmdm-connector", "1.1.0").built_in + assert _plugin("fleet", "odmdm_connector:Mdm", "odmdm-connector", "1.1.0").built_in From 64fe3faf794b4abbc2112466350efcd3d5fcd8d6 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:44:14 +0200 Subject: [PATCH 043/104] feat: add a demo MDM plugin as a package of its own --- .pre-commit-config.yaml | 4 +- examples/README.rst | 3 + examples/odmdm-connector-demo/README.rst | 19 +++++ examples/odmdm-connector-demo/pyproject.toml | 20 +++++ .../src/odmdm_connector_demo/__init__.py | 83 +++++++++++++++++++ .../tests/test_demo_contract.py | 16 ++++ pyproject.toml | 4 + 7 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 examples/odmdm-connector-demo/README.rst create mode 100644 examples/odmdm-connector-demo/pyproject.toml create mode 100644 examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py create mode 100644 examples/odmdm-connector-demo/tests/test_demo_contract.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 746c1e9..667e157 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -110,7 +110,7 @@ repos: # >>> END AUTOGENERATED SECTION - config-ci-library # Add any repo-specific hooks below this line - # Repo specific. The generated mypy hook only looks at src, and the tests are annotated too. + # Repo specific. The generated mypy hook only looks at src, and the tests and the demo plugin are annotated too. - repo: local hooks: - id: mypy-tests @@ -123,3 +123,5 @@ repos: - "--strict" - "--allow-untyped-decorators" - "tests" + - "examples/odmdm-connector-demo/src" + - "examples/odmdm-connector-demo/tests" diff --git a/examples/README.rst b/examples/README.rst index c158a08..cc4a6b8 100644 --- a/examples/README.rst +++ b/examples/README.rst @@ -4,3 +4,6 @@ Examples The example template moved into the package, so an installed connector carries it: ``src/odmdm_connector/template.json``. Copy it from there to change what a deployment installs. + +``odmdm-connector-demo/`` is a plugin, a package of its own: a pretend MDM to start a new plugin +from. See "Write a plugin" in the top-level README. diff --git a/examples/odmdm-connector-demo/README.rst b/examples/odmdm-connector-demo/README.rst new file mode 100644 index 0000000..a74b9ee --- /dev/null +++ b/examples/odmdm-connector-demo/README.rst @@ -0,0 +1,19 @@ +==================== +odmdm-connector-demo +==================== + +A pretend MDM for odmdm-connector, and the starting point for a plugin. Its three phones live in +memory, and it lacks one capability on purpose: it takes no challenge by API, so ``challenge`` +says where to paste one instead. + +Copy this folder, rename the package ``odmdm-connector-`` and the entry point, and replace +the list with calls to your MDM's API. ``tests/test_demo_contract.py`` runs the connector's +contract checks; keep it passing. + +Try it next to the connector:: + + uv build --out-dir dist + uv build --out-dir dist examples/odmdm-connector-demo + uv tool install dist/odmdm_connector-*.whl --with dist/odmdm_connector_demo-*.whl + odmdm-connector mdms + odmdm-connector --mdm demo phones diff --git a/examples/odmdm-connector-demo/pyproject.toml b/examples/odmdm-connector-demo/pyproject.toml new file mode 100644 index 0000000..a38dc3e --- /dev/null +++ b/examples/odmdm-connector-demo/pyproject.toml @@ -0,0 +1,20 @@ +[project] +name = "odmdm-connector-demo" +version = "1.0.0" +description = "A pretend MDM for odmdm-connector: the starting point for an MDM plugin" +license = "MIT" +readme = "README.rst" +requires-python = ">=3.11,<4.0" +dependencies = [ + "odmdm-connector>=1,<2", +] + +[project.entry-points."odmdm_connector.mdm"] +demo = "odmdm_connector_demo:DemoMdm" + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["src/odmdm_connector_demo"] diff --git a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py new file mode 100644 index 0000000..5488fab --- /dev/null +++ b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py @@ -0,0 +1,83 @@ +"""A pretend MDM for odmdm-connector, its phones in memory + +The starting point for a plugin: every method of the contract, odmdm_connector.mdm.Mdm, with +nothing behind it. A real plugin talks to its MDM's API where this changes a list. Each command +starts afresh, so a name given here is gone by the next command. +""" + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace +from typing import ClassVar + +from odmdm_connector.mdm import SET_CHALLENGE, Field, MdmError, Phone, State, Step +from odmdm_connector.settings import Settings + +#: The states ask_again without ids picks, as the contract says +AGAIN = (State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +class DemoMdm: + """A pretend MDM with three phones, which cannot be given a challenge by API""" + + # The contract version this plugin was written for + API_VERSION: ClassVar[int] = 1 + title: ClassVar[str] = "Demo MDM" + fields: ClassVar[tuple[Field, ...]] = ( + Field("group", "Group", default="Deploy App", help="The group phones enrol into"), + ) + missing: ClassVar[Mapping[str, str]] = { + SET_CHALLENGE: ( + "The demo MDM takes no challenge by API: paste it in its console under " + "Certificates > SCEP > Challenge, then run phones" + ), + } + + def __init__(self, values: Mapping[str, str], refuse_after: int | None = None) -> None: + """refuse_after: for tests, the pretend MDM refuses to name more phones than that""" + self.group = values.get("group") or "Deploy App" + self.refuse_after = refuse_after + self.found = [ + Phone("d1", "", "Pretend Phone 7", "2026-11-01T09:00:00+00:00", State.NEEDS_NAME), + Phone("d2", "", "Pretend Phone 7", "2026-11-01T09:05:00+00:00", State.NEEDS_NAME), + Phone("d3", "OTTER1", "Pretend Tablet 2", "2026-11-01T09:10:00+00:00", State.READY), + ] + + def _known(self, ids: Sequence[str]) -> None: + unknown = [phone for phone in ids if phone not in {each.id for each in self.found}] + if unknown: + raise MdmError(f"Phone {unknown[0]} is not in the group {self.group}") + + def _waiting(self, phone: str, callsign: str) -> None: + self.found = [ + replace(each, callsign=callsign, state=State.WAITING) if each.id == phone else each for each in self.found + ] + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step(f"Group {self.group} would enrol at {window.scep_url}", True) + if not dry_run: + yield Step("Certificate template stated", True) + + def set_challenge(self, window: Settings) -> None: + raise MdmError(self.missing[SET_CHALLENGE]) + + def phones(self) -> list[Phone]: + return list(self.found) + + def name(self, names: Mapping[str, str]) -> list[str]: + self._known(list(names)) + named: dict[str, str] = {} + lines: list[str] = [] + for phone, callsign in names.items(): + if self.refuse_after is not None and len(named) >= self.refuse_after: + raise MdmError(f"The demo MDM refused to name phone {phone}", named, lines) + self._waiting(phone, callsign) + named[phone] = callsign + lines.append(f"Phone {phone} is {callsign}") + return lines + + def ask_again(self, ids: Sequence[str]) -> list[str]: + self._known(ids) + again = [each for each in self.found if each.id in ids or (not ids and each.callsign and each.state in AGAIN)] + for each in again: + self._waiting(each.id, each.callsign) + return [f"Phone {each.id}: certificate asked for again" for each in again] diff --git a/examples/odmdm-connector-demo/tests/test_demo_contract.py b/examples/odmdm-connector-demo/tests/test_demo_contract.py new file mode 100644 index 0000000..e88a9fd --- /dev/null +++ b/examples/odmdm-connector-demo/tests/test_demo_contract.py @@ -0,0 +1,16 @@ +"""The demo keeps the contract every MDM plugin keeps""" + +import pytest +from odmdm_connector_demo import DemoMdm + +from odmdm_connector.mdm import Mdm +from odmdm_connector.testing import contract + + +def _demo(refuse_after: int | None = None) -> Mdm: + return DemoMdm({}, refuse_after=refuse_after) + + +@pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) +def test_the_demo_keeps_the_contract(check: contract.Check) -> None: + check(_demo) diff --git a/pyproject.toml b/pyproject.toml index fa57cec..4e5fc06 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,8 @@ target-version = "py311" [tool.mypy] strict=true +# The demo plugin's tests import it from its source, as pytest does +mypy_path="examples/odmdm-connector-demo/src" [[tool.mypy.overrides]] module="tests.*" @@ -59,6 +61,8 @@ disallow_untyped_decorators=false [tool.pytest.ini_options] junit_family="xunit2" +# The demo plugin, a package of its own, runs its contract tests here from its source +pythonpath=["examples/odmdm-connector-demo/src"] addopts="--cov=odmdm_connector --cov-fail-under=65 --cov-branch" [tool.coverage.run] From c915a60c37766a71a9ac1f6aadd82793bdf20127 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:45:12 +0200 Subject: [PATCH 044/104] build: forbid starting processes, eval and exec, and fail any test that starts one --- pyproject.toml | 42 +++++++++++++++++++++++++++++++++ tests/conftest.py | 48 ++++++++++++++++++++++++++++++++++++++ tests/test_no_processes.py | 22 +++++++++++++++++ 3 files changed, 112 insertions(+) create mode 100644 tests/conftest.py create mode 100644 tests/test_no_processes.py diff --git a/pyproject.toml b/pyproject.toml index 4e5fc06..e2e09fc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,6 +50,48 @@ packages = ["src/odmdm_connector"] line-length = 120 target-version = "py311" +[tool.ruff.lint] +# The connector holds a token that can reach every phone: it starts no process and runs no code +# it was given. S102 and S307 are exec and eval. +extend-select = ["TID251", "S102", "S307"] + +[tool.ruff.lint.per-file-ignores] +# The guard that makes those raise during the tests, and its test +"tests/conftest.py" = ["TID251"] +"tests/test_no_processes.py" = ["TID251"] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"subprocess".msg = "The connector starts no process" +"asyncio.create_subprocess_exec".msg = "The connector starts no process" +"asyncio.create_subprocess_shell".msg = "The connector starts no process" +"multiprocessing".msg = "The connector starts no process" +"pty".msg = "The connector starts no process" +"webbrowser".msg = "Opening a browser starts a process" +"os.system".msg = "The connector starts no process" +"os.popen".msg = "The connector starts no process" +"os.fork".msg = "The connector starts no process" +"os.forkpty".msg = "The connector starts no process" +"os.posix_spawn".msg = "The connector starts no process" +"os.posix_spawnp".msg = "The connector starts no process" +"os.startfile".msg = "The connector starts no process" +"os.execl".msg = "The connector starts no process" +"os.execle".msg = "The connector starts no process" +"os.execlp".msg = "The connector starts no process" +"os.execlpe".msg = "The connector starts no process" +"os.execv".msg = "The connector starts no process" +"os.execve".msg = "The connector starts no process" +"os.execvp".msg = "The connector starts no process" +"os.execvpe".msg = "The connector starts no process" +"os.spawnl".msg = "The connector starts no process" +"os.spawnle".msg = "The connector starts no process" +"os.spawnlp".msg = "The connector starts no process" +"os.spawnlpe".msg = "The connector starts no process" +"os.spawnv".msg = "The connector starts no process" +"os.spawnve".msg = "The connector starts no process" +"os.spawnvp".msg = "The connector starts no process" +"os.spawnvpe".msg = "The connector starts no process" +"importlib.import_module".msg = "Only plugins.load imports code, and only the chosen entry point" + [tool.mypy] strict=true # The demo plugin's tests import it from its source, as pytest does diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..18538b5 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,48 @@ +"""Guards for the whole test run""" + +import os +import subprocess +import sys +import webbrowser +from collections.abc import Iterator +from typing import NoReturn + +import pytest + +#: Every way the standard library starts a process, as module and function names. subprocess, +#: os.popen and webbrowser end in Popen._execute_child; multiprocessing in fork_exec or CreateProcess. +STARTERS: tuple[tuple[object, tuple[str, ...]], ...] = ( + (subprocess.Popen, ("_execute_child",)), + (sys.modules.get("_posixsubprocess"), ("fork_exec",)), + (sys.modules.get("_winapi"), ("CreateProcess",)), + (webbrowser, ("open", "open_new", "open_new_tab")), + ( + os, + ( + "system", + "popen", + "fork", + "forkpty", + "posix_spawn", + "posix_spawnp", + "startfile", + *(f"exec{suffix}" for suffix in ("l", "le", "lp", "lpe", "v", "ve", "vp", "vpe")), + *(f"spawn{suffix}" for suffix in ("l", "le", "lp", "lpe", "v", "ve", "vp", "vpe")), + ), + ), +) + + +def _refuse(*args: object, **kwargs: object) -> NoReturn: + raise RuntimeError("A test started a process, and the connector never starts one") + + +@pytest.fixture(autouse=True, scope="session") +def no_process_starts() -> Iterator[None]: + """A process started anywhere, by the connector or by a library, fails the test that did it""" + with pytest.MonkeyPatch.context() as patch: + for module, names in STARTERS: + for name in names: + if module is not None and hasattr(module, name): + patch.setattr(module, name, _refuse) + yield diff --git a/tests/test_no_processes.py b/tests/test_no_processes.py new file mode 100644 index 0000000..604e150 --- /dev/null +++ b/tests/test_no_processes.py @@ -0,0 +1,22 @@ +"""The connector starts no process, and the test run makes sure of it""" + +import os +import subprocess +import webbrowser +from collections.abc import Callable + +import pytest + + +@pytest.mark.parametrize( + "start", + [ + lambda: subprocess.run(["true"], check=False), + lambda: os.system("true"), + lambda: os.popen("true"), + lambda: webbrowser.open("https://example.fi"), + ], +) +def test_a_process_start_fails_the_test(start: Callable[[], object]) -> None: + with pytest.raises(RuntimeError, match="started a process"): + start() From 69a19d80f134996dd7fe0c9caf7106f636247b73 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:45:52 +0200 Subject: [PATCH 045/104] ci: install the connector with the demo plugin on every OS and use it --- .github/workflows/pull_request.yml | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index fae683b..c562997 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -46,6 +46,42 @@ jobs: - name: Test with pytest, coverage floor in pyproject.toml run: uv run pytest -v + # A plugin is a package of its own, found through its entry point once installed: build both + # wheels and install them the way an operator would, into a throwaway tool directory. + plugin-install: + name: Install with a plugin (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - name: Build both wheels and install them as a tool + env: + UV_TOOL_DIR: ${{ runner.temp }}/uv-tools + UV_TOOL_BIN_DIR: ${{ runner.temp }}/uv-bin + run: | + uv build --out-dir dist + uv build --out-dir dist examples/odmdm-connector-demo + uv tool install dist/odmdm_connector-*.whl --with dist/odmdm_connector_demo-*.whl + echo "$UV_TOOL_BIN_DIR" >> "$GITHUB_PATH" + - name: Fleet is built in, the demo is found as a plugin and used + run: | + odmdm-connector mdms | tr -d '\r' | tr -s ' ' | tee mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' mdms.txt + grep -Fqx 'demo odmdm-connector-demo 1.0.0 plugin' mdms.txt + odmdm-connector --mdm demo phones 2> plugin.txt | tee phones.txt + cat plugin.txt + grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' plugin.txt + grep -Eq '^d1 +- +Pretend Phone 7' phones.txt + snyk-test: name: Run Snyk test runs-on: ubuntu-latest From 35846a7b829232eef04b674572e80fc02b2e28aa Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:46:25 +0200 Subject: [PATCH 046/104] docs: say how to add, choose and write an MDM plugin --- AGENTS.md | 20 +++++-- README.rst | 57 ++++++++++++++++++++ examples/odmdm-connector-demo/pyproject.toml | 2 +- 3 files changed, 75 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 21967ec..4a33510 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,11 +20,24 @@ The command line knows an MDM only through one contract; Fleet is the plugin bui - `src/odmdm_connector/mdm.py`: the contract (`Mdm`, `Phone`, `State`, `Field`, `Step`, `MdmError`), standard library only. - `core.py`: the naming rules, the same for every MDM. `console.py`: the command line. Neither - imports anything from `fleet.py` or `fleet_plugin.py`: the command line loads the MDM chosen with - `--mdm` through the entry point group `odmdm_connector.mdm`. + imports anything from `fleet.py` or `fleet_plugin.py`: the command line gets the MDM chosen with + `--mdm` only through `plugins.load`. +- `plugins.py`: lists the entry point group `odmdm_connector.mdm` without importing anything, and + imports only the one entry point chosen. It is the only dynamic import there is. +- `testing/`: the kit for plugin authors, shipped in the package: `FakeMdm` and `contract.CHECKS`. + The repository runs the checks against the fake, Fleet over the stub, and the demo. +- `examples/odmdm-connector-demo/`: a plugin as a package of its own. CI builds it and the + connector and installs both as an operator would. - `fleet_plugin.py`: Fleet behind the contract, registered in `pyproject.toml` as `fleet`. `fleet.py`: Fleet's HTTP dialect. `template.py` and the shipped `template.json`: what a deployment's phones need. +## No processes + +The connector starts no process and runs no code it was given: ruff bans `subprocess`, the +`os.system`/`popen`/`exec*`/`spawn*` family, `webbrowser`, `eval` and `exec`, and +`tests/conftest.py` makes every way to start a process raise for the whole test run. A missing +feature is not a reason to shell out. + ## Facts measured against a live Fleet Comments in `fleet.py` say what each request shape and wait was measured against. Keep that habit: @@ -52,7 +65,8 @@ strands every enrolled phone's key. `src/odmdm_connector/console.py`, from the file `ODMDM_TOKEN_FILE` names: a plugin field marked secret is read only from the file `ODMDM__FILE` names, never from `--set` or a plain variable. The chosen plugin gets it in memory; `FleetPlugin` hands it to `FleetMdm`, which sends it only as - the `Authorization` header to the MDM URL. + the `Authorization` header to the MDM URL. A plugin from another package sees it too, so the + command line names that package on stderr before loading it. - The tool never logs it, prints it, takes it as an option or argument, or writes it to a file. Keep it that way: no `--token` option, no token in an environment variable, no token in an error message. `.gitignore` ignores `*.token` so a token file in the checkout cannot be committed. diff --git a/README.rst b/README.rst index e29f75c..5adc295 100644 --- a/README.rst +++ b/README.rst @@ -78,6 +78,7 @@ Commands odmdm-connector name 31=OTTER4 32=OTTER5 # name these phones, and Fleet sends their certificates odmdm-connector name --all OTTER # the same for every phone without a name, numbered odmdm-connector resend [HOST_ID ...] # ask again; without ids, every named phone that failed + odmdm-connector mdms # the MDMs installed: fleet built in, and any plugins ``name --all`` numbers in enrolment order from one above the highest ``OTTER`` in the team, or from ``--start N``, 1 or more. It sees only this team's phones, and Deploy App never gives a @@ -122,6 +123,28 @@ from the file its ``_FILE`` variable names: what the first deployments were set up with. Never change it for a deployment: a second key will not install over an existing alias. +Plugins +------- + +Fleet is built in. Another MDM comes as a plugin: a Python package of its own, named +``odmdm-connector-``, that the connector finds once it is installed beside it. A plugin is +code that sees the MDM token, so installing one means trusting it as much as the connector +itself. Install only one you know the source of. When the MDM chosen is a plugin, every command +says on stderr which package and version it comes from. + +Add one with the same install line and ``--with``:: + + uv tool install git+https://github.com/pvarki/python-odmdm-fleet --with odmdm-connector- + +See what is installed, without loading any of it:: + + odmdm-connector mdms + +Choose one with ``--mdm NAME`` before the command, or ``ODMDM_MDM``; the default is ``fleet``. +Its settings are given as for Fleet: ``--set KEY=VALUE``, or ``ODMDM_``, and a secret only +from the file ``ODMDM__FILE`` names. A plugin's MDM may lack something Fleet can do, such as +taking the challenge by API; the command then says what to do instead and changes nothing. + The template ------------ @@ -211,6 +234,40 @@ What Fleet does that you would not guess challenge. A taken name is never freed, not even by revoking it, so give the phone another with ``name``. For the challenge, ``challenge`` and then ``resend``. +Write a plugin +-------------- + +An MDM fits if it can do three things: take a static SCEP challenge for its certificate +authority, put a per-device value that its API can set into the certificate subject (the +callsign, as the common name), and ask a device for its certificate again. + +A plugin is one class that satisfies ``Mdm`` in ``src/odmdm_connector/mdm.py``, which is standard +library only: + +- ``API_VERSION = 1``, a ``title``, the ``fields`` it needs (each a ``Field``; mark a token + ``secret``) and ``missing``: for each of ``setup``, ``set_challenge`` and ``ask_again`` it cannot + do, the sentence the operator reads instead. +- ``__init__(values)`` takes the fields' values by key. +- ``setup(window, force, dry_run)`` yields ``Step`` objects; ``set_challenge(window)``; ``phones()`` + answers ``Phone`` objects, oldest first, each with a ``State``; ``name(names)`` and ``ask_again(ids)`` + answer the lines to show. +- It raises only ``MdmError``. One that stops half-way through ``name`` says in ``named`` which + phones it had already named, and in ``lines`` the lines already due to the operator, such as an + old callsign to revoke, which are shown before the error. + +Publish it as ``odmdm-connector-``, depending on ``odmdm-connector>=1.1,<2``, with the class +under the entry point group ``odmdm_connector.mdm``:: + + [project.entry-points."odmdm_connector.mdm"] + = "odmdm_connector_:Mdm" + +The connector ships a test kit: ``odmdm_connector.testing.contract.CHECKS``, the checks every +plugin must pass given a factory for it, and ``odmdm_connector.testing.FakeMdm``, an MDM in +memory. Start from ``examples/odmdm-connector-demo``: a pretend MDM with three phones that cannot +take a challenge by API, its own ``pyproject.toml`` and its contract test. The repository's CI +builds it and the connector, installs both as above and runs ``odmdm-connector --mdm demo +phones``. + Development ----------- diff --git a/examples/odmdm-connector-demo/pyproject.toml b/examples/odmdm-connector-demo/pyproject.toml index a38dc3e..b9a9c73 100644 --- a/examples/odmdm-connector-demo/pyproject.toml +++ b/examples/odmdm-connector-demo/pyproject.toml @@ -6,7 +6,7 @@ license = "MIT" readme = "README.rst" requires-python = ">=3.11,<4.0" dependencies = [ - "odmdm-connector>=1,<2", + "odmdm-connector>=1.1,<2", ] [project.entry-points."odmdm_connector.mdm"] From ec4fd65d02f31b23c0ac9ec159c36fae45f0fc26 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:46:34 +0200 Subject: [PATCH 047/104] chore: bump version to 1.1.0+261121 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/odmdm_connector/__init__.py | 2 +- tests/test_odmdm_connector.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index e2cebe9..fc587d6 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.0.0+261121" +current_version = "1.1.0+261121" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index e2e09fc..502ea8e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "1.0.0+261121" +version = "1.1.0+261121" description = "Connects FleetDM to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index afc294a..ac0f708 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ """Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" -__version__ = "1.0.0+261121" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.1.0+261121" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index 35e897c..184ed0b 100644 --- a/tests/test_odmdm_connector.py +++ b/tests/test_odmdm_connector.py @@ -5,4 +5,4 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.0.0+261121" + assert __version__ == "1.1.0+261121" diff --git a/uv.lock b/uv.lock index c0569e9..01613b8 100644 --- a/uv.lock +++ b/uv.lock @@ -714,7 +714,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "1.0.0+261121" +version = "1.1.0+261121" source = { editable = "." } dependencies = [ { name = "click" }, From 2cf57bbf59b3479be5d24535db1d3ed96cfe09ee Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 06:59:23 +0200 Subject: [PATCH 048/104] test: guard against process starts in every collected test, the demo's too --- .pre-commit-config.yaml | 3 ++- AGENTS.md | 2 +- tests/conftest.py => conftest.py | 0 pyproject.toml | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) rename tests/conftest.py => conftest.py (100%) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 667e157..abf2e06 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -94,7 +94,7 @@ repos: hooks: - id: bandit stages: [pre-commit] - args: ["--exclude", ".tox,.eggs,tests"] + args: ["--exclude", ".tox,.eggs,tests,conftest.py"] - repo: local # Local to get relevant dependencies hooks: - id: mypy @@ -123,5 +123,6 @@ repos: - "--strict" - "--allow-untyped-decorators" - "tests" + - "conftest.py" - "examples/odmdm-connector-demo/src" - "examples/odmdm-connector-demo/tests" diff --git a/AGENTS.md b/AGENTS.md index 4a33510..49fad6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ The command line knows an MDM only through one contract; Fleet is the plugin bui The connector starts no process and runs no code it was given: ruff bans `subprocess`, the `os.system`/`popen`/`exec*`/`spawn*` family, `webbrowser`, `eval` and `exec`, and -`tests/conftest.py` makes every way to start a process raise for the whole test run. A missing +`conftest.py` at the root makes every way to start a process raise for the whole test run. A missing feature is not a reason to shell out. ## Facts measured against a live Fleet diff --git a/tests/conftest.py b/conftest.py similarity index 100% rename from tests/conftest.py rename to conftest.py diff --git a/pyproject.toml b/pyproject.toml index 502ea8e..62b7985 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,7 @@ extend-select = ["TID251", "S102", "S307"] [tool.ruff.lint.per-file-ignores] # The guard that makes those raise during the tests, and its test -"tests/conftest.py" = ["TID251"] +"conftest.py" = ["TID251"] "tests/test_no_processes.py" = ["TID251"] [tool.ruff.lint.flake8-tidy-imports.banned-api] From 84cf5493d67b98227001d5c42bd42a299f3b1c4d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:49 +0200 Subject: [PATCH 049/104] feat: let a plugin mark a field required or rarely changed, and a refusal as its token not accepted --- src/odmdm_connector/mdm.py | 21 ++++++++++++++++++--- tests/test_mdm.py | 6 ++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py index e13daaa..c6da97c 100644 --- a/src/odmdm_connector/mdm.py +++ b/src/odmdm_connector/mdm.py @@ -5,7 +5,8 @@ the class's API_VERSION before it uses it. Every sentence a plugin hands back, a Step's message, a line from name or ask_again, an MdmError, -is shown to the operator as it is. The SCEP challenge is never in one. +is shown to the operator as it is, by the command line and the window alike, so it names no +command, option or button. The SCEP challenge is never in one. """ from collections.abc import Iterator, Mapping, Sequence @@ -59,6 +60,8 @@ class Field: """A setup value a plugin needs, such as its MDM's address A secret is never taken from an option or a plain environment variable, only from a file. + A required one must be given: the window does not connect without it, and the command line + says how to give it. """ key: str @@ -66,6 +69,9 @@ class Field: secret: bool = False default: str = "" help: str = "" + required: bool = False + #: Rarely changed: the window shows it only when asked + advanced: bool = False @dataclass(frozen=True) @@ -82,13 +88,22 @@ class MdmError(Exception): named holds the phones a batch had already named when it stopped, by id, so the operator names only the rest. lines holds the lines already due to the operator when it stopped, such as which - old callsign to revoke, shown before the error. + old callsign to revoke, shown before the error. unauthorized says the MDM did not accept the + secret it was given, such as an expired token: the connector then lets go of it and asks for it + again. """ - def __init__(self, message: str, named: Mapping[str, str] | None = None, lines: Sequence[str] = ()) -> None: + def __init__( + self, + message: str, + named: Mapping[str, str] | None = None, + lines: Sequence[str] = (), + unauthorized: bool = False, + ) -> None: super().__init__(message) self.named: dict[str, str] = dict(named or {}) self.lines: list[str] = list(lines) + self.unauthorized = unauthorized class Mdm(Protocol): diff --git a/tests/test_mdm.py b/tests/test_mdm.py index 7db67f0..550192d 100644 --- a/tests/test_mdm.py +++ b/tests/test_mdm.py @@ -20,3 +20,9 @@ def test_every_state_is_a_sentence_and_every_capability_is_named() -> None: assert all(state.value and state.value == state.value.strip() for state in mdm.State) assert set(mdm.CAPABILITIES) == {"setup", "set_challenge", "ask_again"} assert mdm.API_VERSION == 1 + + +def test_a_field_is_shown_unless_marked_advanced() -> None: + """The window hides a field marked advanced until asked; the command line takes it as any other""" + assert not mdm.Field("team", "Team").advanced + assert mdm.Field("key_alias", "Key alias", advanced=True).advanced From 3d3c382648e54d302c5a7ee76ed6be0c3ad33d47 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:49 +0200 Subject: [PATCH 050/104] feat: keep settings in a file and the MDM token in the system keychain keyring is imported in this module alone, with the one back end for the system fixed in code. Without it the connector still runs, and a token is then held until it stops. --- pyproject.toml | 1 + src/odmdm_connector/store.py | 254 +++++++++++++++++++++++++++++++++ tests/test_store.py | 242 +++++++++++++++++++++++++++++++ uv.lock | 267 +++++++++++++++++++++++++++++++++++ 4 files changed, 764 insertions(+) create mode 100644 src/odmdm_connector/store.py create mode 100644 tests/test_store.py diff --git a/pyproject.toml b/pyproject.toml index 62b7985..559a0b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,7 @@ dependencies = [ "libadvian>=1.4,<2.0", "click>=8.1,<9.0", "httpx>=0.28,<1.0", + "keyring>=25.6,<26.0", ] [project.urls] diff --git a/src/odmdm_connector/store.py b/src/odmdm_connector/store.py new file mode 100644 index 0000000..44feaec --- /dev/null +++ b/src/odmdm_connector/store.py @@ -0,0 +1,254 @@ +"""What the connector keeps between runs: a settings file without secrets, beside its log, and the keychain + +The settings file holds the plugins approved and, for each Deploy App connected by its host, the MDM +chosen, the MDM's fields that are not secret, when its last enrolment window closes and the +operator's callsigns for next time, and which Deploy App was worked with last. Never a secret, never +the challenge. A field marked secret, the MDM token, goes only to the operating system's keychain, +through keyring's one back end for the system, fixed here so that neither PYTHON_KEYRING_BACKEND, +keyring's configuration file nor another back end installed can choose where it goes. keyring is +the connector's one dependency and is imported here alone: without it, as in the one-file build, +there is no keychain and the App holds a secret until the connector stops. Never a plaintext fallback. +""" + +import datetime +import json +import logging +import os +import sys +import tempfile +from collections.abc import Callable +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Protocol + +LOGGER = logging.getLogger(__name__) + +#: The name of the directory the settings file and the log go in, and the keychain service of the secrets +APP = "odmdm-connector" +#: The settings file's format +VERSION = 1 + + +class StoreError(Exception): + """The settings file cannot be read or written, said in a sentence for the operator""" + + +def directory() -> Path: + """Where the settings file and the log live: the user's own application directory, named, not created""" + if sys.platform == "win32": + return Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local") / APP + if sys.platform == "darwin": + return Path.home() / "Library" / "Application Support" / APP + return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / APP + + +@dataclass +class Connection: + """One Deploy App, by the host of its SCEP URL, and the MDM set up for it""" + + #: The MDM chosen, by its plugin name + mdm: str = "" + #: The chosen MDM's fields that are not secret, by key + values: dict[str, str] = field(default_factory=dict) + #: When the last enrolment window pasted closes, as an ISO time, so the banner survives a restart + closes: str = "" + #: The callsign prefix last used, and the list of callsigns still to give + prefix: str = "" + callsigns: list[str] = field(default_factory=list) + + +@dataclass +class Saved: + """The settings file's contents""" + + #: The plugins approved by the operator, each as "name package version"; asked again when it changes + approved: list[str] = field(default_factory=list) + #: The Deploy Apps connected, by the host of their SCEP URL + connections: dict[str, Connection] = field(default_factory=dict) + #: The host of the Deploy App worked with last, or empty + active: str = "" + + +def _typed(key: str, value: Any, default: Any) -> Any: + """The value, if it is of its default's type: a string, a list of strings or a mapping of strings""" + if isinstance(default, dict): + if not isinstance(value, dict) or not all(isinstance(v, str) for v in value.values()): + raise TypeError(f"{key} is not a mapping of strings") + elif isinstance(default, list): + if not isinstance(value, list) or not all(isinstance(v, str) for v in value): + raise TypeError(f"{key} is not a list of strings") + elif not isinstance(value, str): + raise TypeError(f"{key} is not a string") + return value + + +def _connection(host: str, raw: Any) -> Connection: + if not isinstance(raw, dict): + raise TypeError(f"connection {host} is not a mapping") + return Connection( + **{ + key: _typed(f"{host} {key}", raw.get(key, default), default) + for key, default in asdict(Connection()).items() + } + ) + + +def _checked(raw: Any) -> Saved: + """The file's values, each of the type it must be; TypeError otherwise""" + if not isinstance(raw, dict) or raw.get("version") != VERSION: + raise TypeError("not a version 1 settings file") + connections = raw.get("connections", {}) + if not isinstance(connections, dict): + raise TypeError("connections is not a mapping") + found = Saved( + approved=_typed("approved", raw.get("approved", []), []), + connections={host: _connection(host, each) for host, each in connections.items()}, + active=_typed("active", raw.get("active", ""), ""), + ) + if found.active and found.active not in found.connections: + raise TypeError("active is not a connection") + return found + + +class Store: + """The settings file in one directory, written whole and readable only by the user""" + + def __init__(self, directory: Path) -> None: + self.path = directory / "settings.json" + + def load(self) -> Saved: + """The saved settings; empty ones when there is no file yet""" + try: + text = self.path.read_text(encoding="utf-8") + except FileNotFoundError: + return Saved() + except OSError as exc: + raise StoreError(f"The settings file {self.path} cannot be read: {exc.strerror}.") from exc + try: + return _checked(json.loads(text)) + except (ValueError, TypeError) as exc: + LOGGER.warning("Settings file %s refused: %s", self.path, exc) + raise StoreError(f"The settings file {self.path} is damaged, so the app starts without it.") from exc + + def save(self, saved: Saved) -> None: + """Write the file whole: a new file beside it, readable only by the user, then renamed over it""" + text = json.dumps({"version": VERSION, **asdict(saved)}, indent=2) + try: + self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + handle, name = tempfile.mkstemp(dir=self.path.parent, prefix=".settings-", suffix=".json") + try: + with os.fdopen(handle, "w", encoding="utf-8") as written: + written.write(text) + written.flush() + os.fsync(written.fileno()) + os.replace(name, self.path) + except BaseException: + Path(name).unlink(missing_ok=True) + raise + except OSError as exc: + raise StoreError(f"The settings file {self.path} cannot be written: {exc.strerror}.") from exc + + +def closes(connection: Connection) -> datetime.datetime | None: + """When the Deploy App's last enrolment window pasted closes, if one was""" + try: + return datetime.datetime.fromisoformat(connection.closes) if connection.closes else None + except ValueError: + return None + + +class Backend(Protocol): + """The part of a keyring back end the connector uses""" + + def get_password(self, service: str, username: str) -> str | None: ... + + def set_password(self, service: str, username: str, password: str) -> None: ... + + def delete_password(self, service: str, username: str) -> None: ... + + +def platform_backend() -> Backend | None: + """The system's keychain, or None when keyring is not installed or the keychain cannot be used here + + The one back end per system is named here and set as keyring's, so keyring never looks at + PYTHON_KEYRING_BACKEND, its configuration file or the other back ends installed. + """ + try: + import keyring + from keyring.backend import KeyringBackend + + if sys.platform == "win32": + from keyring.backends.Windows import WinVaultKeyring as Chosen + elif sys.platform == "darwin": + from keyring.backends.macOS import Keyring as Chosen + else: + from keyring.backends.SecretService import Keyring as Chosen + except ImportError: + LOGGER.debug("keyring is not installed, so no keychain is used") + return None + if not Chosen.viable: + LOGGER.warning("The keychain back end %s cannot be used here", Chosen.__name__) + return None + # keyring leaves the back ends' constructors unannotated + make: Callable[[], KeyringBackend] = Chosen + backend = make() + keyring.set_keyring(backend) + return backend + + +class KeychainError(Exception): + """The keychain did not answer; it says only the kind of what the back end raised, never a value""" + + +def _asked(backend: Backend, call: Callable[[Backend], str | None]) -> str | None: + """The back end's answer + + A back end raises kinds of its own besides keyring's, D-Bus's and Windows' among them, so any + exception means the keychain did not answer, and becomes a KeychainError that names its kind. + """ + try: + return call(backend) + except Exception as exc: + raise KeychainError(type(exc).__name__) from exc + + +class Keychain: + """Secrets by account, under the service APP, in the system's keychain; no back end is no keychain""" + + def __init__(self, backend: Backend | None) -> None: + self.backend = backend + + @property + def usable(self) -> bool: + return self.backend is not None + + def _call(self, call: Callable[[Backend], str | None]) -> tuple[bool, str]: + """Whether the keychain answered, and its answer; when it did not, that is logged by its kind only""" + if self.backend is None: + return False, "" + try: + return True, _asked(self.backend, call) or "" + except KeychainError as exc: + LOGGER.warning("The keychain did not answer: %s", exc) + return False, "" + + def get(self, account: str) -> str: + """The secret kept, empty when there is none or the keychain did not answer""" + return self._call(lambda backend: backend.get_password(APP, account))[1] + + def keep(self, account: str, secret: str) -> bool: + """Keep the secret; whether the keychain took it""" + return self._call(lambda backend: backend.set_password(APP, account, secret))[0] + + def forget(self, account: str) -> bool: + """Remove the secret; whether the keychain no longer holds it, which is so without a keychain + + Deleting what is not there raises, so the keychain is read first, and again after deleting to tell. + """ + if self.backend is None: + return True + answered, left = self._call(lambda backend: backend.get_password(APP, account)) + if answered and left: + self._call(lambda backend: backend.delete_password(APP, account)) + answered, left = self._call(lambda backend: backend.get_password(APP, account)) + return answered and not left diff --git a/tests/test_store.py b/tests/test_store.py new file mode 100644 index 0000000..47af956 --- /dev/null +++ b/tests/test_store.py @@ -0,0 +1,242 @@ +"""The settings file and the keychain, against a temporary directory and a keychain in memory""" + +import datetime +import json +import logging +import os +import stat +import sys +from pathlib import Path + +import keyring +import keyring.core +import pytest + +from odmdm_connector import store + +TOKEN = "s3cret" # pragma: allowlist secret + + +class MemoryBackend: + """A keychain in memory; broken makes every call raise, as a keychain that does not answer does""" + + def __init__(self) -> None: + self.items: dict[tuple[str, str], str] = {} + self.broken = False + #: Deleting is refused while reading still answers, as a locked item is + self.undeletable = False + + def _check(self) -> None: + if self.broken: + raise RuntimeError(f"no keychain here for {TOKEN}") + + def get_password(self, service: str, username: str) -> str | None: + self._check() + return self.items.get((service, username)) + + def set_password(self, service: str, username: str, password: str) -> None: + self._check() + self.items[(service, username)] = password + + def delete_password(self, service: str, username: str) -> None: + self._check() + if self.undeletable or (service, username) not in self.items: + raise keyring.errors.PasswordDeleteError(username) + del self.items[(service, username)] + + +def test_settings_survive_a_restart(tmp_path: Path) -> None: + unit = store.Connection( + mdm="fleet", + values={"mdm_url": "https://mdm.example.fi"}, + closes="2026-11-21T14:00:00+00:00", + prefix="OTTER", + callsigns=["BEAR1", "BEAR2"], + ) + saved = store.Saved( + approved=["demo odmdm-connector-demo 1.0.0"], + connections={"unit.example.fi": unit, "other.example.fi": store.Connection(mdm="demo")}, + active="unit.example.fi", + ) + + store.Store(tmp_path / "config").save(saved) + + assert store.Store(tmp_path / "config").load() == saved + assert store.closes(unit) == datetime.datetime(2026, 11, 21, 14, tzinfo=datetime.UTC) + + +def test_the_file_holds_no_more_than_said(tmp_path: Path) -> None: + """Written whole, readable only by the user, nothing left beside it""" + settings = store.Store(tmp_path) + settings.save(store.Saved(active="")) + settings.save(store.Saved(connections={"unit.example.fi": store.Connection()}, active="unit.example.fi")) + + assert [path.name for path in tmp_path.iterdir()] == ["settings.json"] + assert json.loads(settings.path.read_text(encoding="utf-8"))["active"] == "unit.example.fi" + if os.name == "posix": + assert stat.S_IMODE(settings.path.stat().st_mode) == 0o600 + + +def test_no_file_is_empty_settings(tmp_path: Path) -> None: + assert store.Store(tmp_path).load() == store.Saved() + assert store.closes(store.Connection()) is None + assert store.closes(store.Connection(closes="soon")) is None + + +@pytest.mark.parametrize( + "text", + [ + "not json", + '{"version": 2}', + '{"version": 1, "active": 3}', + '{"version": 1, "approved": "demo"}', + '{"version": 1, "connections": []}', + '{"version": 1, "connections": {"unit.example.fi": "fleet"}}', + '{"version": 1, "connections": {"unit.example.fi": {"mdm": 3}}}', + '{"version": 1, "connections": {"unit.example.fi": {"values": {"team": 1}}}}', + '{"version": 1, "connections": {"unit.example.fi": {"callsigns": "BEAR1"}}}', + '{"version": 1, "connections": {}, "active": "unit.example.fi"}', + ], +) +def test_a_damaged_file_is_said_in_a_sentence(tmp_path: Path, text: str) -> None: + settings = store.Store(tmp_path) + settings.path.write_text(text, encoding="utf-8") + + with pytest.raises(store.StoreError, match=r"is damaged, so the app starts without it\.$"): + settings.load() + + +def test_a_file_that_cannot_be_read_or_written_is_said(tmp_path: Path) -> None: + (tmp_path / "settings.json").mkdir() + blocked = tmp_path / "blocked" + blocked.write_text("a file where the directory would be", encoding="utf-8") + + with pytest.raises(store.StoreError, match="cannot be read"): + store.Store(tmp_path).load() + with pytest.raises(store.StoreError, match="cannot be written"): + store.Store(blocked).save(store.Saved()) + with pytest.raises(store.StoreError, match="cannot be written"): + store.Store(tmp_path).save(store.Saved()) + assert [path.name for path in tmp_path.iterdir() if path.name.startswith(".")] == [] + + +@pytest.mark.parametrize( + ("platform", "environment", "expected"), + [ + ("win32", {"LOCALAPPDATA": "local"}, ("local", "odmdm-connector")), + ("win32", {}, ("home", "AppData", "Local", "odmdm-connector")), + ("darwin", {"XDG_CONFIG_HOME": "xdg"}, ("home", "Library", "Application Support", "odmdm-connector")), + ("linux", {"XDG_CONFIG_HOME": "xdg"}, ("xdg", "odmdm-connector")), + ("linux", {}, ("home", ".config", "odmdm-connector")), + ], +) +def test_the_directory_is_the_users_own( + monkeypatch: pytest.MonkeyPatch, platform: str, environment: dict[str, str], expected: tuple[str, ...] +) -> None: + """Named, not created""" + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr(Path, "home", lambda: Path("home")) + for name in ("LOCALAPPDATA", "XDG_CONFIG_HOME"): + monkeypatch.delenv(name, raising=False) + for name, value in environment.items(): + monkeypatch.setenv(name, value) + + assert store.directory() == Path(*expected) + + +def test_a_secret_kept_and_forgotten(caplog: pytest.LogCaptureFixture) -> None: + backend = MemoryBackend() + keychain = store.Keychain(backend) + + assert keychain.usable + assert keychain.keep("unit.example.fi:fleet:token", TOKEN) + assert backend.items == {("odmdm-connector", "unit.example.fi:fleet:token"): TOKEN} + assert store.Keychain(backend).get("unit.example.fi:fleet:token") == TOKEN + assert keychain.forget("unit.example.fi:fleet:token") + assert (backend.items, keychain.get("unit.example.fi:fleet:token")) == ({}, "") + with caplog.at_level(logging.WARNING): + assert keychain.forget("unit.example.fi:fleet:token") + assert not caplog.records, "nothing to forget is not a keychain that did not answer" + + +def test_a_keychain_that_does_not_answer_is_logged_by_its_kind_only(caplog: pytest.LogCaptureFixture) -> None: + backend = MemoryBackend() + backend.items[("odmdm-connector", "unit.example.fi:fleet:token")] = TOKEN + backend.broken = True + keychain = store.Keychain(backend) + + with caplog.at_level(logging.WARNING): + assert not keychain.keep("unit.example.fi:fleet:token", TOKEN) + assert keychain.get("unit.example.fi:fleet:token") == "" + assert not keychain.forget("unit.example.fi:fleet:token") + + assert [record.getMessage() for record in caplog.records] == ["The keychain did not answer: RuntimeError"] * 3 + assert all(record.exc_info is None for record in caplog.records) + + +def test_a_secret_the_keychain_will_not_delete_is_said_to_be_left() -> None: + backend = MemoryBackend() + backend.items[("odmdm-connector", "unit.example.fi:fleet:token")] = TOKEN + backend.undeletable = True + + assert not store.Keychain(backend).forget("unit.example.fi:fleet:token") + + +def test_no_back_end_is_no_keychain() -> None: + missing = store.Keychain(None) + + assert not missing.usable + assert not missing.keep("unit.example.fi:fleet:token", TOKEN) + assert missing.get("unit.example.fi:fleet:token") == "" + assert missing.forget("unit.example.fi:fleet:token"), "nothing is kept where there is no keychain" + + +def _chosen() -> type[keyring.backend.KeyringBackend]: + """keyring's back end for this system, as store names it""" + if sys.platform == "win32": + from keyring.backends.Windows import WinVaultKeyring + + return WinVaultKeyring + if sys.platform == "darwin": + from keyring.backends.macOS import Keyring as MacOS + + return MacOS + from keyring.backends.SecretService import Keyring as SecretService + + return SecretService + + +def test_the_systems_keychain_is_fixed_in_code(monkeypatch: pytest.MonkeyPatch) -> None: + """Neither the environment nor keyring's configuration chooses it; nothing is read or written""" + monkeypatch.setattr(keyring.core, "_keyring_backend", None) + monkeypatch.setenv("PYTHON_KEYRING_BACKEND", "keyring.backends.null.Keyring") + + backend = store.platform_backend() + + if backend is None: + pytest.skip(f"{_chosen().__name__} cannot be used on this machine") + assert type(backend) is _chosen() + assert keyring.get_keyring() is backend + + +def test_a_keychain_that_cannot_be_used_here_is_none(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(keyring.core, "_keyring_backend", None) + monkeypatch.setattr(_chosen(), "viable", False) + + assert store.platform_backend() is None + assert keyring.core._keyring_backend is None + + +def test_without_keyring_there_is_no_keychain( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """As in the one-file build, which leaves keyring out; said only to the debug log, as nothing is wrong""" + for name in [name for name in sys.modules if name == "keyring" or name.startswith("keyring.")]: + monkeypatch.setitem(sys.modules, name, None) + monkeypatch.setitem(sys.modules, "keyring", None) + caplog.set_level(logging.DEBUG) + + assert store.platform_backend() is None + assert [(record.levelno, record.getMessage()) for record in caplog.records] == [ + (logging.DEBUG, "keyring is not installed, so no keychain is used") + ] diff --git a/uv.lock b/uv.lock index 01613b8..28ff603 100644 --- a/uv.lock +++ b/uv.lock @@ -29,6 +29,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b8/4bd346e22b28902df4d651910f5242c28d84e4a5c2435ca5c3f797ed7e2e/anyio-4.15.1-py3-none-any.whl", hash = "sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101", size = 132079, upload-time = "2026-09-05T10:42:37.923Z" }, ] +[[package]] +name = "backports-tarfile" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", size = 86406, upload-time = "2024-05-28T17:01:54.731Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181, upload-time = "2024-05-28T17:01:53.112Z" }, +] + [[package]] name = "bandit" version = "1.9.4" @@ -91,6 +100,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "(python_full_version < '3.12' and implementation_name != 'PyPy') or (python_full_version >= '3.15' and implementation_name != 'PyPy') or (implementation_name != 'PyPy' and sys_platform != 'emscripten')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ad/5a/4707a0dc1f203f5dde5a907b0d4e3c25d71120241048bd5bc6f1bb9d4e71/cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0", size = 211805, upload-time = "2026-08-03T21:19:31.867Z" }, + { url = "https://files.pythonhosted.org/packages/ad/66/c19feabb28485b6e0bbaaafa90837a1ef5d302e90f2178bd33f17a49879b/cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813", size = 218716, upload-time = "2026-08-03T21:19:32.896Z" }, + { url = "https://files.pythonhosted.org/packages/a7/92/500760486c8baab49a7a8a58ba7fc3355ec3974b454b8a09e528efde9e1d/cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990", size = 205569, upload-time = "2026-08-03T21:19:34.142Z" }, + { url = "https://files.pythonhosted.org/packages/a5/a7/a67c733254d6e7373f7822f8082d8d6beade791e0cf12a7611f376fa61c7/cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af", size = 204907, upload-time = "2026-08-03T21:19:35.174Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a4/4399daaf8f7dfee9d7c3327fdb0426ee041cc63edc358b93911ceb2bfc7a/cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632", size = 217807, upload-time = "2026-08-03T21:19:36.286Z" }, + { url = "https://files.pythonhosted.org/packages/28/f7/dabe6da2466ecbd82dc62e7342dc6b1065dad990c06f00f0ede9ebf2a0ed/cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd", size = 221252, upload-time = "2026-08-03T21:19:37.416Z" }, + { url = "https://files.pythonhosted.org/packages/ce/87/616202d8e51342c07d2534c510111c4cc37201775ce8f60802c9335d1edd/cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a", size = 214214, upload-time = "2026-08-03T21:19:38.507Z" }, + { url = "https://files.pythonhosted.org/packages/b4/c6/ab025d75d2c26c19b087c0124e75ee31cb65032f4fe345d356d8c507ab97/cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa", size = 219408, upload-time = "2026-08-03T21:19:39.809Z" }, + { url = "https://files.pythonhosted.org/packages/56/e6/8941622732edec876dd17d0453dce07317ae96db34f2ec1436c9d3785986/cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a", size = 214799, upload-time = "2026-08-03T21:19:47.218Z" }, + { url = "https://files.pythonhosted.org/packages/44/de/f98430906df1545ffde0d543dd124a7a439bc2cd32b36b9c53f805df7333/cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890", size = 222389, upload-time = "2026-08-03T21:19:48.331Z" }, + { url = "https://files.pythonhosted.org/packages/6a/5b/717f1526b9957b34456313c31645c5b82b8fb5c3fe9e4752999be7128bfc/cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50", size = 210249, upload-time = "2026-08-03T21:19:49.543Z" }, + { url = "https://files.pythonhosted.org/packages/64/b3/f8aa4f3e34986c7e4ec45072d1b1b9dd295b6b18007b45518d79726dd725/cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e", size = 208775, upload-time = "2026-08-03T21:19:50.918Z" }, + { url = "https://files.pythonhosted.org/packages/b1/db/dceb9dd5b231e1da801793f8acc9f3c52a7e1afe40bb1aae37e02b0faad5/cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf", size = 221822, upload-time = "2026-08-03T21:19:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a0/d2/6cd24ae3be000a634109c247d1475d62e5616d0dc78c82770942ec384248/cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517", size = 225232, upload-time = "2026-08-03T21:19:53.109Z" }, + { url = "https://files.pythonhosted.org/packages/cb/52/3fa190537004dd7f0ab860a6dc7c0175b8667f68d1e618a46f5498d30250/cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735", size = 223597, upload-time = "2026-08-03T21:19:54.515Z" }, + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, +] + [[package]] name = "charset-normalizer" version = "3.5.2" @@ -382,6 +454,65 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c9/17/48032919343afa2906112d458aceda2043afdb24a2ee8eb4c60904d8ddf1/coverage-7.17.0-py3-none-any.whl", hash = "sha256:bac487dce0d2aff28ddf1a533a916f771416eee0e493960f611e49037b878e9d", size = 217383, upload-time = "2026-10-22T16:06:48.471Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "(python_full_version < '3.12' and platform_python_implementation != 'PyPy') or (python_full_version >= '3.15' and platform_python_implementation != 'PyPy') or (platform_python_implementation != 'PyPy' and sys_platform != 'emscripten')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/1d/7a/f08d34ce09d60f89ebd391e2ebc6ba2b995e6dd7552f41820f8085f94e53/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67", size = 4716035, upload-time = "2026-09-30T15:29:48.681Z" }, + { url = "https://files.pythonhosted.org/packages/45/67/e18fb65592451a2acb76e9f2fbe14e0f47a8318b4c5430f1633851d03daa/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a", size = 4726917, upload-time = "2026-09-30T15:29:50.608Z" }, + { url = "https://files.pythonhosted.org/packages/83/28/38fdce17e60f6b825e69fc3b7f75e70a6612759980704697e1de4cbfaf6e/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48", size = 4715341, upload-time = "2026-09-30T15:29:52.522Z" }, + { url = "https://files.pythonhosted.org/packages/b6/b1/d9121a717e0f893c64bd6ca7702614778d7df2a5c309128a002421788516/cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42", size = 4726322, upload-time = "2026-09-30T15:29:54.263Z" }, +] + [[package]] name = "detect-secrets" version = "1.5.0" @@ -498,6 +629,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, ] +[[package]] +name = "importlib-metadata" +version = "10.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "lazy-importer", marker = "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')" }, + { name = "zipp", marker = "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a6/91/0ef39e4ef4407de276289a3759977ac3a8cc546f59c55d725750eae3f41b/importlib_metadata-10.2.0.tar.gz", hash = "sha256:9413a2029fd9ca5669d27f1386071bbfe3c7ebca0545692ec975088241fe1d79", size = 72457, upload-time = "2026-11-09T19:09:10.915Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/61/0c0fae37eb561d8fddb788cbae0f227051628d70d67498a8a116c1f547d7/importlib_metadata-10.2.0-py3-none-any.whl", hash = "sha256:c7a4bf1c7479601f6b8e437cfc14f4f77028ba62a8f34ae95cd93d9774dfba51", size = 34109, upload-time = "2026-11-09T19:09:09.942Z" }, +] + [[package]] name = "iniconfig" version = "2.3.1" @@ -507,6 +651,78 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, ] +[[package]] +name = "jaraco-classes" +version = "3.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "more-itertools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", size = 11780, upload-time = "2024-03-31T07:27:36.643Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", size = 6777, upload-time = "2024-03-31T07:27:34.792Z" }, +] + +[[package]] +name = "jaraco-context" +version = "6.1.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "backports-tarfile", marker = "python_full_version < '3.12'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/af/50/4763cd07e722bb6285316d390a164bc7e479db9d90daa769f22578f698b4/jaraco_context-6.1.2.tar.gz", hash = "sha256:f1a6c9d391e661cc5b8d39861ff077a7dc24dc23833ccee564b234b81c82dfe3", size = 16801, upload-time = "2026-03-20T22:13:33.922Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f2/58/bc8954bda5fcda97bd7c19be11b85f91973d67a706ed4a3aec33e7de22db/jaraco_context-6.1.2-py3-none-any.whl", hash = "sha256:bf8150b79a2d5d91ae48629d8b427a8f7ba0e1097dd6202a9059f29a36379535", size = 7871, upload-time = "2026-03-20T22:13:32.808Z" }, +] + +[[package]] +name = "jaraco-functools" +version = "4.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "more-itertools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/1f/c23395957d41ccf27c4e535c3d334c4051e5395b3752057ba4cbaec35c56/jaraco_functools-4.6.0.tar.gz", hash = "sha256:880c577ec9720b3a052d5bc611fb9f2269b3d87902ef42440df443b88e443280", size = 20837, upload-time = "2026-07-14T01:28:02.544Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/36/ecc85bc96c273dc8a11273ed4782272975e6338d4a3e9228621175edf0e3/jaraco_functools-4.6.0-py3-none-any.whl", hash = "sha256:99e3dc0060c5cbe8fcd1cdb36258e2a65ca40f1566b2033b12abb1bb44dd3c30", size = 11677, upload-time = "2026-07-14T01:28:01.59Z" }, +] + +[[package]] +name = "jeepney" +version = "0.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758, upload-time = "2025-02-27T18:51:01.684Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010, upload-time = "2025-02-27T18:51:00.104Z" }, +] + +[[package]] +name = "keyring" +version = "25.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "importlib-metadata", marker = "python_full_version < '3.12'" }, + { name = "jaraco-classes" }, + { name = "jaraco-context" }, + { name = "jaraco-functools" }, + { name = "jeepney", marker = "sys_platform == 'linux'" }, + { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" }, + { name = "secretstorage", marker = "sys_platform == 'linux'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/4b/674af6ef2f97d56f0ab5153bf0bfa28ccb6c3ed4d1babf4305449668807b/keyring-25.7.0.tar.gz", hash = "sha256:fe01bd85eb3f8fb3dd0405defdeac9a5b4f6f0439edbb3149577f244a2e8245b", size = 63516, upload-time = "2025-11-16T16:26:09.482Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/db/e655086b7f3a705df045bf0933bdd9c2f79bb3c97bfef1384598bb79a217/keyring-25.7.0-py3-none-any.whl", hash = "sha256:be4a0b195f149690c166e850609a477c532ddbfbaed96a404d4e43f8d5e2689f", size = 39160, upload-time = "2025-11-16T16:26:08.402Z" }, +] + +[[package]] +name = "lazy-importer" +version = "0.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d9/23/d2c8308466a6831043ac3518e480c2e1a06b21a13e0a8f6542ab29cf592a/lazy_importer-0.1.0.tar.gz", hash = "sha256:b2e296716ce015c0cd80e57b940e52727c5b934b34b8656d5ce06bdd0ee5fbdd", size = 84008, upload-time = "2026-10-20T00:36:58.369Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/28/7ded071d0975dcc6d5d106ffbf7b3ca420f7caa3b8a235fa604b6e37032a/lazy_importer-0.1.0-py3-none-any.whl", hash = "sha256:bd93fab7bef18e842eea02b839410954d37889140dc64ca4d9680aec6880c739", size = 12580, upload-time = "2026-10-20T00:36:57.176Z" }, +] + [[package]] name = "libadvian" version = "1.9.0" @@ -653,6 +869,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] +[[package]] +name = "more-itertools" +version = "11.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/52/b8/c63995bebbb9ac9c059350e0fb8c82c2420c85aeca7d34e40aecf3df9281/more_itertools-11.2.1.tar.gz", hash = "sha256:cbf08fd0af284dc69718b9b76a8e6203df624d70209ea511e4219d350c856f63", size = 154133, upload-time = "2026-10-14T18:50:30.407Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/57/3c4b1c6f2e0cc29ba023802458ea3d2a996f87085559e4a5f2192d549532/more_itertools-11.2.1-py3-none-any.whl", hash = "sha256:35a7377edd1dd6608dcb2cdf534ded55ea32d49448875ad042cd3f879fb1ded0", size = 74405, upload-time = "2026-10-14T18:50:29.116Z" }, +] + [[package]] name = "mypy" version = "1.20.2" @@ -719,6 +944,7 @@ source = { editable = "." } dependencies = [ { name = "click" }, { name = "httpx" }, + { name = "keyring" }, { name = "libadvian" }, ] @@ -741,6 +967,7 @@ dev = [ requires-dist = [ { name = "click", specifier = ">=8.1,<9.0" }, { name = "httpx", specifier = ">=0.28,<1.0" }, + { name = "keyring", specifier = ">=25.6,<26.0" }, { name = "libadvian", specifier = ">=1.4,<2.0" }, ] @@ -824,6 +1051,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/6f/84908cad2d6aa5144abcf7b42709fe4fdb459bc640ec7ac5786e7693dabc/prompt_toolkit-3.0.53-py3-none-any.whl", hash = "sha256:01c0891d7f9237d5e339f7d3e42cdae80b7534abb1c7c0e3352efba6231492f2", size = 392288, upload-time = "2026-07-26T20:56:12.512Z" }, ] +[[package]] +name = "pycparser" +version = "3.12" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cb/27/eeb9f307bf07060f3d9f9aa0fb8c15b01bdfded0a941e4b2719c7f94cacd/pycparser-3.12.tar.gz", hash = "sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6", size = 158785, upload-time = "2026-10-22T13:40:03.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/ae/315bbeee126a769cbde43cf4908acb4b40408d8bf8bbf334dd7368d8dadf/pycparser-3.12-py3-none-any.whl", hash = "sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e", size = 62600, upload-time = "2026-10-22T13:40:02.021Z" }, +] + [[package]] name = "pydantic" version = "2.14.2" @@ -1062,6 +1298,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/60/d1/38f3a3405989a89ac18390803e70c6ad7c7760da4f9b83cbeca0c44a0c72/python_dotenv-1.2.4-py3-none-any.whl", hash = "sha256:42269a8a5b3fd54ffa6f3d84b18abed50064717576b4ecf03dc4a55d8aa04fdc", size = 23266, upload-time = "2026-10-01T05:36:08.633Z" }, ] +[[package]] +name = "pywin32-ctypes" +version = "0.2.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471, upload-time = "2024-08-14T10:15:34.626Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756, upload-time = "2024-08-14T10:15:33.187Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -1196,6 +1441,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/d5/4ad4ed31413c301430918e70d3d38ae6f097af0766cb9ab8c9d502b2a4d6/ruff-0.17.3-py3-none-win_arm64.whl", hash = "sha256:81fce74bcd6be0e9da7c67c7553fd0f1f12964a2052cd728ef917b937a5ca1d9", size = 9854332, upload-time = "2026-10-27T00:34:03.847Z" }, ] +[[package]] +name = "secretstorage" +version = "3.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cryptography", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, + { name = "jeepney", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, +] + [[package]] name = "stevedore" version = "5.9.1" @@ -1398,3 +1656,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4e/cc/7eeb28059186cae72a770df79e744f232ef068192a5a588b718473e35bb4/wcwidth-0.9.4-cp315-cp315t-win_arm64.whl", hash = "sha256:2cca7b5d0b9d0ae49068d3ce806e965326a987f555b62eaa322223396e10d01b", size = 605198, upload-time = "2026-10-24T18:11:33.75Z" }, { url = "https://files.pythonhosted.org/packages/6f/0c/309b1813b230d1dbbd6f2c2ab2bb21ef68992358977605d9ef289bbfedcc/wcwidth-0.9.4-py3-none-any.whl", hash = "sha256:901eace6d2dd25ebb917d0ce5db18e5c537e1504c905cf32f0d006c12098b05d", size = 301806, upload-time = "2026-10-24T18:10:52.651Z" }, ] + +[[package]] +name = "zipp" +version = "4.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/05/ba1458dee0ac485b2a01071c1b88f5199fe878a485df482e10e1ef2205cc/zipp-4.1.2.tar.gz", hash = "sha256:cf474b90b07ea932637e17c6b9479de2b2882900b0d311bdaf4f5c000a15a97f", size = 27864, upload-time = "2026-10-21T18:57:04.743Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b8/44/7bd2007260da11cccca29ba2d4c345f1287aa663db38ee7cefeabf6386a5/zipp-4.1.2-py3-none-any.whl", hash = "sha256:b30cb6cd253122169c47de245ca24a86bac2a5d3802ba15bf7ba6414eb9e144d", size = 10581, upload-time = "2026-10-21T18:57:03.79Z" }, +] From 700e5d8e0fb5e0aae94cdb2a66681867705565b2 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:49 +0200 Subject: [PATCH 051/104] feat: drive the connector without a command line, MDM work on one worker --- src/odmdm_connector/app.py | 1049 ++++++++++++++++++++++++++++++++++++ 1 file changed, 1049 insertions(+) create mode 100644 src/odmdm_connector/app.py diff --git a/src/odmdm_connector/app.py b/src/odmdm_connector/app.py new file mode 100644 index 0000000..f454c46 --- /dev/null +++ b/src/odmdm_connector/app.py @@ -0,0 +1,1049 @@ +"""The connector without a command line: what the page shows and does, with no user interface in it + +The App works with several Deploy Apps, each a connection by the host of its SCEP URL, and with one +of them at a time: the active one, whose MDM, enrolment window and phones it holds. + +A view calls an App and renders the plain data it answers: a Banner, Rows, a Form, a Preview, a +Detail and Results. Work that talks to the MDM runs on the App's one worker thread, and its Results +wait in a queue that the view drains on a timer with drain(), which is also where the App takes +them in. The App never touches a user interface and a view never touches the network or the file +system. Time is passed in. + +Every failure the operator meets is one sentence: an AppError raised at once, or a Result's error. +""" + +import datetime +import logging +import math +import queue +import threading +from collections.abc import Callable, Mapping, Sequence +from dataclasses import dataclass, field, replace +from enum import Enum +from logging.handlers import RotatingFileHandler +from pathlib import Path +from typing import Any +from urllib.parse import urlsplit + +from . import core, plugins, settings, store +from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step +from .settings import Settings + +LOGGER = logging.getLogger(__name__) + +#: How long before the window closes the banner warns +CLOSING = datetime.timedelta(minutes=10) +#: A phone that joined this recently may still be installing its apps +RECENT = datetime.timedelta(minutes=10) +#: The states of a phone whose certificate failed, which asking again or another callsign may cure +FAILED = (State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) + + +class AppError(Exception): + """What the operator asked cannot be done, said in one sentence""" + + +class Level(Enum): + """How the banner reads""" + + #: No enrolment window known yet + NONE = "none" + OPEN = "open" + #: Closing within ten minutes + CLOSING = "closing" + CLOSED = "closed" + + +@dataclass(frozen=True) +class Banner: + level: Level + text: str + #: The same in a few words, beside the Deploy App's name in a list of them + short: str + + +@dataclass(frozen=True) +class DeployApp: + """A connection as the list of them shows it""" + + host: str + #: What the banner would say of it + banner: Banner + active: bool + + +@dataclass(frozen=True) +class Reading: + """What a settings line says, before it is taken""" + + host: str + #: Until when that Deploy App accepts phones, as the banner says it + until: str + #: Whether a connection for that Deploy App is saved already + known: bool + + +@dataclass(frozen=True) +class Row: + """One phone as the table shows it""" + + id: str + #: Empty while nobody has named it + callsign: str + phone: str + joined: str + #: The state's sentence and the plugin's words + certificate: str + #: It has no callsign yet + waiting: bool + #: Its certificate was refused or failed: ask it again, or give it another callsign + failed: bool + #: It has its certificate + ready: bool + #: Asking it again can help, and the MDM can ask + askable: bool + + +@dataclass(frozen=True) +class FieldValue: + """A field of the chosen MDM and its value now; a secret's as typed, or as kept in the keychain""" + + field: Field + value: str + #: A secret kept in this computer's keychain, not only held until the connector stops + remembered: bool = False + + +@dataclass(frozen=True) +class Form: + """What setup asks for the chosen MDM""" + + name: str + title: str + fields: tuple[FieldValue, ...] + + +@dataclass(frozen=True) +class PreviewRow: + id: str + phone: str + joined: str + callsign: str + #: Why this one cannot be named, empty when it can + refusal: str + + +@dataclass(frozen=True) +class Preview: + """What naming would do, and every reason it cannot""" + + rows: tuple[PreviewRow, ...] + #: Why the batch as a whole cannot be named, empty when it can + refusal: str = "" + #: Said before naming, without stopping it + warning: str = "" + + @property + def ok(self) -> bool: + return bool(self.rows) and not self.refusal and not any(row.refusal for row in self.rows) + + @property + def names(self) -> dict[str, str]: + return {row.id: row.callsign for row in self.rows} + + @property + def button(self) -> str: + return f"Name {_count(len(self.rows), 'phone')}" + + +@dataclass(frozen=True) +class Detail: + """One phone, with what the app itself knows""" + + id: str + callsign: str + phone: str + joined: str + #: The state's sentence + state: str + #: The plugin's own words, may be empty + detail: str + #: Whether Deploy App accepts phones now, as the banner says it + window: str + can_ask_again: bool + + +class Job(Enum): + """What the worker was asked to do""" + + SETUP = "setup" + CHALLENGE = "challenge" + PHONES = "phones" + NAME = "name" + ASK_AGAIN = "ask again" + + +@dataclass(frozen=True) +class Result: + """A job done; error is its one sentence when it failed""" + + job: Job + error: str = "" + lines: tuple[str, ...] = () + steps: tuple[Step, ...] = () + phones: tuple[Phone, ...] | None = None + #: The phones named, by id, also when naming stopped half-way + named: dict[str, str] = field(default_factory=dict) + #: The Deploy App the job was for, which may no longer be the active one + host: str = "" + #: The MDM did not accept its secret: the operator has to type it again + unauthorized: bool = False + #: The MDM that did the job, so that a refusal of an MDM no longer held drops nothing + by: object = field(default=None, compare=False, repr=False) + + +def _askable(phone: Phone) -> bool: + """Whether asking again can help: it has a callsign, and its certificate failed or is still asked for + + A phone that has its certificate is left alone: asked again under the name it holds, it is refused as taken. + """ + return bool(phone.callsign) and (phone.state in FAILED or phone.state is State.WAITING) + + +def _count(number: int, noun: str) -> str: + return f"{number} {noun}{'' if number == 1 else 's'}" + + +def _sentence(text: str) -> str: + return text if text.endswith(".") else f"{text}." + + +def _banner(host: str, closes: datetime.datetime | None, now: datetime.datetime) -> Banner: + """Whether the Deploy App accepts phones, in the operator's time""" + if closes is None or not host: + return Banner( + Level.NONE, + "On the MDM page of Deploy App, press Open in the MDM connector to let phones enrol.", + "no enrolment window known", + ) + at = closes.astimezone(now.tzinfo).strftime("%H:%M") + if now >= closes: + return Banner( + Level.CLOSED, + f"Enrolment closed at {at}. Open enrolment again on the MDM page of Deploy App, " + "then press Open in the MDM connector there.", + f"enrolment closed at {at}", + ) + if closes - now <= CLOSING: + left = _count(math.ceil((closes - now).total_seconds() / 60), "minute") + return Banner( + Level.CLOSING, + f"Deploy App {host} accepts phones until {at}, {left} from now", + f"enrolment open until {at}, {left} left", + ) + return Banner(Level.OPEN, f"Deploy App {host} accepts phones until {at}", f"enrolment open until {at}") + + +def _admin(host: str) -> str: + """Where the Deploy App's admin pages are, its MDM page among them: the mtls. name of the deployment""" + return f"https://mtls.{host}" + + +def _read(text: str, now: datetime.datetime, sender: str) -> tuple[Settings, str]: + """The line's enrolment window and its Deploy App's host + + sender is the origin of the page that sent the line, such as https://mtls.unit.example.fi, or + empty for a line typed or pasted by hand. A line is taken only from its own Deploy App's pages. + """ + try: + window = settings.parse(text, now) + except settings.SettingsError as exc: + raise AppError(str(exc)) from exc + host = urlsplit(window.scep_url).hostname or "" + if sender and sender not in (f"https://{host}", _admin(host)): + raise AppError( + f"These settings are for Deploy App {host}, but the page that sent them is {sender}: " + "use the button on that Deploy App's own MDM page." + ) + return window, host + + +class Redact(logging.Formatter): + """Formats a log line, tracebacks included, with every secret it was told of blanked out""" + + def __init__(self) -> None: + super().__init__("%(asctime)s %(levelname)s %(name)s: %(message)s") + self.secrets: set[str] = set() + + def add(self, secret: str) -> None: + if secret: + self.secrets.add(secret) + + def scrub(self, text: str) -> str: + """The text with every secret blanked out""" + for secret in self.secrets: + text = text.replace(secret, "[secret]") + return text + + def format(self, record: logging.LogRecord) -> str: + return self.scrub(super().format(record)) + + +def open_log(directory: Path, redact: Redact) -> Path: + """Log to a file in the directory, through redact, and answer its path + + The handlers already there, such as the command line's on stderr, go through redact too. + """ + for handler in logging.getLogger().handlers: + handler.setFormatter(redact) + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + path = directory / "odmdm-connector.log" + handler = RotatingFileHandler(path, maxBytes=1_000_000, backupCount=2, encoding="utf-8") + handler.setFormatter(redact) + logging.getLogger().addHandler(handler) + logging.getLogger().setLevel(logging.INFO) + return path + + +class Worker: + """Runs jobs one at a time, in order, on one thread of its own; their results wait in a queue""" + + def __init__(self) -> None: + self._jobs: queue.Queue[Callable[[], Result] | None] = queue.Queue() + self.results: queue.Queue[Result] = queue.Queue() + threading.Thread(target=self._run, name="odmdm-connector-mdm", daemon=True).start() + + def _run(self) -> None: + while True: + job = self._jobs.get() + try: + if job is None: + return + self.results.put(job()) + finally: + self._jobs.task_done() + + def submit(self, job: Callable[[], Result]) -> None: + """job must not raise""" + self._jobs.put(job) + + def wait(self) -> None: + """Until every job submitted has finished""" + self._jobs.join() + + def stop(self) -> None: + self._jobs.put(None) + + +def _run(job: Job, work: Callable[[], Result], log_path: Path) -> Result: + """The work's result, or its failure as one sentence""" + try: + return work() + except MdmError as exc: + LOGGER.warning("%s failed: %s", job.value, exc) + return Result(job, error=str(exc), lines=tuple(exc.lines), named=exc.named, unauthorized=exc.unauthorized) + except OSError: + LOGGER.exception("%s failed", job.value) + return Result(job, error="Cannot reach the MDM.") + except Exception: # A plugin's bug reaches the operator as a sentence and leaves the worker running + LOGGER.exception("%s failed", job.value) + return Result(job, error=f"The MDM plugin failed; the log says more: {log_path}") + + +def _setup(mdm: Mdm, window: Settings, seen: Callable[[tuple[Step, ...]], None]) -> Result: + """The MDM's setup, each step shown as it is done, with the steps done before it stopped if it did""" + steps: list[Step] = [] + try: + for step in mdm.setup(window): + steps.append(step) + seen(tuple(steps)) + except MdmError as exc: + LOGGER.warning("Setup failed: %s", exc) + return Result(Job.SETUP, error=str(exc), steps=tuple(steps), unauthorized=exc.unauthorized) + return Result(Job.SETUP, steps=tuple(steps)) + + +def _name(mdm: Mdm, wanted: list[tuple[str, str]]) -> Result: + """Check the names against the phones as they are now, then name them""" + refused = core.refusal(mdm.phones(), wanted) + if refused: + return Result(Job.NAME, error=f"Nothing named: {refused}. Refresh and give callsigns again.") + return Result(Job.NAME, lines=tuple(mdm.name(dict(wanted))), named=dict(wanted)) + + +class App: + """The connector for one operator, as the page drives it""" + + def __init__( + self, + settings_store: store.Store, + *, + installed: Callable[[], list[plugins.Plugin]] = plugins.installed, + load: Callable[[str], type[Mdm]] = plugins.load, + redact: Redact | None = None, + log_path: Path = Path("odmdm-connector.log"), + keychain: store.Keychain | None = None, + ) -> None: + self.store = settings_store + #: Where a secret is kept between runs when the operator says remember; none without one + self.keychain = keychain if keychain is not None else store.Keychain(None) + #: The secrets typed, or taken from the keychain, since the start, by Deploy App, MDM and field + self._secrets: dict[tuple[str, str, str], str] = {} + #: Whether the keychain keeps each one, as read once, so that the keychain is asked again only after a + #: change: a keychain may ask the operator before it answers, and every request would wait for that + self._kept: dict[tuple[str, str, str], bool] = {} + self.redact = redact or Redact() + self.log_path = log_path + self._installed = installed + self._load_plugin = load + self.worker = Worker() + #: The last thing to tell the operator + self.status = "" + #: Every line the MDM handed back for the last naming or asking again, while status is about it + self.lines: tuple[str, ...] = () + try: + self.saved = settings_store.load() + except store.StoreError as exc: + self.saved = store.Saved() + self.status = str(exc) + self.mdm: Mdm | None = None + self.mdm_class: type[Mdm] | None = None + #: The enrolment window last pasted, challenge and all, in memory only + self.window: Settings | None = None + self.phones: list[Phone] = [] + #: Whether the MDM held now has listed its phones, so that none means none + self._listed = False + self._passed: dict[str, str] | None = None + #: The steps the setup under way has done so far, as the worker hands them over one by one + self._progress: tuple[Step, ...] = () + self._pending = dict.fromkeys(Job, 0) + # Say at once why the MDM set up before is not connected: its secrets went with the last run + if not self.status: + self.status = self._take_up() + + @classmethod + def default(cls) -> "App": + """The app on this computer: its settings file and log in the connector's own directory, and its keychain""" + redact = Redact() + log_path = open_log(store.directory(), redact) + keychain = store.Keychain(store.platform_backend()) + return cls(store.Store(store.directory()), redact=redact, log_path=log_path, keychain=keychain) + + @property + def keeps(self) -> bool: + """Whether a secret can be kept in this computer's keychain""" + return self.keychain.usable + + def close(self) -> None: + self.worker.stop() + + def _save(self, changed: store.Saved) -> None: + """Write the settings, and only then hold them""" + try: + self.store.save(changed) + except store.StoreError as exc: + raise AppError(str(exc)) from exc + self.saved = changed + + @property + def conn(self) -> store.Connection: + """The active connection, or an empty one when none is active""" + return self.saved.connections.get(self.saved.active, store.Connection()) + + def _save_conn(self, **changes: Any) -> None: + """Write the active connection with the changes""" + if not self.saved.active: + raise AppError("Add the Deploy App first: on its MDM page, press Open in the MDM connector.") + connections = {**self.saved.connections, self.saved.active: replace(self.conn, **changes)} + self._save(replace(self.saved, connections=connections)) + + def _drop(self) -> None: + """Let go of what is held for the active connection: its MDM, its enrolment window and its phones""" + self.mdm = self.mdm_class = self.window = self._passed = None + self.phones, self._listed, self._progress = [], False, () + + def _say(self, sentence: str, *lines: str) -> str: + """Say the sentence, with lines under it; what was said, the lines first""" + self.status, self.lines = sentence, lines + return " ".join([*lines, sentence]) + + # The MDM + + def mdms(self) -> list[plugins.Plugin]: + """The MDMs installed, none of them imported""" + try: + return self._installed() + except plugins.PluginError as exc: + raise AppError(str(exc)) from exc + + def _plugin(self, name: str) -> plugins.Plugin: + for plugin in self.mdms(): + if plugin.name == name: + return plugin + raise AppError(f"No MDM named {name} is installed.") + + def approval(self, name: str) -> str: + """What to ask before the MDM's plugin is used; empty when it is built in or approved as it is""" + plugin = self._plugin(name) + if plugin.built_in or f"{plugin.name} {plugin.package} {plugin.version}" in self.saved.approved: + return "" + return ( + f"The MDM {name} comes from the package {plugin.package} {plugin.version}, not with this app. " + "A plugin is code that sees the MDM token: use it only if you trust where it comes from." + ) + + def approve(self, name: str) -> None: + plugin = self._plugin(name) + others = [each for each in self.saved.approved if each.split()[0] != plugin.name] + self._save(replace(self.saved, approved=[*others, f"{plugin.name} {plugin.package} {plugin.version}"])) + LOGGER.info("Plugin approved: %s %s %s", plugin.name, plugin.package, plugin.version) + + def _class(self, name: str) -> type[Mdm]: + """The MDM's class, importing its plugin and no other, once it is approved""" + if self.approval(name): + raise AppError(f"The MDM {name} is a plugin that has not been approved in this app.") + try: + return self._load_plugin(name) + except plugins.PluginError as exc: + raise AppError(str(exc)) from exc + + @staticmethod + def _account(host: str, name: str, item: Field) -> tuple[str, str, str]: + """Whose secret it is: per Deploy App, so that two never share a token by accident""" + return host, name, item.key + + def _look(self, account: tuple[str, str, str]) -> None: + """Read the account's secret from the keychain, once, and hold it if none is held""" + if account in self._kept: + return + kept = self.keychain.get(":".join(account)) + self._kept[account] = bool(kept) + if kept and not self._secrets.get(account): + self._secrets[account] = kept + + def _secret(self, name: str, item: Field) -> str: + """The active Deploy App's secret: as held since the start, else as kept in the keychain""" + account = self._account(self.saved.active, name, item) + self._look(account) + return self._secrets.get(account, "") + + def _keep(self, name: str, chosen: type[Mdm], remember: bool) -> list[str]: + """Keep the active Deploy App's secrets in the keychain if remember, else remove any kept + + What to say of a secret the keychain did not take. + """ + notices = [] + for item in chosen.fields: + if not item.secret: + continue + account = self._account(self.saved.active, name, item) + secret = self._secrets.get(account, "") + self._kept.pop(account, None) + if not (remember and secret and self.keeps): + self.keychain.forget(":".join(account)) + elif not self.keychain.keep(":".join(account), secret): + notices.append( + f"This computer's keychain cannot be used, so the {item.label} is kept only until the connector " + "stops." + ) + return notices + + def _forget(self, host: str, name: str) -> bool: + """Let go of the secrets of the Deploy App's MDM, held and kept; whether the keychain holds none of them""" + self._secrets = {account: secret for account, secret in self._secrets.items() if account[0] != host} + self._kept = {account: kept for account, kept in self._kept.items() if account[0] != host} + if not name or not self.keeps: + return True + try: + chosen = self._class(name) + except AppError: + return False + accounts = [":".join(self._account(host, name, item)) for item in chosen.fields if item.secret] + left = [account for account in accounts if not self.keychain.forget(account)] + return not left + + def form(self, name: str) -> Form: + """The MDM's fields with their values: saved ones if it is the active connection's MDM, else the defaults""" + chosen = self._class(name) + saved = self.conn.values if self.conn.mdm == name else {} + return Form( + name, + chosen.title, + tuple( + FieldValue(item, self._secret(name, item), self._remembered(name, item)) + if item.secret + else FieldValue(item, saved.get(item.key, item.default)) + for item in chosen.fields + ), + ) + + def _remembered(self, name: str, item: Field) -> bool: + """Whether the active Deploy App's secret is kept in the keychain""" + account = self._account(self.saved.active, name, item) + self._look(account) + return self.keeps and self._kept[account] + + def _make(self, name: str, chosen: type[Mdm]) -> Mdm: + """The MDM, made from the saved values and the secrets, and held""" + values = {} + for item in chosen.fields: + values[item.key] = self._secret(name, item) if item.secret else self.conn.values.get(item.key, item.default) + if item.secret: + self.redact.add(values[item.key]) + try: + mdm = chosen(values) + except MdmError as exc: + raise AppError(str(exc)) from exc + self.mdm, self.mdm_class, self._listed = mdm, chosen, False + return mdm + + def _take_up(self) -> str: + """Take up the active connection's MDM, if still approved and its secrets are at hand; why not, or empty""" + name = self.conn.mdm + if not name: + return "" + try: + chosen = self._class(name) + lacking = [item.label for item in chosen.fields if item.secret and not self._secret(name, item)] + if lacking: + kept = "it is" if len(lacking) == 1 else "they are" + if self.keeps: + return f"Type the {' and '.join(lacking)} again to connect: {kept} not kept on this computer." + return f"Type the {' and '.join(lacking)} again to connect: {kept} kept only while the connector runs." + self._make(name, chosen) + except AppError as exc: + return str(exc) + return "" + + def connect(self, name: str, values: Mapping[str, str], remember: bool = True) -> str: + """Use this MDM with these values: secrets held in memory, the rest in the settings file + + A secret is kept in the keychain too if remember and one can be used; not remembered, any + copy kept there is removed. A secret given empty stands for the one held or kept for this + Deploy App and MDM only when every other value given is the one saved for it, so that a kept + secret never goes to an address it was not kept for. + + With an enrolment window held, its setup runs on the worker and its Result carries the steps. + Without one, an MDM already set up for the Deploy App is only connected, so its phones can be + seen on any day; one not set up yet is refused, as setup needs the window. + """ + chosen = self._class(name) + if not self.saved.active: + raise AppError("Add the Deploy App first: on its MDM page, press Open in the MDM connector.") + if self.window is None and self.conn.mdm != name: + raise AppError( + f"To set {chosen.title} up, open enrolment on the MDM page of Deploy App {self.saved.active}, " + "then press Open in the MDM connector there." + ) + plain = {item.key: values.get(item.key, item.default) for item in chosen.fields if not item.secret} + saved = {item.key: self.conn.values.get(item.key, item.default) for item in chosen.fields if not item.secret} + same = self.conn.mdm == name and plain == saved + given = dict(plain) + for item in chosen.fields: + if not item.secret: + continue + given[item.key] = values.get(item.key, "") + if not given[item.key].isprintable(): + raise AppError( + f"The {item.label} holds a line break or another character that cannot be part of it: copy it again." + ) + if not given[item.key] and self._secret(name, item): + if not same: + raise AppError(f"Type the {item.label} again: the settings changed.") + given[item.key] = self._secret(name, item) + for item in chosen.fields: + if item.required and not given[item.key].strip(): + raise AppError(f"Fill in {item.label}.") + self._save_conn(mdm=name, values=plain) + for item in chosen.fields: + if item.secret: + self._secrets[self._account(self.saved.active, name, item)] = given[item.key] + mdm, window = self._make(name, chosen), self.window + notices = self._keep(name, chosen, remember) + if window is None: + LOGGER.info("Connected to the MDM %s for Deploy App %s", name, self.saved.active) + return self._say(f"Connected to {chosen.title} for Deploy App {self.saved.active}.", *notices) + LOGGER.info("Connecting to the MDM %s for Deploy App %s", name, self.saved.active) + if SETUP in chosen.missing: + self._submit(Job.SETUP, lambda: Result(Job.SETUP, steps=(Step(chosen.missing[SETUP], False),))) + else: + self._progress = () + self._submit(Job.SETUP, lambda: _setup(mdm, window, self._show)) + return self._say(f"Setting {chosen.title} up for Deploy App {self.saved.active}.", *notices) + + @property + def connected(self) -> bool: + return self.mdm is not None + + # The Deploy Apps + + def connections(self, now: datetime.datetime) -> list[DeployApp]: + """The Deploy Apps saved, in the order they were added""" + return [ + DeployApp( + host, + self.banner(now) if host == self.saved.active else _banner(host, store.closes(each), now), + host == self.saved.active, + ) + for host, each in self.saved.connections.items() + ] + + def read_settings(self, text: str, now: datetime.datetime, sender: str = "") -> Reading: + """What the settings line says, taking nothing from it; sender as for paste_settings""" + window, host = _read(text, now, sender) + return Reading(host, _sentence(_banner(host, window.closes, now).text), host in self.saved.connections) + + def _activate(self, host: str, connection: store.Connection) -> bool: + """Save the connection and make it the active one; whether that changed which one is""" + changed = host != self.saved.active + self._save(replace(self.saved, connections={**self.saved.connections, host: connection}, active=host)) + if changed: + self._drop() + LOGGER.info("Working with Deploy App %s", host) + return changed + + def open(self, host: str, now: datetime.datetime) -> str: + """Make the saved connection to the Deploy App the active one, and take up its MDM""" + if host not in self.saved.connections: + raise AppError(f"There is no Deploy App {host} in this app.") + changed = self._activate(host, self.saved.connections[host]) + failed = self._take_up() if changed or self.mdm is None else "" + return self._say(" ".join(filter(None, [_sentence(self.banner(now).text), failed]))) + + def remove(self, host: str) -> str: + """Delete the connection to the Deploy App and its secrets, held and kept; if it was the active one, none is""" + gone = self.saved.connections.get(host) + if gone is None: + raise AppError(f"There is no Deploy App {host} in this app.") + active = host == self.saved.active + connections = {each: kept for each, kept in self.saved.connections.items() if each != host} + self._save(replace(self.saved, connections=connections, active="" if active else self.saved.active)) + if active: + self._drop() + forgotten = self._forget(host, gone.mdm) + LOGGER.info("Deploy App %s removed", host) + if not gone.mdm: + return self._say(f"Deploy App {host} is removed from this app.") + if not forgotten: + return self._say( + f"Deploy App {host} is removed from this app, but its MDM token may still be in this computer's " + f"keychain: delete the odmdm-connector item of {host} there by hand." + ) + return self._say(f"Deploy App {host} is removed from this app, and its MDM token from this computer.") + + # The enrolment window + + def paste_settings(self, text: str, now: datetime.datetime, sender: str = "") -> str: + """Take the settings line Deploy App's MDM page copied, and give the MDM its challenge + + A line for a Deploy App not saved yet adds a connection to it. Its Deploy App becomes the + active one. An MDM that cannot take a challenge by API gets none: challenge_note then says + what to do. sender is the origin of the page that sent the line, empty for one typed or + pasted by hand; a line sent from a page other than its own Deploy App's is refused. + """ + window, host = _read(text, now, sender) + closes = window.closes.isoformat() if window.closes else "" + connection = replace(self.saved.connections.get(host, store.Connection()), closes=closes) + changed = self._activate(host, connection) + failed = self._take_up() if changed or self.mdm is None else "" + self.redact.add(window.challenge) + self.window = window + LOGGER.info("Settings pasted for Deploy App %s, open until %s", host, closes) + until = self.banner(now).text + if self.mdm is None or self.challenge_note(): + return self._say(" ".join(filter(None, [f"{until}.", failed]))) + mdm = self.mdm + + def give() -> Result: + mdm.set_challenge(window) + return Result(Job.CHALLENGE) + + self._submit(Job.CHALLENGE, give) + return self._say(f"{until}. Giving the MDM the new challenge.") + + def challenge_note(self) -> str: + """The plugin's sentence for an MDM that cannot take the challenge by API, when one is held""" + if self.window is None or self.mdm_class is None: + return "" + return self.mdm_class.missing.get(SET_CHALLENGE, "") + + def challenge(self) -> str: + """The challenge, only for an MDM that has to be given it by hand""" + return self.window.challenge if self.window and self.challenge_note() else "" + + def banner(self, now: datetime.datetime) -> Banner: + """Whether the active Deploy App accepts phones, in the operator's time""" + closes = self.window.closes if self.window else store.closes(self.conn) + return _banner(self.saved.active, closes, now) + + @property + def mdm_page(self) -> str: + """The active Deploy App's MDM page, where enrolment is opened; empty while none is active""" + return f"{_admin(self.saved.active)}/mdm" if self.saved.active else "" + + # The phones + + def refresh(self) -> None: + """List the phones again on the worker, unless a listing is under way""" + if self.mdm is None or self._pending[Job.PHONES]: + return + mdm = self.mdm + self._submit(Job.PHONES, lambda: Result(Job.PHONES, phones=tuple(mdm.phones()))) + + @staticmethod + def _joined(phone: Phone, now: datetime.datetime) -> tuple[str, datetime.datetime | None]: + """When it joined, in the operator's time, and as a time if it is one""" + try: + when = datetime.datetime.fromisoformat(phone.joined) + except ValueError: + return phone.joined, None + if when.tzinfo is None: + when = when.replace(tzinfo=datetime.UTC) + return when.astimezone(now.tzinfo).strftime("%Y-%m-%d %H:%M"), when + + def rows(self, now: datetime.datetime) -> list[Row]: + """The table, oldest first as the MDM lists them""" + return [ + Row( + phone.id, + phone.callsign, + phone.model, + self._joined(phone, now)[0], + core.said(phone), + not phone.callsign, + phone.state in FAILED, + phone.state is State.READY, + self._askable(phone), + ) + for phone in self.phones + ] + + def _askable(self, phone: Phone) -> bool: + """Whether asking the phone again can help, with an MDM that can ask""" + return bool(self.mdm and ASK_AGAIN not in self.mdm.missing) and _askable(phone) + + def summary(self) -> str: + """How many phones there are and where they are; empty while no MDM is connected or none is listed yet""" + if self.mdm is None: + return "" + if not self.phones: + return "No phones yet." if self._listed else "" + named = [phone for phone in self.phones if phone.callsign] + ready = sum(phone.state is State.READY for phone in named) + failed = sum(phone.state in FAILED for phone in named) + parts = [ + (ready, "ready"), + (len(named) - ready - failed, "waiting for the phone"), + (failed, "failed"), + (len(self.phones) - len(named), "without a name"), + ] + return f"{_count(len(self.phones), 'phone')}: " + ", ".join(f"{n} {word}" for n, word in parts if n) + + def detail(self, phone_id: str, now: datetime.datetime) -> Detail: + phone = next((each for each in self.phones if each.id == phone_id), None) + if phone is None: + raise AppError(f"Phone {phone_id} is no longer in the MDM's list: refresh.") + return Detail( + phone.id, + phone.callsign, + phone.model, + self._joined(phone, now)[0], + phone.state.value, + phone.detail, + self.banner(now).text, + self._askable(phone), + ) + + # Naming + + def targets(self, selected: Sequence[str]) -> list[str]: + """The phones to name, in table order: the selected ones, or with none, every one without a name""" + chosen = set(selected) + return [phone.id for phone in self.phones if (phone.id in chosen if chosen else not phone.callsign)] + + def first_number(self, prefix: str) -> int: + """The number to start from: one above the highest prefix in use""" + return core.next_number(self.phones, prefix) + + @staticmethod + def numbered(prefix: str, start: int, count: int) -> list[str]: + return [f"{prefix}{start + n}" for n in range(count)] + + @staticmethod + def listed(text: str) -> list[str]: + """A list of callsigns as typed, one per line""" + return [line.strip() for line in text.splitlines() if line.strip()] + + def keep_callsigns(self, prefix: str, callsigns: Sequence[str]) -> None: + """Keep the prefix and the list for the active Deploy App next time, also before any phone has joined""" + self._save_conn(prefix=prefix, callsigns=list(callsigns)) + + def preview(self, ids: Sequence[str], callsigns: Sequence[str], now: datetime.datetime) -> Preview: + """What naming the phones with the callsigns, in order, would do, by the naming rules + + Only a preview that passed can then be named. + """ + found = {phone.id: phone for phone in self.phones} + rows: list[PreviewRow] = [] + fine: list[tuple[str, str]] = [] + for index, phone_id in enumerate(ids): + callsign = callsigns[index] if index < len(callsigns) else "" + phone = found.get(phone_id) + if not callsign: + refused = "no callsign left in the list" + else: + refused = core.refusal(self.phones, [(phone_id, callsign)]) or core.refusal( + self.phones, [*fine, (phone_id, callsign)] + ) + if not refused: + fine.append((phone_id, callsign)) + joined = self._joined(phone, now)[0] if phone else "" + rows.append(PreviewRow(phone_id, phone.model if phone else "", joined, callsign, refused)) + refusal = "" + if not ids: + refusal = "No phone is waiting for a name. To give a phone another callsign, select it first." + elif len(callsigns) < len(ids): + refusal = f"{_count(len(ids), 'phone')} to name, but only {_count(len(callsigns), 'callsign')}." + recent = [phone for phone in self.phones if self._recent(phone, now)] + warning = "" + if len(recent) == 1: + warning = ( + "A phone joined less than 10 minutes ago and may still be installing its apps. Naming now sends " + "the policy to every phone again, which stops apps that are still installing: wait until it has " + "its apps." + ) + elif recent: + warning = ( + f"{len(recent)} phones joined less than 10 minutes ago and may still be installing their apps. " + "Naming now sends the policy to every phone again, which stops apps that are still installing: " + "wait until they have their apps." + ) + result = Preview(tuple(rows), refusal, warning) + self._passed = result.names if result.ok else None + return result + + def _recent(self, phone: Phone, now: datetime.datetime) -> bool: + when = self._joined(phone, now)[1] + return when is not None and now - when < RECENT + + def name(self, names: Mapping[str, str]) -> str: + """Name the phones of the preview that passed last, on the worker""" + if self.mdm is None: + raise AppError("Connect to the MDM first.") + if self._passed is None or dict(names) != self._passed: + raise AppError("Preview the callsigns first: nothing is named without a preview that passed.") + self._passed = None + mdm, wanted = self.mdm, list(names.items()) + self._submit(Job.NAME, lambda: _name(mdm, wanted)) + return self._say(f"Naming {_count(len(wanted), 'phone')}.") + + def ask_again(self, ids: Sequence[str]) -> str: + """Have the phones ask for their certificates again; no ids: every named one that failed""" + if self.mdm is None: + raise AppError("Connect to the MDM first.") + if ASK_AGAIN in self.mdm.missing: + raise AppError(self.mdm.missing[ASK_AGAIN]) + if not ids: + mdm = self.mdm + self._submit(Job.ASK_AGAIN, lambda: Result(Job.ASK_AGAIN, lines=tuple(mdm.ask_again([])))) + return self._say("Asking every named phone whose certificate failed again.") + wanted = set(ids) + chosen = [phone.id for phone in self.phones if phone.id in wanted and _askable(phone)] + if not chosen: + raise AppError( + "Nothing to ask again: the selected phones have their certificates, or have no callsign yet." + ) + mdm, left = self.mdm, len(wanted) - len(chosen) + self._submit(Job.ASK_AGAIN, lambda: Result(Job.ASK_AGAIN, lines=tuple(mdm.ask_again(chosen)))) + if left: + return self._say(f"Asking {_count(len(chosen), 'phone')} again; {_count(left, 'phone')} left alone.") + return self._say("Asking again.") + + # The worker + + def _submit(self, job: Job, work: Callable[[], Result]) -> None: + self._pending[job] += 1 + log_path, host, by = self.log_path, self.saved.active, self.mdm + self.worker.submit(lambda: replace(_run(job, work, log_path), host=host, by=by)) + + def busy(self, job: Job | None = None) -> bool: + """Whether a job, or that kind of job, is under way""" + return bool(self._pending[job]) if job else any(self._pending.values()) + + def drain(self) -> list[Result]: + """The results finished since the last drain, taken in; called on the view's timer""" + done: list[Result] = [] + while True: + try: + result = self.worker.results.get_nowait() + except queue.Empty: + return done + self._pending[result.job] -= 1 + result = self._scrubbed(result) + self._take(result) + done.append(result) + + def _show(self, steps: tuple[Step, ...]) -> None: + """Called on the worker: the steps the setup has done so far""" + self._progress = steps + + @property + def progress(self) -> tuple[Step, ...]: + """The steps the setup under way has done so far, for a view to tick them as they come""" + return self._clean(self._progress) + + def _clean(self, steps: tuple[Step, ...]) -> tuple[Step, ...]: + scrub = self.redact.scrub + return tuple(replace(step, label=scrub(step.label), message=scrub(step.message)) for step in steps) + + def _scrubbed(self, result: Result) -> Result: + """The result with every secret the app was told of blanked out, as an MDM's answer may echo one""" + scrub = self.redact.scrub + return replace( + result, + error=scrub(result.error), + lines=tuple(scrub(line) for line in result.lines), + steps=self._clean(result.steps), + ) + + def _take(self, result: Result) -> None: + """What a result changes in the app, and what the status line says of it + + A result for a Deploy App no longer active changes nothing the app holds, and is still said. + """ + for line in result.lines: + LOGGER.info("%s: %s", result.job.value, line) + current = result.host == self.saved.active + if current and result.unauthorized and result.by is self.mdm is not None: + # The secret is not accepted, so it is let go of, kept copy and all, and the MDM with it, until typed again + self._forget(result.host, self.conn.mdm) + self.mdm, self.phones, self._listed = None, [], False + if current and result.phones is not None and self.mdm is not None: + self.phones, self._listed = list(result.phones), True + if current and result.named and self.conn.callsigns: + used = {callsign.lower() for callsign in result.named.values()} + try: + self._save_conn(callsigns=[each for each in self.conn.callsigns if each.lower() not in used]) + except AppError as exc: + LOGGER.warning("%s", exc) + if current and result.job in (Job.NAME, Job.ASK_AGAIN): + self.refresh() + title = self.mdm_class.title if self.mdm_class else "The MDM" + if result.error: + stopped = "" + if result.named: + done = ", ".join(f"{phone} as {callsign}" for phone, callsign in result.named.items()) + stopped = f" Named before it stopped: {done}." + self._say(result.error + stopped) + elif result.job is Job.SETUP and (any(not step.done for step in result.steps) or self.challenge_note()): + self._say(f"Do the steps by hand to finish setting {title} up for Deploy App {result.host}.") + elif result.job is Job.SETUP: + self._say(f"{title} is set up for Deploy App {result.host}.") + elif result.job is Job.CHALLENGE: + self._say(f"{title} has the new challenge.") + elif result.job is Job.NAME: + self._say(f"{_count(len(result.named), 'phone')} named.") + elif result.job is Job.ASK_AGAIN: + self._say("Asked again." if result.lines else "No phone needed asking again.") + if result.job in (Job.NAME, Job.ASK_AGAIN): + self.lines = result.lines From 5b7af23dc5f209a00301d64a9af14d8241848fe5 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:49 +0200 Subject: [PATCH 052/104] feat: serve the connector as a page on this computer On 127.0.0.1 only, the App called under one lock. A request to /api/ needs the key the printed address carries in its fragment, as a header; the Host and, for a POST, the Origin are checked. --- src/odmdm_connector/web.py | 418 +++++++++++++++++++++++++++++++++++++ 1 file changed, 418 insertions(+) create mode 100644 src/odmdm_connector/web.py diff --git a/src/odmdm_connector/web.py b/src/odmdm_connector/web.py new file mode 100644 index 0000000..4981be8 --- /dev/null +++ b/src/odmdm_connector/web.py @@ -0,0 +1,418 @@ +"""The connector as a page served on this computer, the second face of App beside the command line + +A standard library HTTP server on 127.0.0.1 only, a thread per connection, so that a connection a +browser opens and leaves idle holds nothing up; the App is called by one of them at a time. It +serves three fixed files and JSON answers; every decision is App's, and the page draws what they say. + +A request is answered only when it names this computer's address in its Host header, which stops +a page elsewhere from reaching this one through DNS rebinding. The three files are public code and +need nothing more. Everything under /api/ carries the header X-ODMDM-Key, holding the key made at +start that the address printed hands the page in its fragment, which no server is sent: so another +user or program on the computer cannot drive the page. A cookie would not do, as a browser sends a +cookie for 127.0.0.1 to every port of it. A POST must come from the page itself, by its Origin +header. No answer and +no log line holds the MDM token or the settings line; the challenge is in an answer only when the +MDM has to be given it by hand. +""" + +import datetime +import json +import logging +import secrets +import sys +import threading +import time +from collections.abc import Callable, Mapping +from dataclasses import asdict +from http import HTTPStatus +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import resources +from typing import Any +from urllib.parse import urlsplit + +from . import __version__ +from .app import App, AppError, Banner, Job, Result + +LOGGER = logging.getLogger(__name__) + +PORT = 8737 +#: The largest request body taken +LIMIT = 64 * 1024 +#: The request header that carries the page's key +KEY = "X-ODMDM-Key" +#: Seconds between listings of the phones while the page asks for its state +REFRESH = 60.0 +#: Seconds a connection may stay silent before it is dropped +TIMEOUT = 5 +#: The only files served, by request path: no path from a request reaches the file system +STATIC = { + "/": ("index.html", "text/html; charset=utf-8"), + "/app.css": ("app.css", "text/css; charset=utf-8"), + "/app.js": ("app.js", "text/javascript; charset=utf-8"), +} +HEADERS = { + "Cache-Control": "no-store", + "Content-Security-Policy": "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", +} +FORBIDDEN = "Open the address that the connector printed when it started. This page then goes on by itself." + +Body = dict[str, Any] + + +def _now() -> datetime.datetime: + return datetime.datetime.now().astimezone() + + +def _text(body: Body, key: str) -> str: + value = body.get(key, "") + if not isinstance(value, str): + raise AppError(f"The page sent {key} as something other than text.") + return value + + +def _texts(body: Body, key: str) -> list[str]: + value = body.get(key, []) + if not isinstance(value, list) or not all(isinstance(each, str) for each in value): + raise AppError(f"The page sent {key} as something other than a list of text.") + return value + + +def _banner(banner: Banner) -> dict[str, str]: + return {"level": banner.level.value, "text": banner.text} + + +class Page(ThreadingHTTPServer): + """The page's server: on this computer only, with a key made at start, and the App called under one lock""" + + # On Windows the option lets another program bind the same port and take the page's requests + allow_reuse_address = sys.platform != "win32" + daemon_threads = True + + def __init__( + self, + app: App, + port: int = PORT, + now: Callable[[], datetime.datetime] = _now, + clock: Callable[[], float] = time.monotonic, + ) -> None: + super().__init__(("127.0.0.1", port), Handler) + self.app, self.now, self.clock = app, now, clock + self.port: int = self.server_address[1] + self.key = secrets.token_urlsafe(32) + #: Held around every call into the App, so that it sees one caller at a time + self.lock = threading.Lock() + self.hosts = {f"127.0.0.1:{self.port}", f"localhost:{self.port}"} + self.origins = {f"http://{host}" for host in self.hosts} + #: The steps of the last setup, as its result brought them, and its error, empty when it passed + self.steps: list[dict[str, Any]] = [] + self.setup_error = "" + #: When the phones were last asked for, by clock; None before the first time + self.listed: float | None = None + #: The Deploy App whose phones arrived last, and the hour and minute they did, in the operator's time + self.updated = ("", "") + + @property + def address(self) -> str: + """Where the operator opens the page: the key in the fragment, which the browser sends to no server""" + return f"http://127.0.0.1:{self.port}/#key={self.key}" + + def handle_error(self, request: Any, client_address: Any) -> None: + """A request that failed outside the answers goes to the log, not the terminal + + A connection the browser dropped or left silent is one line naming its kind. + """ + failure = sys.exception() + if isinstance(failure, OSError): + LOGGER.info("A connection to the page ended: %s", type(failure).__name__) + else: + LOGGER.exception("The page could not answer a request") + + def _take(self, results: list[Result], now: datetime.datetime) -> None: + for result in results: + if result.job is Job.SETUP: + self.steps, self.setup_error = [asdict(step) for step in result.steps], result.error + elif result.job is Job.PHONES and result.phones is not None: + self.updated = (result.host, now.strftime("%H:%M")) + + def _list(self) -> None: + """Ask for the phones, when an MDM is connected""" + if self.app.connected: + self.app.refresh() + self.listed = self.clock() + + def state(self) -> Body: + """Everything the page draws, after taking in the worker's results + + The phones are asked for again once REFRESH seconds have passed, so they are listed only + while a page is open and asking. + """ + app, now = self.app, self.now() + self._take(app.drain(), now) + if self.listed is None or self.clock() - self.listed >= REFRESH: + self._list() + conn = app.conn + return { + "version": __version__, + # Each Deploy App with a few words on its enrolment window, for the list of them + "connections": [ + {"host": each.host, "level": each.banner.level.value, "short": each.banner.short, "active": each.active} + for each in app.connections(now) + ], + "active": app.saved.active, + "banner": _banner(app.banner(now)), + # Where the operator opens enrolment again, in a tab of its own + "mdm_page": app.mdm_page, + "mdm": conn.mdm, + "connected": app.connected, + # Whether a secret can be kept in this computer's keychain, so the page offers to remember it + "keeps": app.keeps, + # What stops the MDM being connected: none chosen yet, or its secret not at hand + "needs": "" if app.connected or not app.saved.active else ("secret" if conn.mdm else "mdm"), + "mdms": [ + {"name": each.name, "package": each.package, "version": each.version, "built_in": each.built_in} + for each in app.mdms() + ], + # While a setup runs, the steps it has done so far; after it, the steps its result brought + "steps": self.steps or [asdict(step) for step in app.progress], + "setup_error": self.setup_error, + "summary": app.summary(), + "rows": [asdict(row) for row in app.rows(now)], + "status": app.status, + # When the phones of the active Deploy App were last listed, as HH:MM; empty before the first time + "updated": self.updated[1] if self.updated[0] == app.saved.active and app.connected else "", + "lines": list(app.lines), + "busy": [job.value for job in Job if app.busy(job)], + "challenge_note": app.challenge_note(), + "challenge": app.challenge(), + "prefix": conn.prefix, + "callsigns": conn.callsigns, + "log": str(app.log_path), + } + + # The answers to the page's POSTs, each from its JSON body + + def read(self, body: Body) -> Body: + return asdict(self.app.read_settings(_text(body, "line"), self.now(), _text(body, "from"))) + + def add(self, body: Body) -> Body: + said = self.app.paste_settings(_text(body, "line"), self.now(), _text(body, "from")) + self._list() + return {"said": said} + + def open(self, body: Body) -> Body: + said = self.app.open(_text(body, "host"), self.now()) + self._list() + return {"said": said} + + def remove(self, body: Body) -> Body: + return {"said": self.app.remove(_text(body, "host"))} + + def form(self, body: Body) -> Body: + """The question before a plugin is used, or the MDM's fields with their values, never a secret's""" + name = _text(body, "mdm") + question = self.app.approval(name) + if question: + return {"approval": question} + form = self.app.form(name) + return { + "name": form.name, + "title": form.title, + "fields": [ + { + **asdict(each.field), + "value": "" if each.field.secret else each.value, + "kept": each.field.secret and bool(each.value), + "remembered": each.remembered, + } + for each in form.fields + ], + } + + def approve(self, body: Body) -> Body: + self.app.approve(_text(body, "mdm")) + return {} + + def connect(self, body: Body) -> Body: + """Connect with the values typed; a secret left empty is the one kept, as App.connect allows + + remember keeps the secrets in this computer's keychain; without it, any kept copy is removed. + """ + name = _text(body, "mdm") + given, remember = body.get("values", {}), body.get("remember", False) + if not isinstance(given, dict) or not all(isinstance(each, str) for each in given.values()): + raise AppError("The page sent the values as something other than text.") + if not isinstance(remember, bool): + raise AppError("The page sent remember as something other than yes or no.") + self.steps, self.setup_error = [], "" + said = self.app.connect(name, given, remember) + self._list() + return {"said": said} + + def refresh(self, body: Body) -> Body: + self._list() + return {} + + def preview(self, body: Body) -> Body: + """What naming the phones chosen would do, and the first number a numbered batch starts from""" + app = self.app + ids = app.targets(_texts(body, "ids")) + if _text(body, "how") == "list": + found, start = app.preview(ids, app.listed(_text(body, "list")), self.now()), 0 + else: + prefix, first = _text(body, "prefix").strip(), _text(body, "first").strip() + if first and not first.isdigit(): + raise AppError("The first number must be a whole number.") + start = int(first) if first else app.first_number(prefix) + found = app.preview(ids, app.numbered(prefix, start, len(ids)), self.now()) + return {**asdict(found), "ok": found.ok, "button": found.button, "first": start} + + def name(self, body: Body) -> Body: + """Name what the preview shown held, which the App takes only if it is the preview that passed last + + The callsigns are kept for next time too: a numbered batch's prefix, and a list if asked to save it. + """ + names, save = body.get("names"), body.get("save", False) + if not isinstance(names, dict) or not all(isinstance(each, str) for each in names.values()): + raise AppError("The page sent the names as something other than text.") + if not isinstance(save, bool): + raise AppError("The page sent save as something other than yes or no.") + app = self.app + said = app.name(names) + if _text(body, "how") == "list": + if save: + app.keep_callsigns(app.conn.prefix, app.listed(_text(body, "list"))) + else: + app.keep_callsigns(_text(body, "prefix").strip(), app.conn.callsigns) + return {"said": said} + + def again(self, body: Body) -> Body: + return {"said": self.app.ask_again(_texts(body, "ids"))} + + def detail(self, body: Body) -> Body: + return asdict(self.app.detail(_text(body, "id"), self.now())) + + +#: The POST answers by path +ACTIONS: Mapping[str, Callable[[Page, Body], Body]] = { + "/api/read": Page.read, + "/api/add": Page.add, + "/api/open": Page.open, + "/api/remove": Page.remove, + "/api/form": Page.form, + "/api/approve": Page.approve, + "/api/connect": Page.connect, + "/api/refresh": Page.refresh, + "/api/preview": Page.preview, + "/api/name": Page.name, + "/api/again": Page.again, + "/api/detail": Page.detail, +} + + +class Handler(BaseHTTPRequestHandler): + """One request: checked, then a fixed file, the state or an answer""" + + server: Page + timeout = TIMEOUT + server_version = "odmdm-connector" + + def version_string(self) -> str: + """The Server header: the name alone, without Python's version""" + return self.server_version + + def log_message(self, format: str, *args: Any) -> None: + """No request log: the first request's address holds the key""" + + def _answer(self, status: int, body: bytes, kind: str) -> None: + self.send_response(status) + headers = {**HEADERS, "Content-Type": kind, "Content-Length": str(len(body))} + for header, value in headers.items(): + self.send_header(header, value) + self.end_headers() + self.wfile.write(body) + + def _plain(self, status: int, sentence: str) -> None: + self._answer(status, sentence.encode(), "text/plain; charset=utf-8") + + def _json(self, status: int, data: Body) -> None: + self._answer(status, json.dumps(data).encode(), "application/json") + + def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None: + """http.server's own refusals, such as a malformed request, in the same plain form""" + self.close_connection = True + self._plain(code, message or HTTPStatus(code).phrase) + + def _refuse(self) -> None: + self._plain(HTTPStatus.FORBIDDEN, FORBIDDEN) + + def _here(self) -> bool: + """Whether the request came to this computer's address, in its one Host header; refused if not""" + hosts = self.headers.get_all("Host") or [] + if len(hosts) == 1 and hosts[0] in self.server.hosts: + return True + self._refuse() + return False + + def _admitted(self) -> bool: + """Whether the request came to this computer's address with the key in its one key header; refused if not""" + if not self._here(): + return False + given = self.headers.get_all(KEY) or [] + if len(given) == 1 and secrets.compare_digest(given[0].encode(), self.server.key.encode()): + return True + self._refuse() + return False + + def do_GET(self) -> None: + if not self._here(): + return + url = urlsplit(self.path) + if url.path in STATIC: + name, kind = STATIC[url.path] + self._answer(HTTPStatus.OK, resources.files(__package__).joinpath("static", name).read_bytes(), kind) + elif self._admitted(): + if url.path == "/api/state": + self._call(lambda: self.server.state()) + else: + self._plain(HTTPStatus.NOT_FOUND, "Not found.") + + def do_POST(self) -> None: + if not self._admitted(): + return + if self.headers.get("Origin") not in self.server.origins: + self._refuse() + return + action = ACTIONS.get(self.path) + if action is None: + self._plain(HTTPStatus.NOT_FOUND, "Not found.") + return + length = self.headers.get("Content-Length", "") + if not length.isdigit() or int(length) > LIMIT: + self._plain(HTTPStatus.BAD_REQUEST, "The request has no length or is too large.") + return + try: + body = json.loads(self.rfile.read(int(length)) or b"{}") + except (ValueError, RecursionError): + body = None + if not isinstance(body, dict): + self._plain(HTTPStatus.BAD_REQUEST, "The request is not a JSON object.") + return + self._call(lambda: action(self.server, body)) + + def _call(self, answer: Callable[[], Body]) -> None: + """The answer as JSON, made under the lock; an AppError is its sentence, anything else points at the log""" + try: + with self.server.lock: + data = answer() + except AppError as exc: + self._json(HTTPStatus.BAD_REQUEST, {"error": str(exc)}) + except Exception: # A bug reaches the operator as a sentence, and the page goes on + LOGGER.exception("The page's request %s failed", urlsplit(self.path).path) + self._json( + HTTPStatus.INTERNAL_SERVER_ERROR, + {"error": f"The connector failed; the log says more: {self.server.app.log_path}"}, + ) + else: + self._json(HTTPStatus.OK, data) From 1c1fa74a3b99d664ca56f0a827731092bf8e502d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:49 +0200 Subject: [PATCH 053/104] feat: the page's markup --- src/odmdm_connector/static/index.html | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/odmdm_connector/static/index.html diff --git a/src/odmdm_connector/static/index.html b/src/odmdm_connector/static/index.html new file mode 100644 index 0000000..29ddba0 --- /dev/null +++ b/src/odmdm_connector/static/index.html @@ -0,0 +1,22 @@ + + + + + + + ODMDM connector + + + + +
+
ODMDM connector
+
+

Loading…

+ +
+
+ + + + From f4d1eaa3103256679b42f0d2ba4396713bca9b54 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:49 +0200 Subject: [PATCH 054/104] feat: the page's style --- src/odmdm_connector/static/app.css | 1203 ++++++++++++++++++++++++++++ 1 file changed, 1203 insertions(+) create mode 100644 src/odmdm_connector/static/app.css diff --git a/src/odmdm_connector/static/app.css b/src/odmdm_connector/static/app.css new file mode 100644 index 0000000..376e9ce --- /dev/null +++ b/src/odmdm_connector/static/app.css @@ -0,0 +1,1203 @@ +/* Deploy App's dark look: setting up is one card at a time, as its login is; the daily work is the + earlier window's layout across the whole width, with the browser's own dialogs over it */ + +:root { + --page: #1a1a1a; + --text: #ffffff; + --muted: #a3a3a3; + --dim: #808080; + --card: #222222; + --raise: #2a2a2a; + --table: #1e1e1e; + --line: #333333; + --line-strong: #444444; + --field: #1c1c1c; + --main: #ff6b1a; + --main-press: #e85d10; + --main-done: #a14a17; + --amber: #f5a524; + --red: #ff6b6b; + --green: #4cc38a; + color-scheme: dark; +} + +* { + box-sizing: border-box; +} + +html { + background: var(--page); +} + +body { + margin: 0; + background: var(--page); + color: var(--text); + font-family: "Geist Mono", ui-monospace, Menlo, Consolas, monospace; + font-size: 15px; + line-height: 1.45; +} + +button { + font: inherit; + color: inherit; + cursor: pointer; +} + +button:disabled { + cursor: default; +} + +p { + margin: 0 0 16px; + overflow-wrap: anywhere; +} + +h1 { + font-size: 18px; + margin: 0 0 6px; + overflow-wrap: anywhere; +} + +h2 { + font-size: 15px; + margin: 8px 0 8px; +} + +h3 { + font-size: 15px; + margin: 0 0 10px; + overflow-wrap: anywhere; +} + +.muted { + color: var(--muted); +} + +.error { + color: var(--red); +} + +.warn { + color: var(--amber); +} + +[hidden] { + display: none !important; +} + +input[type="text"]:focus-visible, +textarea:focus-visible { + outline: none; + box-shadow: 0 0 0 1px var(--main); +} + +button:focus-visible, +input[type="checkbox"]:focus-visible, +summary:focus-visible, +a:focus-visible, +tr:focus-visible { + outline: 2px solid var(--main); + outline-offset: 2px; +} + +/* Buttons */ + +.main, +.second { + display: block; + width: 100%; + min-height: 56px; + border-radius: 10px; + font-weight: 700; + margin: 0 0 12px; + padding: 8px 16px; +} + +.main { + background: var(--main); + color: #ffffff; + border: 1px solid var(--main); +} + +.main:hover:not(:disabled) { + background: var(--main-press); +} + +.main:disabled { + opacity: 0.45; +} + +.main.plain { + background: transparent; + border-color: var(--line-strong); +} + +.main.danger { + background: transparent; + color: var(--red); + border-color: var(--red); +} + +.second { + background: transparent; + border: 1px solid var(--line-strong); +} + +.second:hover:not(:disabled), +.choice:hover, +.tool:hover:not(:disabled) { + border-color: var(--main); +} + +.back { + background: none; + border: 0; + padding: 0; + color: var(--muted); + text-decoration: underline; + text-underline-offset: 3px; +} + +.back:hover { + color: var(--text); +} + +.choice { + display: block; + width: 100%; + min-height: 56px; + background: var(--field); + border: 1px solid var(--line); + border-radius: 10px; + text-align: left; + padding: 12px 16px; + margin: 0 0 12px; +} + +.choice strong { + display: block; + overflow-wrap: anywhere; +} + +.choice span { + color: var(--muted); + font-size: 13px; +} + +.closing { + color: var(--amber); +} + +.closed { + color: var(--red); +} + +/* Inputs */ + +label { + display: block; + margin: 0 0 8px; +} + +input[type="text"], +textarea { + display: block; + width: 100%; + min-height: 48px; + background: var(--field); + color: var(--text); + border: 1px solid var(--line); + border-radius: 10px; + padding: 12px; + font: inherit; + margin: 0 0 20px; +} + +input[type="text"]:focus, +textarea:focus { + border-color: var(--main); +} + +input::placeholder, +textarea::placeholder { + color: #6b6b6b; +} + +/* A secret is plain text to the browser, so that no password manager offers to keep it, and masked here */ +.secret { + -webkit-text-security: disc; +} + +textarea { + resize: vertical; + line-height: 1.3; +} + +input[type="checkbox"] { + width: 18px; + height: 18px; + margin: 0; + accent-color: var(--main); +} + +.check { + display: flex; + gap: 10px; + align-items: center; + margin: -6px 0 22px; +} + +.hint { + font-size: 13px; + margin: -12px 0 20px; +} + +/* ---------- Setting up: one card, one thing ---------- */ + +body.cards { + min-height: 100vh; + padding: 64px 16px 48px; +} + +.brand { + text-align: center; + color: var(--muted); + font-size: 14px; + letter-spacing: 0.04em; + margin-bottom: 28px; + overflow-wrap: anywhere; +} + +.card { + max-width: 28rem; + margin: 0 auto; + background: var(--card); + border: 1px solid var(--line); + border-radius: 16px; + padding: 24px; +} + +.lead { + color: var(--muted); + margin: 0 0 22px; +} + +.topline { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + font-size: 13px; + color: var(--muted); + margin-bottom: 12px; +} + +/* How far a first set-up is: three parts, each named under its line */ +.progress { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 6px; + list-style: none; + margin: 0 0 24px; + padding: 0; +} + +.progress li { + border-top: 4px solid var(--line-strong); + padding-top: 6px; + font-size: 12px; + color: var(--dim); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.progress li.done { + border-color: var(--main-done); + color: var(--muted); +} + +.progress li.now { + border-color: var(--main); + color: var(--text); + font-weight: 700; +} + +/* A picture of the button on Deploy App's page: nothing here to press */ +.lookfor { + border: 1px dashed #4a4a4a; + border-radius: 12px; + padding: 14px 16px 16px; + margin: 0 0 18px; + text-align: center; + pointer-events: none; + user-select: none; +} + +.lookfor small { + display: block; + color: var(--muted); + font-size: 12px; + margin-bottom: 10px; +} + +.lookfor span { + display: inline-block; + border-radius: 8px; + background: var(--main); + color: #ffffff; + font-weight: 700; + font-size: 14px; + padding: 10px 16px; +} + +.waiting { + display: flex; + align-items: center; + gap: 10px; + color: var(--muted); + margin: 0; +} + +.pulse { + flex: none; + width: 9px; + height: 9px; + border-radius: 50%; + background: var(--main); + animation: pulse 1.6s ease-in-out infinite; +} + +@keyframes pulse { + 50% { + box-shadow: 0 0 0 5px rgba(255, 107, 26, 0.25); + opacity: 0.6; + } +} + +@media (prefers-reduced-motion: reduce) { + .pulse { + animation: none; + } +} + +.or { + display: flex; + align-items: center; + gap: 12px; + color: var(--muted); + font-size: 11px; + margin: 20px 0; +} + +.or::before, +.or::after { + content: ""; + flex: 1; + border-top: 1px solid var(--line); +} + +.athand { + border-top: 1px solid var(--line); + margin-top: 8px; + padding-top: 14px; + font-size: 13px; + color: var(--muted); +} + +.athand strong { + color: var(--text); +} + +.athand ul { + margin: 6px 0 0; + padding-left: 18px; +} + +.box { + background: var(--field); + border: 1px solid var(--line); + border-radius: 10px; + padding: 12px; + margin: 0 0 16px; + color: var(--muted); + font-size: 13px; + overflow-wrap: anywhere; +} + +.note { + border: 1px solid var(--amber); + border-radius: 10px; + padding: 12px 16px; + margin: 0 0 20px; +} + +.note p { + margin: 0 0 8px; +} + +.note p:last-child { + margin: 0; +} + +details.more { + border-top: 1px solid var(--line); + padding-top: 12px; + margin: 0 0 20px; +} + +details.more summary { + color: var(--muted); + cursor: pointer; + margin-bottom: 14px; +} + +/* The setup's steps as the connector reports them */ +ul.run { + list-style: none; + margin: 0 0 20px; + padding: 0; +} + +ul.run li { + display: grid; + grid-template-columns: 22px 1fr; + padding: 6px 0; + overflow-wrap: anywhere; +} + +ul.run li::before { + grid-row: span 3; +} + +ul.run li.done::before { + content: "✓"; + color: var(--green); +} + +ul.run li.now::before { + content: "◌"; + color: var(--amber); +} + +ul.run li.hand::before { + content: "→"; + color: var(--amber); +} + +/* What a step adds under its label: one line of it per line */ +ul.run li > span { + color: var(--muted); + font-size: 14px; + white-space: pre-line; +} + +.copyrow { + display: flex; + gap: 8px; + margin-top: 8px; +} + +.copyrow input[type="text"] { + flex: 1; + min-width: 0; + min-height: 40px; + margin: 0; + padding: 8px 10px; + font-size: 13px; +} + +/* ---------- The phones: the earlier window, dark, across the width ---------- */ + +body.app #view { + display: flex; + flex-direction: column; + min-height: 100vh; +} + +.top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 24px; + border-bottom: 1px solid var(--line); + font-size: 14px; + color: var(--muted); +} + +.top .name { + white-space: nowrap; +} + +.picker { + display: inline-flex; + align-items: baseline; + gap: 8px; + min-width: 0; + min-height: 36px; + padding: 7px 12px; + background: var(--card); + border: 1px solid var(--line); + border-radius: 8px; + white-space: nowrap; +} + +.picker small { + color: var(--muted); + font-size: 13px; +} + +.picker strong { + font-weight: 400; + overflow: hidden; + text-overflow: ellipsis; +} + +.picker:hover { + border-color: var(--main); +} + +.work { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; + padding: 16px 24px 0; +} + +.app-form { + flex: 1; + display: flex; + flex-direction: column; + min-height: 0; +} + +.window { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 14px; + font-weight: 700; + font-size: 16px; + margin: 0 0 14px; +} + +.window .said { + flex: 0 1 auto; + min-width: 0; + overflow-wrap: anywhere; +} + +.window .dot { + margin-right: 10px; +} + +.window.closing { + color: var(--amber); +} + +.window.closed { + color: var(--red); +} + +.window.none { + color: var(--muted); +} + +.window .tool { + min-height: 34px; + padding: 4px 12px; + font-size: 14px; + font-weight: 400; + color: var(--text); +} + +.out { + line-height: 20px; + color: var(--red); + font-size: 14px; + border: 1px solid var(--line-strong); + border-radius: 8px; + padding: 6px 12px; + text-decoration: none; + white-space: nowrap; +} + +.window.none .out { + color: var(--text); +} + +.out:hover { + border-color: var(--main); +} + +.tools, +.select { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-bottom: 12px; +} + +.tool { + display: inline-block; + width: auto; + min-height: 40px; + margin: 0; + padding: 6px 16px; + border-radius: 8px; + background: var(--card); + border: 1px solid var(--line-strong); + font-weight: 400; + white-space: nowrap; +} + +.tool.go { + background: var(--main); + border-color: var(--main); + color: #ffffff; + font-weight: 700; +} + +.tool:disabled { + opacity: 0.4; +} + +.tool.small { + min-height: 34px; + padding: 4px 12px; + font-size: 14px; +} + +.tool.push { + margin-left: auto; +} + +.select { + font-size: 14px; +} + +.select .count { + margin-left: auto; + color: var(--muted); +} + +/* The table fills what is left of the window and scrolls inside it */ +.table { + flex: 1 1 0; + min-height: 14rem; + overflow: auto; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--table); +} + +.table.settling { + opacity: 0.5; +} + +table { + border-collapse: collapse; + width: 100%; + font-size: 14px; +} + +th, +td { + text-align: left; + vertical-align: top; + padding: 9px 12px; + border-bottom: 1px solid var(--line); + white-space: nowrap; +} + +th { + position: sticky; + top: 0; + z-index: 1; + background: var(--card); + color: var(--muted); + font-weight: 400; +} + +td.cert, +th.cert { + width: 100%; + white-space: normal; + min-width: 10rem; +} + +td.pick, +th.pick { + width: 1%; + padding-right: 0; +} + +.pick input { + vertical-align: -3px; +} + +tbody tr { + cursor: pointer; +} + +tbody tr:hover td { + background: var(--raise); +} + +tr.sel td { + background: #2c2118; +} + +tr.bad td.cert { + color: var(--red); +} + +td.nocall { + color: var(--dim); +} + +tbody tr:hover td.empty { + background: none; +} + +td.empty { + text-align: center; + color: var(--muted); + padding: 72px 16px; + white-space: normal; + border-bottom: 0; + cursor: default; +} + +.dot { + display: inline-block; + flex: none; + width: 8px; + height: 8px; + border-radius: 50%; + margin-right: 8px; + vertical-align: 1px; + background: var(--dim); +} + +.dot.ok, +.window.open .dot { + background: var(--green); +} + +.dot.on, +.window.closing .dot { + background: var(--amber); +} + +.dot.bad, +.window.closed .dot { + background: var(--red); +} + +.status { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 10px 24px 12px; + font-size: 13px; + color: var(--muted); +} + +.status > div { + flex: 1; + min-width: 0; +} + +.status .updated { + flex: none; + white-space: nowrap; +} + +.status p { + margin: 0; +} + +.status ul { + margin: 4px 0 0; + padding-left: 18px; +} + +/* The Deploy Apps, under the picker */ +.menu { + position: fixed; + inset: 52px 24px auto auto; + width: 25rem; + max-width: calc(100vw - 32px); + margin: 0; + padding: 6px; + background: var(--card); + color: var(--text); + border: 1px solid var(--line-strong); + border-radius: 12px; + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.55); +} + +.menu .item { + display: grid; + grid-template-columns: 22px 1fr; + width: 100%; + padding: 10px 12px; + background: none; + border: 0; + border-radius: 8px; + text-align: left; +} + +.menu .item:hover, +.menu .item.now { + background: var(--raise); +} + +.menu .item strong { + display: block; + font-weight: 400; + overflow-wrap: anywhere; +} + +.menu .item small { + display: block; + color: var(--muted); + font-size: 13px; +} + +.menu .item small.closing { + color: var(--amber); +} + +.menu .item small.closed { + color: var(--red); +} + +.menu .mark { + color: var(--main); +} + +.menu .act { + display: block; + padding-left: 34px; +} + +.menu .danger { + color: var(--red); +} + +.menu hr { + border: 0; + border-top: 1px solid var(--line); + margin: 6px 0; +} + +/* ---------- Dialogs ---------- */ + +dialog { + width: calc(100% - 32px); + max-width: 760px; + max-height: calc(100vh - 64px); + margin: 48px auto auto; + padding: 0; + background: var(--card); + color: var(--text); + border: 1px solid var(--line-strong); + border-radius: 16px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); +} + +dialog::backdrop { + background: rgba(0, 0, 0, 0.62); +} + +dialog header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + padding: 18px 24px 0; +} + +dialog h2 { + margin: 0; + font-size: 18px; + overflow-wrap: anywhere; +} + +.x { + background: none; + border: 0; + color: var(--muted); + font-size: 22px; + line-height: 1; + padding: 4px 6px; +} + +.x:hover { + color: var(--text); +} + +dialog .body { + padding: 18px 24px 4px; +} + +dialog .body > .error:empty { + display: none; +} + +dialog .body .second { + display: inline-block; + width: auto; + min-height: 40px; + padding: 6px 16px; + font-weight: 400; +} + +dialog footer { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; + justify-content: flex-end; + padding: 16px 24px 20px; + border-top: 1px solid var(--line); + margin-top: 8px; +} + +dialog footer .main, +dialog footer .second { + width: auto; + min-height: 48px; + margin: 0; + padding: 8px 22px; +} + +dialog footer .check { + margin: 0 auto 0 0; +} + +/* Numbered or from a list */ +.mode { + display: inline-flex; + border: 1px solid var(--line-strong); + border-radius: 10px; + overflow: hidden; + margin-bottom: 16px; +} + +.mode button { + background: none; + border: 0; + padding: 9px 18px; + min-height: 40px; + color: var(--muted); +} + +.mode button[aria-pressed="true"] { + background: var(--raise); + color: var(--text); + box-shadow: inset 0 -3px 0 var(--main); +} + +.inline { + display: flex; + gap: 12px 20px; +} + +.inline .grow { + flex: 0 1 14rem; + min-width: 0; +} + +.inline .num { + flex: 0 0 9rem; +} + +dialog label { + font-size: 13px; + color: var(--muted); + margin-bottom: 6px; +} + +dialog .check { + font-size: 15px; + color: var(--text); + margin-bottom: 0; +} + +dialog h3 { + font-size: 13px; + color: var(--muted); + font-weight: 400; + margin: 0 0 8px; +} + +dialog h3.sect { + color: var(--text); + font-size: 15px; + font-weight: 700; + margin-bottom: 12px; +} + +dialog h3.sect ~ h3.sect { + border-top: 1px solid var(--line); + padding-top: 16px; + margin-top: 4px; +} + +dialog .table.preview { + flex: none; + min-height: 0; + margin-bottom: 12px; +} + +.preview td.will { + font-weight: 700; +} + +.preview tr.bad td { + color: var(--red); +} + +.preview td.why, +.preview th.why { + width: 100%; + white-space: normal; + min-width: 9rem; +} + +.preview tbody tr { + cursor: default; +} + +.preview tbody tr:last-child td { + border-bottom: 0; +} + +dl.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 8px 18px; + margin: 0 0 16px; +} + +dl.facts dt { + color: var(--muted); +} + +dl.facts dd { + margin: 0; + overflow-wrap: anywhere; +} + +dd.bad { + color: var(--red); +} + +dialog .copyrow { + margin: 0 0 12px; +} + +/* Half a screen: the button rows wrap, the count goes under them and Joined leaves the tables */ +@media (max-width: 720px) { + body.cards { + padding: 32px 16px; + } + + .top, + .work, + .status { + padding-left: 16px; + padding-right: 16px; + } + + .menu { + inset: 52px 16px auto auto; + } + + .select .count { + margin-left: 0; + flex-basis: 100%; + } + + .joined { + display: none; + } + + /* The page scrolls rather than the table, which shows every phone */ + .table { + flex: none; + min-height: 0; + } + + dialog { + margin-top: 16px; + max-height: calc(100vh - 32px); + } + + dialog header, + dialog .body, + dialog footer { + padding-left: 16px; + padding-right: 16px; + } + + .inline .grow { + flex: 1 1 auto; + } + + dialog footer .check { + flex-basis: 100%; + } +} + +/* A phone's width: Callsign and Certificate stay readable without scrolling sideways */ +@media (max-width: 480px) { + .phone, + .picker small { + display: none; + } + + .card { + padding: 20px 16px; + } + + .inline .num { + flex-basis: 7.5rem; + } + + th, + td { + padding: 8px; + } + + td.cert { + min-width: 0; + } + + dialog footer .main, + dialog footer .second { + flex: 1 1 auto; + } + + dl.facts { + grid-template-columns: 1fr; + gap: 2px; + } + + dl.facts dd { + margin-bottom: 10px; + } + + /* The sentence keeps the width, and when the phones were listed goes under it */ + .status { + flex-direction: column; + gap: 4px; + } +} From 556743efd6789d0fd025f8c42033447681f78a8b Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 055/104] feat: the page's behaviour Cards for setting up, one thing each; one view of the phones with dialogs for giving callsigns, one phone, settings and removing. A settings line arrives by window message from Deploy App. --- src/odmdm_connector/static/app.js | 1200 +++++++++++++++++++++++++++++ 1 file changed, 1200 insertions(+) create mode 100644 src/odmdm_connector/static/app.js diff --git a/src/odmdm_connector/static/app.js b/src/odmdm_connector/static/app.js new file mode 100644 index 0000000..911ba30 --- /dev/null +++ b/src/odmdm_connector/static/app.js @@ -0,0 +1,1200 @@ +"use strict"; +// The page: asks the connector for its state and draws it. Setting up is a row of cards, one thing +// each, like a setup wizard; the daily work is one view of the phones with a few dialogs. Every +// sentence shown comes from the connector; this file adds labels, headings and the sentences for a +// connector that refuses this browser or does not answer. Data never becomes markup: the page is +// built with createElement and text nodes. The browser keeps one thing, the page's key, and nothing else. + +const view = document.getElementById("view"); +const dialog = document.getElementById("dialog"); +const menu = document.getElementById("menu"); +// After naming or asking again, the table waits for the listing that follows +const SETTLING = ["name", "ask again", "phones"]; + +let S = null; // the last state +let screen = ""; // a card's name, or "app" for the phones +let problem = ""; // the last refusal, shown in the view +let notice = ""; // the last answer's sentence, shown on the next card +let timer = 0; +let selected = new Set(); // the phones ticked in the table, by id +let settling = false; // the table is from before a naming or an asking again +let submit = null; // what the main button of the form being drawn does +let arriving = null; // a settings line Deploy App's page sent, {line, from}, until it is read +const flow = {}; // what the cards carry from one to the next, in memory only + +// Building blocks + +function el(tag, props, ...children) { + const node = document.createElement(tag); + for (const [key, value] of Object.entries(props || {})) { + if (value === false || value === null || value === undefined) continue; + if (key === "class") node.className = value; + else if (key === "value" || key === "checked" || key === "indeterminate") node[key] = value; + else if (key.startsWith("on")) node.addEventListener(key.slice(2), value); + else node.setAttribute(key, value === true ? "" : value); + } + // A string becomes a text node, never markup + for (const child of children.flat(Infinity)) if (child !== null && child !== undefined && child !== "") node.append(child); + return node; +} + +const h1 = (text) => el("h1", {}, text); +const lead = (text) => (text ? el("p", { class: "lead" }, text) : null); +// A button is known by its text, so that it keeps the focus when the view is drawn again +const button = (props, text) => { + const node = el("button", props, text); + node.dataset.key = text; + return node; +}; +// The form's main button submits it, so Enter in a field presses it +const main = (text, action, disabled = false, tone = "") => { + submit = action; + return button({ class: `main ${tone}`, type: "submit", disabled }, text); +}; +const second = (text, onclick, disabled = false) => button({ class: "second", type: "button", onclick, disabled }, text); +const tool = (text, onclick, disabled = false, tone = "") => button({ class: `tool ${tone}`, type: "button", onclick, disabled }, text); +const link = (text, onclick) => el("button", { class: "back", type: "button", onclick }, text); +const choice = (title, sub, onclick, tone = "") => + el("button", { class: "choice", type: "button", onclick }, el("strong", {}, title), sub ? el("span", { class: tone }, sub) : null); +const count = (n, noun) => `${n} ${noun}${n === 1 ? "" : "s"}`; +// Text a password manager must not take: masked by the style, never a password field +const typed = (props) => el("input", { type: "text", autocomplete: "off", spellcheck: "false", ...props }); +// Where a phone's certificate is, as a dot's colour +const tone = (row) => (!row ? "" : row.failed ? "bad" : row.waiting ? "none" : row.ready ? "ok" : "on"); + +function field(id, label, input) { + input.id = id; + input.dataset.key = id; + return [el("label", { for: id }, label), input]; +} + +function check(label, checked, onchange) { + return el( + "label", + { class: "check" }, + el("input", { type: "checkbox", checked, onchange: (event) => onchange(event.target.checked) }), + label, + ); +} + +function copy(text) { + navigator.clipboard?.writeText(text).catch(() => {}); +} + +// A text to copy, shown in a field of its own that keeps a long one on one line +function copyable(text, label, masked = false) { + const value = typed({ class: masked ? "secret" : null, value: text, readonly: true, "aria-label": label }); + value.dataset.key = label; + return value; +} + +// The page's key, which the connector printed in the address's fragment: no server is sent a +// fragment, so it reaches this page alone. It is kept in this browser's storage for this port, which +// another port cannot read, so that every tab of the page has it; without storage, in this tab only. +const KEPT = "odmdm-key"; +let key = ""; +try { + key = localStorage.getItem(KEPT) || ""; +} catch {} + +// Take the key from the address, if it holds one, and take it out of the address; whether it did. +// Any web page can send the browser here with a key of its own, so a key is kept, and so passed to the +// other tabs, only once the connector accepts it; another one leaves the kept key as it is. +async function takeKey() { + const found = new URLSearchParams(location.hash.slice(1)).get("key"); + if (!found) return false; + history.replaceState(null, "", location.pathname); + // The answer is read to its end, so that the request is not left open + const accepted = await fetch("/api/state", { cache: "no-store", headers: { "X-ODMDM-Key": found } }).then( + (response) => response.text().then(() => response.ok), + () => false, + ); + if (!accepted) return false; + key = found; + try { + localStorage.setItem(KEPT, found); + } catch {} + return true; +} + +// Talking to the connector + +async function call(path, body) { + const headers = { "X-ODMDM-Key": key }; + const options = + body === undefined + ? { cache: "no-store", headers } + : { method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify(body) }; + const response = await fetch(path, options); + const json = (response.headers.get("Content-Type") || "").startsWith("application/json"); + const answer = json ? await response.json() : { error: await response.text() }; + if (!response.ok) throw Object.assign(new Error(answer.error || response.statusText), { status: response.status }); + return answer; +} + +// Ask, take the state that follows, then go on; a refusal is said by fail, in the view by default +async function act(path, body, then, fail = say) { + problem = ""; + let answer; + try { + answer = await call(path, body); + } catch (error) { + if (error.status && error.status !== 403) fail(error.message); + else away(error); + return; + } + notice = answer.said || ""; + if (await refresh(false)) then(answer); +} + +function say(text) { + problem = text; + draw(false); +} + +const overlaid = () => dialog.open || menu.matches(":popover-open"); + +function closeOverlays() { + if (menu.matches(":popover-open")) menu.hidePopover(); + if (dialog.open) dialog.close(); +} + +// The cards that hold nothing typed yet, which follow another tab's adding, opening or connecting +const FOLLOWING = ["add", "choose", "mdm"]; + +// Whether the state came; the views that show it are drawn again, and follow it where it moved on +async function refresh(redraw = true) { + const before = S; + try { + S = await call("/api/state"); + } catch (error) { + away(error); + return false; + } + const moved = + before && (S.active !== before.active || S.connected !== before.connected || S.connections.length > before.connections.length); + if (settling && !S.busy.some((job) => SETTLING.includes(job))) settling = false; + if (!screen || screen === "away") begin(); + else if (!redraw) return true; + else if (screen === "app" && !S.connected) { + closeOverlays(); + home(); + } else if (screen === "connecting") checklist(); + else if (screen === "app" && !overlaid()) draw(false); + else if (FOLLOWING.includes(screen) && moved) begin(); + return true; +} + +// The connector refuses this browser, having no key yet or a new one since a restart, or does not answer +function away(error) { + closeOverlays(); + flow.away = { status: error.status || 0, text: error.message }; + screen = "away"; + problem = ""; + draw(false); +} + +function schedule() { + clearTimeout(timer); + timer = setTimeout(tick, S && S.busy.length ? 1000 : 3000); +} + +async function tick() { + if (document.visibilityState === "visible") await refresh(); + schedule(); +} + +// Moving between views + +function show(name) { + screen = name; + problem = ""; + draw(true); +} + +function go(name) { + notice = ""; + show(name); +} + +function draw(fresh) { + const focused = document.activeElement?.dataset?.key; + const scroller = view.querySelector(".table"); + const at = scroller ? [scroller.scrollTop, scroller.scrollLeft] : null; + submit = null; + const built = screen === "app" ? phones() : frame(CARDS[screen]()); + document.body.className = screen === "app" ? "app" : "cards"; + view.replaceChildren(...built); + const table = view.querySelector(".table"); + if (table && at && !fresh) [table.scrollTop, table.scrollLeft] = at; + const again = fresh ? null : [...view.querySelectorAll("[data-key]")].find((node) => node.dataset.key === focused); + const card = view.querySelector(".card"); + const first = card ? starting(card) : null; + (again || ((fresh || document.activeElement === document.body) && first) || null)?.focus(); +} + +// Where the focus starts: a button marked to start on, else the first field shown, else the main +// button, so that typing or Enter works at once +function starting(root) { + const fields = root.querySelectorAll("input:not([type=checkbox]):not([readonly]), textarea"); + return root.querySelector("[autofocus]") || [...fields].find((node) => !node.closest("[hidden]")) || root.querySelector("button.main:enabled"); +} + +// Cancel, to start on where a stray Enter must not remove something or take something in +const cancel = (onclick) => { + const node = second("Cancel", onclick); + node.autofocus = true; + return node; +}; + +// The form of a view: its main button submits it +function form(parts, cls) { + const action = submit; + return el( + "form", + { + class: cls, + onsubmit: (event) => { + event.preventDefault(); + action?.(); + }, + }, + parts, + ); +} + +// A card: the brand line, a link back and a corner, how far a first set-up is, then the card's own parts +function frame({ parts, step = null, back = null, corner = "", host = false }) { + // The MDM's own title once its fields are asked for; a plugin is not imported before it is approved + const chosen = screen === "field" || screen === "connecting" ? flow.form.title : "MDM"; + const names = ["Deploy App", chosen, "Connect"]; + const bar = + step === null + ? null + : el( + "ol", + { class: "progress", "aria-label": "Set-up" }, + names.map((name, index) => + el("li", { class: index < step ? "done" : index === step ? "now" : "", "aria-current": index === step ? "step" : null }, name), + ), + ); + const top = back || corner ? el("div", { class: "topline" }, back ? link(`‹ ${back.text}`, back.action) : el("span"), corner) : null; + const body = parts.flat(Infinity).filter(Boolean); + // A refusal goes under the heading and the lead, where it is read first + let at = body.findIndex((node) => node.tagName === "H1") + 1; + while (body[at]?.matches?.("p.lead, p.muted")) at += 1; + if (problem) body.splice(at, 0, el("p", { class: "error", role: "alert" }, problem)); + return [ + el("header", { class: "brand" }, host && S?.active ? `ODMDM connector · ${S.active}` : "ODMDM connector"), + el("main", { class: "card" }, form([top, bar, body])), + ]; +} + +function begin() { + problem = notice = ""; + if (!arriving) return home(); + closeOverlays(); + const { line, from } = arriving; + arriving = null; + // Nothing else moves the view on while the line is read: it goes to the confirming card, or to Add + screen = "reading"; + readLine(line, from); +} + +// Where a Deploy App's work goes on: its phones, else what its MDM still needs, and why. The last +// answer's sentence stays, for a card to say. +function home() { + flow.renew = flow.change = flow.again = false; + flow.back = null; + if (!S.active) show(S.connections.length ? "choose" : "add"); + else if (S.connected) show("app"); + else if (S.needs === "secret") chooseMdm(S.mdm, S.status, true); + else if (S.mdms.length === 1) chooseMdm(S.mdms[0].name); + else go("mdm"); +} + +// Add a Deploy App, or new settings for the active one; Back returns to the phones +function adding(renew) { + closeOverlays(); + flow.renew = renew; + flow.back = () => go("app"); + go("add"); +} + +// from is the origin of the page that sent the line, empty for one typed or pasted here +function readLine(line, from) { + act( + "/api/read", + { line, from }, + (reading) => { + flow.line = { line, from }; + flow.reading = reading; + show("confirm"); + }, + (text) => { + if (screen !== "add") show("add"); + say(text); + }, + ); +} + +// A secret kept goes only with the settings it was kept for: it stands in while the rest are as loaded +const unchanged = () => flow.form.fields.every((each) => each.secret || (flow.values[each.key] || "") === (flow.loaded[each.key] || "")); +const held = (each) => each.secret && each.kept && unchanged(); +const filled = (each) => Boolean((flow.values[each.key] || "").trim() || held(each)); + +// The MDM's fields one at a time; with only, just the first it lacks. why is said above that field. +function chooseMdm(name, why = "", only = false) { + act("/api/form", { mdm: name }, (answer) => { + if (answer.approval) { + flow.approval = { name, text: answer.approval }; + show("approve"); + return; + } + flow.form = answer; + flow.values = Object.fromEntries(answer.fields.map((each) => [each.key, each.value])); + flow.loaded = { ...flow.values }; + flow.remember = true; + flow.why = why; + const lacking = only ? answer.fields.findIndex((each) => !each.advanced && (each.required || each.secret) && !filled(each)) : -1; + flow.only = lacking >= 0; + flow.index = flow.only ? answer.fields.filter((each) => !each.advanced).indexOf(answer.fields[lacking]) : 0; + show("field"); + }); +} + +// After Connect: the setup's steps while it runs or leaves something to say, else the phones. With +// the token typed again, a setup that ends with nothing to say goes straight on to the phones. +function checklist() { + const busy = S.busy.includes("setup"); + const said = S.setup_error || S.challenge || S.steps.some((step) => !step.done) || (S.steps.length && !flow.again); + if (!busy && (!S.connected || !said)) home(); + else if (screen === "connecting") draw(false); + else show("connecting"); +} + +// The challenge, for an MDM that is given it by hand: masked until shown +function challenge() { + return el( + "div", + { class: "copyrow" }, + copyable(S.challenge, "Challenge", !flow.showChallenge), + tool(flow.showChallenge ? "Hide" : "Show", () => { + flow.showChallenge = !flow.showChallenge; + draw(false); + }), + tool("Copy", () => copy(S.challenge)), + ); +} + +// The cards of a first set-up, and of the few things that interrupt the work + +const CARDS = { + away() { + const { status, text } = flow.away; + const kept = arriving ? el("p", { class: "muted" }, "The settings from Deploy App are kept here until then.") : null; + if (status === 403) + return { + parts: [ + h1("Open the connector's address"), + lead(text), + el("div", { class: "box" }, "It looks like this:", el("br"), `http://127.0.0.1:${location.port}/#key=…`), + kept, + ], + }; + if (status) return { parts: [h1("The connector failed"), el("p", { class: "error" }, text)] }; + return { + parts: [h1("The connector has stopped"), lead("Start it again on this computer, then open the address it prints."), kept], + }; + }, + + add() { + const renew = flow.renew && S.active; + const input = typed({ class: "secret", placeholder: "ODMDM1 …" }); + let button; + input.addEventListener("input", () => { + button.disabled = !input.value.trim(); + }); + input.addEventListener("paste", (event) => { + event.preventDefault(); + readLine(event.clipboardData.getData("text"), ""); + }); + button = main("Continue", () => readLine(input.value, ""), true); + return { + step: renew ? null : 0, + back: S.connections.length ? { text: "Back", action: flow.back || home } : null, + parts: [ + h1(renew ? `New settings for Deploy App ${S.active}` : "Add your Deploy App"), + notice ? el("p", { class: "muted" }, notice) : null, + lead("On Deploy App's MDM page, press this button:"), + // A picture of Deploy App's button, which the sentence above names: nothing to press here + el("div", { class: "lookfor", "aria-hidden": "true" }, el("small", {}, "on Deploy App"), el("span", {}, "Open in the MDM connector")), + // Only a tab that Deploy App's button opened waits for its message; the button opens a new tab otherwise + window.opener + ? el("p", { class: "waiting" }, el("span", { class: "pulse" }), "Waiting for Deploy App…") + : el("p", { class: "waiting" }, "It opens the connector in a new tab."), + el("div", { class: "or" }, "OR"), + field("line", "Paste its settings line:", input), + button, + S.connections.length + ? null + : el( + "div", + { class: "athand" }, + el("strong", {}, "Have at hand:"), + el( + "ul", + {}, + ["Deploy App's MDM page, open as an admin", "your MDM's address", "an API token for your MDM"].map((each) => el("li", {}, each)), + ), + ), + ], + }; + }, + + confirm() { + const { host, until, known } = flow.reading; + const leave = () => { + flow.line = null; + home(); + }; + const take = () => + act("/api/add", flow.line, () => { + flow.line = null; + home(); + }); + return { + step: known ? null : 0, + parts: [ + h1(known ? `New settings for Deploy App ${host}` : `Add Deploy App ${host}?`), + lead(until), + main(known ? "Use the new settings" : `Add ${host}`, take), + // Any web page can bring this card up for a Deploy App of its own + known ? second("Cancel", leave) : cancel(leave), + ], + }; + }, + + choose() { + return { + parts: [ + h1("Which Deploy App?"), + notice ? lead(notice) : null, + S.connections.map((each) => + choice(each.host, each.short, () => act("/api/open", { host: each.host }, home), each.level), + ), + second("Add a Deploy App", () => { + flow.renew = false; + flow.back = () => go("choose"); + go("add"); + }), + ], + }; + }, + + mdm() { + return { + step: 1, + host: true, + back: S.connections.length > 1 ? { text: "Other Deploy Apps", action: () => go("choose") } : null, + parts: [ + h1("Which MDM?"), + S.mdms.map((each) => + choice(each.name, each.built_in ? "Comes with the connector" : `Plugin: ${each.package} ${each.version}`, () => + chooseMdm(each.name), + ), + ), + ], + }; + }, + + approve() { + const { name, text } = flow.approval; + return { + step: 1, + host: true, + back: { text: "Back", action: () => go("mdm") }, + parts: [ + h1("Use this plugin?"), + lead(text), + main("Use it", () => act("/api/approve", { mdm: name }, () => chooseMdm(name))), + ], + }; + }, + + field() { + const form = flow.form; + const steps = form.fields.filter((each) => !each.advanced); + const shown = steps[flow.index]; + const last = flow.only || flow.index >= steps.length - 1; + const advanced = flow.only ? [] : form.fields.filter((each) => each.advanced); + // A required field left empty holds the button back; a secret kept from before counts as filled + const ready = () => (last ? [shown, ...advanced] : [shown]).every((each) => !each || !each.required || filled(each)); + let button; + const input = (each) => { + const kept = each.remembered ? "Kept on this computer" : "Kept while the connector runs"; + const node = typed({ + class: each.secret ? "secret" : null, + value: flow.values[each.key], + placeholder: held(each) ? kept : each.default, + oninput: (event) => { + flow.values[each.key] = event.target.value; + button.disabled = !ready(); + }, + }); + return field(`field-${each.key}`, each.label, node); + }; + // The card's title is the field's label, so the input is named by it rather than shown it again + const alone = (each) => { + const node = input(each)[1]; + node.setAttribute("aria-label", each.label); + return node; + }; + const connect = () => + act( + "/api/connect", + { mdm: form.name, values: flow.values, remember: S.keeps && flow.remember }, + () => { + flow.values = {}; + flow.again = flow.only; + checklist(); + }, + // A kept secret left empty after the settings changed is asked for again on its own card + (text) => { + const again = steps.findIndex((each) => each.secret && each.kept && !unchanged() && !(flow.values[each.key] || "").trim()); + if (again >= 0 && !flow.only) { + flow.index = again; + show("field"); + } + say(text); + }, + ); + const next = () => { + flow.index += 1; + show("field"); + }; + const back = () => { + if (flow.index > 0 && !flow.only) { + flow.index -= 1; + show("field"); + } else if (flow.change) go("app"); + else go(flow.only ? "choose" : "mdm"); + }; + const backward = flow.change || (flow.only ? S.connections.length > 1 : flow.index > 0 || S.mdms.length > 1); + const backText = flow.only ? "Other Deploy Apps" : flow.index > 0 ? "Back" : flow.change ? "Back to the phones" : "Back"; + button = main(last ? "Connect" : "Next", last ? connect : next, !ready()); + return { + step: flow.only ? null : 1, + corner: flow.only ? "" : `${flow.index + 1} of ${steps.length}`, + back: backward ? { text: backText, action: back } : null, + host: true, + parts: [ + h1(shown.label), + lead(shown.help), + flow.why ? el("p", { class: "note" }, flow.why) : null, + alone(shown), + // Said once: without a keychain the reason above already says the token is not kept + shown.secret + ? S.keeps + ? check("Remember on this computer", flow.remember, (on) => { + flow.remember = on; + }) + : flow.why + ? null + : el("p", { class: "muted hint" }, "Kept only until the connector stops.") + : null, + last && advanced.length + ? el( + "details", + { class: "more" }, + el("summary", {}, "More settings"), + advanced.map((each) => [input(each), each.help ? el("p", { class: "muted hint" }, each.help) : null]), + ) + : null, + button, + ], + }; + }, + + connecting() { + const title = flow.form.title; + const busy = S.busy.includes("setup"); + const done = S.steps.filter((step) => step.done); + const todo = S.steps.filter((step) => !step.done); + const item = (cls, step) => el("li", { class: cls }, step.label, step.message ? el("span", {}, step.message) : null); + // Steps left to the operator are what the card is about once the setup has run + const hand = !busy && !S.setup_error && (todo.length || S.challenge); + const heading = busy ? `Connecting ${title}` : S.setup_error ? `${title} is not set up` : hand ? "Do these by hand" : `${title} is connected`; + return { + step: flow.again ? null : 2, + host: true, + parts: [ + h1(heading), + // The connector's sentence only where it says more than the heading + hand ? lead(S.status) : null, + busy ? S.lines.map((line) => el("p", { class: "note" }, line)) : null, + hand + ? el( + "ul", + { class: "run" }, + todo.map((step) => item("hand", step)), + S.challenge ? el("li", { class: "hand" }, S.challenge_note, challenge()) : null, + ) + : null, + el( + "ul", + { class: "run" }, + done.map((step) => item("done", step)), + busy ? el("li", { class: "now" }, "…") : null, + ), + S.setup_error ? el("p", { class: "error" }, S.setup_error) : null, + S.setup_error + ? main("Change the settings", () => { + flow.change = false; + chooseMdm(S.mdm); + }) + : main("Show the phones", home, busy), + ], + }; + }, +}; + +// The phones: the window's line, one row of buttons, the selection, the table and what was said last + +function phones() { + const rows = S.rows; + const ids = new Set(rows.map((row) => row.id)); + selected = new Set([...selected].filter((id) => ids.has(id))); + const picked = rows.filter((row) => selected.has(row.id)); + const pick = (test) => { + selected = new Set(rows.filter(test).map((row) => row.id)); + draw(false); + }; + const flip = (id) => { + if (selected.has(id)) selected.delete(id); + else selected.add(id); + draw(false); + }; + const waiting = rows.some((row) => row.waiting); + const askable = selected.size ? picked.some((row) => row.askable) : rows.some((row) => row.askable && row.failed); + const level = S.banner.level; + const renew = level === "closed" || level === "none"; + + const picker = el( + "button", + { class: "picker", type: "button", popovertarget: "menu", "aria-haspopup": "true" }, + el("small", {}, "Deploy App"), + el("strong", {}, S.active), + " ▾", + ); + picker.dataset.key = "picker"; + const all = el("input", { + type: "checkbox", + "aria-label": "Select all", + checked: rows.length > 0 && selected.size === rows.length, + indeterminate: selected.size > 0 && selected.size < rows.length, + disabled: !rows.length, + onchange: (event) => pick(() => event.target.checked), + }); + all.dataset.key = "all"; + const body = rows.map((row) => { + const box = el("input", { + type: "checkbox", + checked: selected.has(row.id), + "aria-label": `Select ${row.callsign || row.id}`, + onchange: () => flip(row.id), + }); + box.dataset.key = `pick-${row.id}`; + const line = el( + "tr", + { + class: `${row.failed ? "bad" : ""} ${selected.has(row.id) ? "sel" : ""}`, + tabindex: "0", + onclick: (event) => { + if (!event.target.closest(".pick")) flip(row.id); + }, + ondblclick: () => detail(row.id), + onkeydown: (event) => { + if (event.target !== event.currentTarget) return; + if (event.key === "Enter") { + event.preventDefault(); + detail(row.id); + } else if (event.key === " ") { + event.preventDefault(); + flip(row.id); + } + }, + }, + el("td", { class: "pick" }, box), + el("td", {}, row.id), + el("td", { class: row.callsign ? "call" : "call nocall" }, row.callsign || "—"), + el("td", { class: "phone" }, row.phone), + el("td", { class: "joined" }, row.joined), + el("td", { class: "cert" }, el("span", { class: `dot ${tone(row)}` }), row.certificate), + ); + line.dataset.key = `row-${row.id}`; + return line; + }); + const empty = el("tr", {}, el("td", { class: "empty", colspan: "6" }, S.summary || "…")); + + return [ + el("header", { class: "top" }, el("span", { class: "name" }, "ODMDM connector"), picker), + el( + "main", + { class: "work" }, + form( + [ + el( + "div", + { class: `window ${level}` }, + el("span", { class: "said" }, el("span", { class: "dot" }), S.banner.text), + renew && S.mdm_page + ? el("a", { class: "out", href: S.mdm_page, target: "_blank", rel: "noopener noreferrer" }, "Open Deploy App ↗") + : null, + ), + S.challenge_note + ? el("div", { class: "note" }, el("p", {}, S.challenge_note), S.challenge ? challenge() : null) + : null, + el( + "div", + { class: "tools" }, + main("Give callsigns", () => giveCallsigns([...selected]), settling || !(selected.size || waiting), "tool go"), + tool("Ask again", () => askAgain([...selected]), settling || !askable), + tool("Details", () => detail([...selected][0]), settling || selected.size !== 1), + tool("Refresh", () => act("/api/refresh", {}, () => draw(false))), + tool("New settings", () => adding(true)), + tool("Settings", settings, false, "push"), + ), + el( + "div", + { class: "select" }, + el("span", { class: "muted" }, "Select:"), + tool("Waiting for a name", () => pick((row) => row.waiting), !waiting, "small"), + tool("Refused or failed", () => pick((row) => row.failed), !rows.some((row) => row.failed), "small"), + selected.size ? [el("span", { class: "muted" }, `${selected.size} selected`), link("Clear", () => pick(() => false))] : null, + rows.length ? el("span", { class: "count" }, S.summary) : null, + ), + el( + "div", + { class: settling ? "table settling" : "table", "aria-busy": settling ? "true" : null }, + el( + "table", + {}, + el( + "thead", + {}, + el( + "tr", + {}, + el("th", { class: "pick" }, all), + el("th", {}, "ID"), + el("th", {}, "Callsign"), + el("th", { class: "phone" }, "Phone"), + el("th", { class: "joined" }, "Joined"), + el("th", { class: "cert" }, "Certificate"), + ), + ), + el("tbody", {}, rows.length ? body : empty), + ), + ), + ], + "app-form", + ), + ), + el( + "footer", + { class: "status" }, + el( + "div", + { "aria-live": "polite" }, + problem ? el("p", { class: "error", role: "alert" }, problem) : el("p", {}, S.status), + S.lines.length ? el("ul", {}, S.lines.map((line) => el("li", {}, line))) : null, + ), + S.updated ? el("span", { class: "updated" }, `Updated ${S.updated}`) : null, + ), + ]; +} + +function askAgain(ids) { + settling = true; + act("/api/again", { ids }, () => draw(false), (text) => { + settling = false; + say(text); + }); +} + +// The Deploy Apps, in the menu under the picker: open one, add one, or remove the one open + +menu.addEventListener("beforetoggle", (event) => { + if (event.newState !== "open") return; + const pick = (action) => () => { + menu.hidePopover(); + action(); + }; + menu.replaceChildren( + ...S.connections.map((each) => + el( + "button", + { + class: each.active ? "item now" : "item", + type: "button", + "aria-current": each.active ? "true" : null, + onclick: pick(() => (each.active ? null : act("/api/open", { host: each.host }, home))), + }, + el("span", { class: "mark" }, each.active ? "●" : ""), + el("span", {}, el("strong", {}, each.host), el("small", { class: each.level }, each.short)), + ), + ), + el("hr"), + el("button", { class: "item act", type: "button", onclick: pick(() => adding(false)) }, "+ Add a Deploy App"), + el("button", { class: "item act danger", type: "button", onclick: pick(remove) }, `Remove ${S.active}…`), + ); +}); + +menu.addEventListener("toggle", (event) => { + if (event.newState === "closed" && screen === "app" && !dialog.open) draw(false); +}); + +// The dialogs: the browser's own, which bring the backdrop, Escape and the keyboard kept inside. Each +// is a form; parts is what it holds, and its main button submits it. + +function open(title, parts, foot) { + const opener = document.activeElement?.dataset?.key; + dialog.dataset.opener = opener || ""; + const say = el("p", { class: "error", role: "alert" }); + const built = form( + [ + el("header", {}, el("h2", { id: "dialog-title" }, title), el("button", { class: "x", type: "button", "aria-label": "Close", onclick: () => dialog.close() }, "×")), + el("div", { class: "body" }, parts, say), + el("footer", {}, foot), + ], + "", + ); + dialog.setAttribute("aria-labelledby", "dialog-title"); + dialog.replaceChildren(built); + if (!dialog.open) dialog.showModal(); + // Never on the close mark, which the browser would choose + (starting(built.querySelector(".body")) || starting(built.querySelector("footer")))?.focus(); + return (text) => { + say.textContent = text; + }; +} + +dialog.addEventListener("close", () => { + // The event comes a moment later: a dialog opened in its place since then stays + if (dialog.open) return; + dialog.replaceChildren(); + if (screen !== "app") return; + draw(false); + const opener = [...view.querySelectorAll("[data-key]")].find((node) => node.dataset.key === dialog.dataset.opener); + opener?.focus(); +}); + +// A click on the backdrop, outside the dialog's box, closes it +dialog.addEventListener("click", (event) => { + if (event.target === dialog) dialog.close(); +}); + +function detail(id) { + act("/api/detail", { id }, (phone) => { + const row = S.rows.find((each) => each.id === phone.id); + const pair = (term, value, cls) => (value ? [el("dt", {}, term), el("dd", { class: cls }, value)] : null); + submit = null; + const give = phone.callsign ? "Give another callsign" : "Give a callsign"; + const giving = () => { + dialog.close(); + giveCallsigns([phone.id]); + }; + const foot = phone.can_ask_again + ? [ + second(give, giving), + main("Ask again", () => { + dialog.close(); + askAgain([phone.id]); + }), + ] + : [main(give, giving)]; + open( + phone.callsign || `Phone ${phone.id}`, + [ + el( + "dl", + { class: "facts" }, + pair("Phone", phone.phone ? `${phone.phone}, ID ${phone.id}` : `ID ${phone.id}`), + pair("Joined", phone.joined), + [el("dt", {}, "Certificate"), el("dd", { class: tone(row) }, el("span", { class: `dot ${tone(row)}` }), phone.state)], + pair("The MDM says", phone.detail), + ), + el("p", { class: "muted" }, phone.window), + ], + foot, + ); + }); +} + +// One dialog for naming: numbered or from a list, and the preview the connector makes of it, asked a +// moment after the typing stops. One preview is asked at a time and the last one asked is the one +// shown, as the connector names only its last; Name waits for it, and names exactly what it showed. +function giveCallsigns(ids) { + const n = ids.length || S.rows.filter((row) => row.waiting).length; + // The rest of a list kept from last time is where the next callsigns come from + const naming = { how: S.callsigns.length ? "list" : "numbered", prefix: S.prefix, first: "", list: S.callsigns.join("\n"), save: true }; + let found = null; + let refused = ""; + let asking = false; + let again = false; + let wait = 0; + const later = (key) => (event) => { + naming[key] = event.target.value; + tell(""); + clearTimeout(wait); + wait = setTimeout(ask, 400); + shown(); + }; + const prefix = typed({ value: naming.prefix, placeholder: "OTTER", oninput: later("prefix") }); + const first = typed({ inputmode: "numeric", value: "", oninput: later("first") }); + const list = el("textarea", { spellcheck: "false", rows: "6", oninput: later("list") }); + list.value = naming.list; + const numbered = el("div", { class: "inline" }, el("div", { class: "grow" }, field("prefix", "Prefix", prefix)), el("div", { class: "num" }, field("first", "First number", first))); + const listed = el("div", {}, field("list", "One callsign per line", list)); + const keep = check("Keep the rest of the list for next time", naming.save, (on) => { + naming.save = on; + }); + const switches = ["numbered", "list"].map((how) => + el( + "button", + { + type: "button", + "aria-pressed": "false", + onclick: () => { + naming.how = how; + tell(""); + ask(); + }, + }, + how === "numbered" ? "Numbered" : "From a list", + ), + ); + const preview = el("div", { class: "preview-part" }); + const name = () => { + const names = Object.fromEntries(found.rows.map((row) => [row.id, row.callsign])); + const { how, list: text, save } = naming; + act( + "/api/name", + { names, how, prefix: naming.prefix, list: text, save }, + () => { + selected = new Set(); + settling = true; + dialog.close(); + }, + // The connector may hold another preview, from another tab: ask again, so the dialog shows what it would + // name; the reason stays until the operator changes something + (text) => { + tell(text); + ask(); + }, + ); + }; + submit = null; + const button = main("Name", name, true); + shown(); + const tell = open( + `Give callsigns to ${count(n, "phone")}`, + [el("div", { class: "mode", role: "group", "aria-label": "How" }, switches), numbered, listed, preview], + [keep, second("Cancel", () => dialog.close()), button], + ); + + // What the dialog shows now: the way chosen, and the preview with the button, held back while one is asked + function shown() { + const list = naming.how === "list"; + switches.forEach((each, index) => each.setAttribute("aria-pressed", String(index === (list ? 1 : 0)))); + numbered.hidden = list; + listed.hidden = !list; + keep.hidden = !list; + if (found) first.placeholder = String(found.first || ""); + const busy = asking || again || Boolean(wait); + const rows = found ? found.rows : []; + const problems = rows.some((row) => row.refusal); + const cell = (cls, text) => el("td", { class: cls }, text); + const parts = [ + found || refused ? el("h3", {}, "Preview") : null, + found + ? [ + el( + "div", + { class: busy ? "table preview settling" : "table preview", "aria-busy": busy ? "true" : null }, + el( + "table", + {}, + el( + "thead", + {}, + el( + "tr", + {}, + el("th", {}, "ID"), + el("th", { class: "phone" }, "Phone"), + el("th", { class: "joined" }, "Joined"), + el("th", {}, "Callsign"), + problems ? el("th", { class: "why" }, "Problem") : null, + ), + ), + el( + "tbody", + {}, + rows.map((row) => + el( + "tr", + { class: row.refusal ? "bad" : "" }, + cell("", row.id), + cell("phone", row.phone), + cell("joined", row.joined), + cell("will", row.callsign || "—"), + problems ? cell("why", row.refusal) : null, + ), + ), + ), + ), + ), + found.refusal ? el("p", { class: "error" }, found.refusal) : null, + found.warning ? el("p", { class: "warn" }, found.warning) : null, + ] + : null, + refused ? el("p", { class: "error" }, refused) : null, + !found && !refused && busy ? el("p", { class: "muted" }, "…") : null, + ]; + preview.replaceChildren(...parts.flat(Infinity).filter(Boolean)); + button.textContent = found ? found.button : "Name"; + button.disabled = busy || refused !== "" || !found?.ok; + } + + async function ask() { + clearTimeout(wait); + wait = 0; + if (!preview.isConnected) return; + // A numbered batch with neither a prefix nor a first number has nothing typed to preview yet + if (naming.how === "numbered" && !naming.prefix.trim() && !naming.first.trim()) { + found = null; + refused = ""; + shown(); + return; + } + if (asking) { + again = true; + return; + } + asking = true; + again = false; + shown(); + try { + found = await call("/api/preview", { ids, ...naming }); + refused = ""; + } catch (error) { + if (!error.status || error.status === 403) { + away(error); + return; + } + found = null; + refused = error.message; + } finally { + asking = false; + } + if (again) ask(); + else shown(); + } + + ask(); +} + +function settings() { + act("/api/form", { mdm: S.mdm }, (answer) => { + const said = (each) => + each.secret + ? each.remembered + ? "kept on this computer" + : each.kept + ? "kept until the connector stops" + : "not given" + : each.value; + const change = () => { + dialog.close(); + flow.change = true; + chooseMdm(S.mdm); + }; + submit = null; + const close = main("Close", () => dialog.close(), false, "plain"); + open( + "Settings", + [ + el("h3", { class: "sect" }, `${answer.title} for ${S.active}`), + el( + "dl", + { class: "facts" }, + answer.fields.filter((each) => said(each)).map((each) => [el("dt", {}, each.label), el("dd", {}, said(each))]), + ), + second(`Change the ${answer.title} settings`, change), + el("h3", { class: "sect" }, "Log"), + el("div", { class: "copyrow" }, copyable(S.log, "Log"), tool("Copy", () => copy(S.log))), + el("p", { class: "muted" }, `odmdm-connector ${S.version}`), + ], + [close], + ); + }); +} + +function remove() { + const host = S.active; + submit = null; + const removing = () => + act( + "/api/remove", + { host }, + () => { + dialog.close(); + home(); + }, + (text) => tell(text), + ); + const button = main("Remove", removing, false, "danger"); + const tell = open( + `Remove Deploy App ${host}?`, + [ + el( + "p", + {}, + "The connector forgets this Deploy App and its MDM token on this computer. Nothing changes in Deploy App, the MDM or the phones.", + ), + ], + [cancel(() => dialog.close()), button], + ); +} + +// A settings line from Deploy App's page arrives by message, only from the page that opened this one. +// Once it has, this page lets go of that one: holding it would let this page send it elsewhere. +window.addEventListener("message", (event) => { + if (!window.opener || event.source !== window.opener || typeof event.data?.add !== "string") return; + window.opener = null; + arriving = { line: event.data.add, from: event.origin }; + if (screen === "away") draw(false); + else if (S && screen) begin(); +}); + +document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") tick(); +}); + +// The address opened in a tab that shows the page already changes only its fragment, and reloads nothing +window.addEventListener("hashchange", async () => { + if (await takeKey()) tick(); +}); + +// Another tab of the page took a key: a tab that waits for one goes on by itself +window.addEventListener("storage", (event) => { + if (event.key !== KEPT || !event.newValue) return; + key = event.newValue; + tick(); +}); + +// The word is no secret: it only tells Deploy App's page that this one listens +window.opener?.postMessage("odmdm-ready", "*"); +takeKey().then(tick); From ec498bedf37621e6a36d1b20f04d847377a4c982 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 056/104] refactor: the next free number of a prefix, and a phone's words only while its certificate failed --- src/odmdm_connector/core.py | 19 ++++++++++++++----- tests/test_core.py | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/src/odmdm_connector/core.py b/src/odmdm_connector/core.py index f5c6970..158c400 100644 --- a/src/odmdm_connector/core.py +++ b/src/odmdm_connector/core.py @@ -3,11 +3,15 @@ import re from collections.abc import Sequence -from .mdm import Phone +from .mdm import Phone, State #: The deployment's rule for a device callsign, checked here only so a typo is refused now rather #: than as a failed certificate twenty minutes later. The deployment still decides. CALLSIGN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{1,30}[A-Za-z0-9]") +#: The states the plugin's words are said beside: the certificate was never asked for, was refused, +#: could not be reached or failed. Waiting for it or having it, the state alone is true: words from +#: an earlier failure would sit beside a request that has not failed. +EXPLAINED = (State.NO_REQUEST, State.NOT_ASKED, State.REFUSED, State.UNREACHABLE, State.FAILED) def pairs(values: Sequence[str]) -> list[tuple[str, str]]: @@ -21,14 +25,19 @@ def pairs(values: Sequence[str]) -> list[tuple[str, str]]: return found +def next_number(phones: Sequence[Phone], prefix: str) -> int: + """One above the highest PREFIX in use, compared without case; 1 when none is""" + used = (re.fullmatch(re.escape(prefix) + r"(\d+)", phone.callsign, re.IGNORECASE) for phone in phones) + return max((int(match.group(1)) for match in used if match), default=0) + 1 + + def numbered(phones: Sequence[Phone], prefix: str, start: int | None) -> list[tuple[str, str]]: """PREFIX for every phone without a name, in the order given Numbered from start, else from one above the highest PREFIX already in use. """ if start is None: - used = (re.fullmatch(re.escape(prefix) + r"(\d+)", phone.callsign, re.IGNORECASE) for phone in phones) - start = max((int(match.group(1)) for match in used if match), default=0) + 1 + start = next_number(phones, prefix) waiting = [phone.id for phone in phones if not phone.callsign] return [(phone, f"{prefix}{start + n}") for n, phone in enumerate(waiting)] @@ -59,5 +68,5 @@ def refusal(phones: Sequence[Phone], wanted: Sequence[tuple[str, str]]) -> str: def said(phone: Phone) -> str: - """Where the phone's certificate is, as the operator reads it: the state, then the plugin's words""" - return f"{phone.state.value}: {phone.detail}" if phone.detail else phone.state.value + """Where the phone's certificate is, as the operator reads it: the state, and the words EXPLAINED allows""" + return f"{phone.state.value}: {phone.detail}" if phone.detail and phone.state in EXPLAINED else phone.state.value diff --git a/tests/test_core.py b/tests/test_core.py index 7212173..d7147a2 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,5 +1,7 @@ """The naming rules, without an MDM""" +from dataclasses import replace + import pytest from odmdm_connector import core @@ -27,6 +29,7 @@ def test_numbering_goes_on_from_the_highest_in_use() -> None: assert core.numbered(phones, "OTTER", None) == [("b", "OTTER8"), ("d", "OTTER9")] assert core.numbered(phones, "OTTER", 20) == [("b", "OTTER20"), ("d", "OTTER21")] + assert (core.next_number(phones, "otter"), core.next_number(phones, "BEAR")) == (8, 1) @pytest.mark.parametrize( @@ -48,3 +51,24 @@ def test_a_batch_is_refused_whole(wanted: list[tuple[str, str]], says: str) -> N refused = core.refusal(phones, wanted) assert refused.startswith(says) if says else not refused + + +@pytest.mark.parametrize( + ("state", "says"), + [ + (State.NO_REQUEST, "no certificate requested: the words"), + (State.NEEDS_NAME, "waiting for a name"), + (State.NOT_ASKED, "named, but its certificate was not asked for again: the words"), + (State.WAITING, "requested, waiting for the phone"), + (State.READY, "has its certificate"), + (State.REFUSED, "refused by Deploy App: the words"), + (State.UNREACHABLE, "could not reach Deploy App: the words"), + (State.FAILED, "failed: the words"), + ], +) +def test_the_plugins_words_explain_only_a_certificate_not_under_way(state: State, says: str) -> None: + """After asking again, an old refusal does not sit beside a request that is waiting""" + phone = Phone("a1", "OTTER1", "a phone", "2026-11-01T08:00:00Z", state, "the words") + + assert core.said(phone) == says + assert core.said(replace(phone, detail="")) == state.value From 42b0f4b842e098c064d1dd9cd4847e3464b86b86 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 057/104] feat: take a settings line only with a plain SCEP URL on a plain DNS host Python and browsers read some addresses as two different hosts, so a crafted line could pass for a known Deploy App. The closing time of an expired line is said in local time. --- src/odmdm_connector/settings.py | 47 ++++++++++++++++++---- tests/test_settings.py | 70 ++++++++++++++++++++++++++++++--- 2 files changed, 105 insertions(+), 12 deletions(-) diff --git a/src/odmdm_connector/settings.py b/src/odmdm_connector/settings.py index b0265d2..346c285 100644 --- a/src/odmdm_connector/settings.py +++ b/src/odmdm_connector/settings.py @@ -2,7 +2,7 @@ Version 1 is four fields separated by whitespace:: - ODMDM1 + ODMDM1 /> It is the same for every MDM and carries no names. The challenge is a secret: nothing here puts it in a message. @@ -16,6 +16,12 @@ MARK = "ODMDM1" CHALLENGE = re.compile(r"[0-9a-f]{32}") CLOSES = "%Y-%m-%dT%H:%M:%SZ" +#: A plain DNS name: letters, digits and inner hyphens in labels separated by dots, at least two labels +HOST = re.compile(r"[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+") +URL = ( + "The SCEP URL in the settings line must be https:///, with a plain host name and nothing else " + "before the path." +) class SettingsError(ValueError): @@ -43,18 +49,44 @@ def is_line(value: str) -> bool: return len(value.split()) > 1 or value.strip().upper().startswith("ODMDM") +def _scep_url(url: str) -> str: + """The URL with its host in lower case, if it is https:/// and nothing else; else empty + + No user name, password, port, query or fragment, and no backslash anywhere: Python and a browser + read a URL such as https://evil.example\\@unit.example.fi/scep as two different hosts, which is how a + crafted line could pass for a known Deploy App. The host is a plain DNS name, so that no + look-alike letter, percent sign, semicolon or control character makes a name that looks like + a real one. + """ + try: + parts = urlsplit(url) + except ValueError: + return "" + host = parts.hostname or "" + if ( + parts.scheme == "https" + and HOST.fullmatch(host) + and parts.netloc.lower() == host + and parts.path.strip("/") + and not any(mark in url for mark in "\\?#") + ): + return f"https://{host}{parts.path}" + return "" + + def parse(line: str, now: datetime.datetime) -> Settings: """The line's values, or SettingsError saying why not - now is the current time with its time zone, given by the caller. + now is the current time with its time zone, given by the caller; a closing time in a message is + in that time zone. """ fields = line.split() if len(fields) != 4 or fields[0] != MARK: raise SettingsError(f"This is not a settings line: it has four parts and starts with {MARK}.") - _, url, challenge, closes = fields - parts = urlsplit(url) - if parts.scheme != "https" or not parts.hostname: - raise SettingsError("The SCEP URL in the settings line must start with https://.") + _, given, challenge, closes = fields + url = _scep_url(given) + if not url: + raise SettingsError(URL) if not CHALLENGE.fullmatch(challenge): raise SettingsError("The challenge in the settings line must be 32 lowercase hex characters.") try: @@ -62,5 +94,6 @@ def parse(line: str, now: datetime.datetime) -> Settings: except ValueError as exc: raise SettingsError(f"The closing time {closes!r} is not YYYY-MM-DDTHH:MM:SSZ.") from exc if when <= now: - raise SettingsError(f"The enrolment window closed at {closes}: open a new one in Deploy App.") + at = when.astimezone(now.tzinfo).strftime("%H:%M") + raise SettingsError(f"The enrolment window closed at {at}: open a new one in Deploy App.") return Settings(scep_url=url, challenge=challenge, closes=when) diff --git a/tests/test_settings.py b/tests/test_settings.py index f6f7583..85c588b 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -38,8 +38,6 @@ def test_the_challenge_never_shows_in_its_repr() -> None: ("odmdm1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "not a settings line"), ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE, "not a settings line"), ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z OTTER1", "not a settings line"), - ("ODMDM1 http://unit.example.fi/scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "must start with https://"), - ("ODMDM1 https:///scep " + CHALLENGE + " 2026-11-21T14:00:00Z", "must start with https://"), ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE.upper() + " 2026-11-21T14:00:00Z", "32 lowercase hex"), ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE[:-1] + " 2026-11-21T14:00:00Z", "32 lowercase hex"), ("ODMDM1 https://unit.example.fi/scep " + CHALLENGE[:-1] + "g 2026-11-21T14:00:00Z", "32 lowercase hex"), @@ -55,9 +53,71 @@ def test_a_line_that_cannot_be_used_says_why(line: str, says: str) -> None: assert CHALLENGE[:-1] not in str(raised.value), "the challenge is never in a message" -@pytest.mark.parametrize("now", [CLOSES, CLOSES + datetime.timedelta(seconds=1)]) -def test_a_closed_window_is_refused(now: datetime.datetime) -> None: - with pytest.raises(SettingsError, match="closed at 2026-11-21T14:00:00Z: open a new one in Deploy App"): +@pytest.mark.parametrize( + "url", + [ + "http://unit.example.fi/scep", + "https:///scep", + "https://unit.example.fi", + "https://unit.example.fi/", + "https://evil.example\\@unit.example.fi/scep", + "https://unit.example.fi\\scep", + "https://user:pass@unit.example.fi/scep", # pragma: allowlist secret + "https://user@unit.example.fi/scep", + "https://unit.example.fi:8443/scep", + "https://unit.example.fi:/scep", + "https://unit.example.fi/scep?x=1", + "https://unit.example.fi/scep?", + "https://unit.example.fi/scep#x", + "https://[unit.example.fi/scep", + "ftp://unit.example.fi/scep", + "https://un\u0456t.example.fi/scep", + "https://\uff55nit.example.fi/scep", + "https://unit.example.fi\u200b/scep", + "https://unit%2eexample.fi/scep", + "https://unit.example.fi;x/scep", + "https://unit.example.fi\x7f/scep", + "https://unit_1.example.fi/scep", + "https://-unit.example.fi/scep", + "https://unit-.example.fi/scep", + "https://unit..example.fi/scep", + "https://unit.example.fi./scep", + "https://localhost/scep", + ], +) +def test_a_scep_url_that_is_not_just_a_host_and_a_path_is_refused(url: str) -> None: + line = f"ODMDM1 {url} {CHALLENGE} 2026-11-21T14:00:00Z" + + with pytest.raises(SettingsError) as raised: + parse(line, BEFORE) + + assert str(raised.value) == ( + "The SCEP URL in the settings line must be https:///, with a plain host name and nothing else " + "before the path." + ) + + +def test_a_host_in_capitals_is_the_same_host() -> None: + assert ( + parse(VECTOR.replace("unit.example.fi", "Unit.Example.FI"), BEFORE).scep_url == "https://unit.example.fi/scep" + ) + + +@pytest.mark.parametrize("host", ["unit.example.fi", "a.b", "x-1.unit-2.example.fi", "192.0.2.10"]) +def test_a_plain_host_is_taken(host: str) -> None: + assert parse(VECTOR.replace("unit.example.fi", host), BEFORE).scep_url == f"https://{host}/scep" + + +@pytest.mark.parametrize( + ("now", "at"), + [ + (CLOSES, "14:00"), + (CLOSES + datetime.timedelta(seconds=1), "14:00"), + (CLOSES.astimezone(datetime.timezone(datetime.timedelta(hours=2))), "16:00"), + ], +) +def test_a_closed_window_is_refused_at_the_operators_time(now: datetime.datetime, at: str) -> None: + with pytest.raises(SettingsError, match=f"^The enrolment window closed at {at}: open a new one in Deploy App.$"): parse(VECTOR, now) From ed0c87b12cc05cbb868d64c9f4a906af9b171963 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 058/104] feat: Fleet's id for the phone in the shipped subject, and the template read from inside a zip too --- src/odmdm_connector/template.json | 8 +++++--- src/odmdm_connector/template.py | 10 ++++++---- tests/test_template.py | 8 ++++++++ 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/odmdm_connector/template.json b/src/odmdm_connector/template.json index 1680e0f..5faff5f 100644 --- a/src/odmdm_connector/template.json +++ b/src/odmdm_connector/template.json @@ -41,12 +41,14 @@ "The template Fleet fills in per phone. Its common name becomes the phone's callsign: 3-32", "letters, digits or inner hyphens. This is the name `odmdm-connector name` gives a phone, and", "the connector refuses any other common name: one the phone supplies, such as its serial", - "number, would make a leaked enrolment link enough for an identity. OU=$FLEET_VAR_HOST_UUID", - "may follow it. The name becomes the Android keystore alias, so it is per deployment." + "number, would make a leaked enrolment link enough for an identity. Fleet's id for the phone", + "follows it as OU, so the deployment can tell later which device a callsign was issued to;", + "leave the OU out only for a team that already has phones under a subject without it.", + "The name becomes the Android keystore alias, so it is per deployment." ], "authority": "RMSCEP", "name": "{key_alias}", - "subject": "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" + "subject": "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID" }, "link_app": { "_comment": "A launcher icon so nobody has to know where the server lives. It is a browser shortcut, so it only works alongside the browser and the certificate.", diff --git a/src/odmdm_connector/template.py b/src/odmdm_connector/template.py index 152b662..d45ce15 100644 --- a/src/odmdm_connector/template.py +++ b/src/odmdm_connector/template.py @@ -18,13 +18,15 @@ import logging import re from dataclasses import dataclass, field -from pathlib import Path +from importlib import resources +from importlib.resources.abc import Traversable from typing import Any LOGGER = logging.getLogger(__name__) -#: The template shipped with the package: what a Deploy App deployment's phones need -EXAMPLE = Path(__file__).with_name("template.json") +#: The template shipped with the package: what a Deploy App deployment's phones need. Read through +#: importlib.resources, so that it is found also when the package runs from inside a zip file. +EXAMPLE = resources.files(__package__).joinpath("template.json") class TemplateError(ValueError): @@ -141,7 +143,7 @@ def _substitute(value: Any, values: dict[str, str]) -> Any: return value -def load(path: Path, domain: str, key_alias: str) -> MdmTemplate: +def load(path: Traversable, domain: str, key_alias: str) -> MdmTemplate: """Read the document and fill in this deployment's values Raises TemplateError rather than letting a malformed document reach the MDM, because a half diff --git a/tests/test_template.py b/tests/test_template.py index b1eaf9c..e45009a 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -179,3 +179,11 @@ def test_the_example_is_a_template_we_accept() -> None: assert "defaultPermissionPolicy" not in template.policy, "nothing granted to every app" rules = template.policy["choosePrivateKeyRules"] assert [r["packageNames"] for r in rules] == [["com.android.chrome", "com.atakmap.app.civ", "im.vector.app"]] + + +def test_the_shipped_subject_carries_the_device_id() -> None: + """A subject cannot change once a team has phones, so the id is there from the first template""" + template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None + assert template.certificate.subject == f"{NAMED}, OU=$FLEET_VAR_HOST_UUID" From e2bedc4f291bdfd7414437fdd7126be00db1014a Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 059/104] refactor: talk to Fleet with the standard library HTTPS only, a redirect never followed, the token in no error text. A 401 is marked as the token not accepted. A certificate authority of the same name that serves another Deploy App is refused, before anything is changed in Fleet. --- src/odmdm_connector/fleet.py | 171 +++++++++++----- tests/test_fleet.py | 383 ++++++++++++++++++++++++++++++----- 2 files changed, 449 insertions(+), 105 deletions(-) diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index 696b98d..ee79bc4 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -6,14 +6,18 @@ import dataclasses import datetime +import http.client import json import logging +import secrets +import ssl import time +import urllib.error +import urllib.request from typing import Any from urllib.parse import urlencode, urlparse -import httpx - +from . import __version__ from .icon import launcher_icon from .template import MdmTemplate @@ -24,10 +28,78 @@ WEB_APP_PUBLISH_WAIT = 10.0 +def _same_case(url: str) -> str: + """A URL with its scheme and host lower-cased, as they compare without case""" + parts = urlparse(url) + return parts._replace(scheme=parts.scheme.lower(), netloc=parts.netloc.lower()).geturl() + + class FleetError(RuntimeError): """Fleet refused, or answered something we cannot use""" +class Unauthorized(FleetError): + """Fleet answered 401: it does not accept the token""" + + +#: The proxy the environment names, and HTTPS with certificates checked: nothing else. Without a +#: redirect handler a redirect comes back as an answer and is never followed, so the token goes +#: nowhere but the MDM URL; without the error handlers an answer of any status comes back as it is. +_OPENER = urllib.request.OpenerDirector() +_OPENER.add_handler(urllib.request.ProxyHandler()) +_OPENER.add_handler(urllib.request.HTTPSHandler(context=ssl.create_default_context())) + + +def _send(method: str, url: str, headers: dict[str, str], body: bytes | None, timeout: float) -> tuple[int, bytes]: + """Send one request to the MDM and return its status and body, whatever the status""" + if urlparse(url).scheme != "https": + # The token goes with every request, so it must not cross the network readable + raise FleetError("the MDM address must start with https://") + try: + request = urllib.request.Request( + url, data=body, headers={**headers, "User-Agent": f"odmdm-connector/{__version__}"}, method=method + ) + with _OPENER.open(request, timeout=timeout) as response: + return int(response.status), response.read() + except ValueError: + # Its text quotes the header it refused, the token with it + raise FleetError("the MDM address or the token holds a character a request cannot carry") from None + except urllib.error.URLError as exc: + raise FleetError(f"could not reach the MDM: {exc.reason}") from exc + except (OSError, http.client.HTTPException) as exc: + raise FleetError(f"could not reach the MDM: {exc}") from exc + + +def _multipart( + fields: dict[str, str], file_field: str, filename: str, payload: bytes, content_type: str +) -> tuple[str, bytes]: + """A multipart/form-data body and its content type: the plain fields, then the file""" + for name in (*fields, file_field, filename, content_type): + if any(character in name for character in '"\r\n'): + raise ValueError(f"{name!r} cannot go in a multipart header") + boundary = secrets.token_hex(16) + parts = [ + f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode() + for name, value in fields.items() + ] + parts.append( + f'--{boundary}\r\nContent-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n' + f"Content-Type: {content_type}\r\n\r\n".encode() + + payload + + b"\r\n" + ) + parts.append(f"--{boundary}--\r\n".encode()) + return f"multipart/form-data; boundary={boundary}", b"".join(parts) + + +#: Said when Fleet answers 401. A token copied from a signed-in account is that sign-in's own, and Fleet ends it +#: after some days or at sign-out; an API-only user's token does not end. +UNAUTHORIZED = ( + "the API token is not accepted. A token copied from a signed-in account ends with that sign-in: " + "give a new one, or an API-only user's, which does not end" +) + + #: Fleet's hosts listing answers in pages; Fleet's page numbers start from 0 HOSTS_PER_PAGE = 500 @@ -75,25 +147,22 @@ def __init__(self, base_url: str, token: str, timeout: float = 60.0) -> None: self.timeout = timeout def _call(self, method: str, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]: - url = f"{self.base_url}{path}" - try: - response = httpx.request( - method, - url, - json=body, - headers={"Authorization": f"Bearer {self._token}"}, - timeout=self.timeout, - ) - except httpx.HTTPError as exc: - raise FleetError(f"could not reach the MDM: {exc}") from exc - if response.status_code >= 400: + headers = {"Authorization": f"Bearer {self._token}"} + data = None + if body is not None: + headers["Content-Type"] = "application/json" + data = json.dumps(body, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8") + status, answer = _send(method, f"{self.base_url}{path}", headers, data, self.timeout) + if status == 401: + raise Unauthorized(UNAUTHORIZED) + if not 200 <= status < 300: # Enough of the body to keep the reason intact: the retry below matches on it, and # truncating to a couple of hundred characters cut the phrase off mid-word. - raise FleetError(f"{method} {path} answered {response.status_code}: {response.text[:800]}") - if not response.content: + raise FleetError(f"{method} {path} answered {status}: {answer.decode('utf-8', 'replace')[:800]}") + if not answer: return {} try: - payload: dict[str, Any] = response.json() + payload: dict[str, Any] = json.loads(answer) except ValueError as exc: raise FleetError(f"{method} {path} did not answer JSON") from exc return payload @@ -107,20 +176,15 @@ def _upload( file_field: str, content_type: str = "application/json", ) -> dict[str, Any]: - url = f"{self.base_url}{path}" - try: - response = httpx.post( - url, - data=fields, - files={file_field: (filename, payload, content_type)}, - headers={"Authorization": f"Bearer {self._token}"}, - timeout=self.timeout, - ) - except httpx.HTTPError as exc: - raise FleetError(f"could not reach the MDM: {exc}") from exc - if response.status_code >= 400: - raise FleetError(f"upload to {path} answered {response.status_code}: {response.text[:200]}") - return response.json() if response.content else {} + form_type, form = _multipart(fields, file_field, filename, payload, content_type) + headers = {"Authorization": f"Bearer {self._token}", "Content-Type": form_type} + status, answer = _send("POST", f"{self.base_url}{path}", headers, form, self.timeout) + if status == 401: + raise Unauthorized(UNAUTHORIZED) + if not 200 <= status < 300: + raise FleetError(f"upload to {path} answered {status}: {answer.decode('utf-8', 'replace')[:200]}") + result: dict[str, Any] = json.loads(answer) if answer else {} + return result # --- scopes --------------------------------------------------------------- @@ -134,7 +198,7 @@ def team_id(self, name: str, create: bool = False) -> int: if team.get("name") == name: return int(team["id"]) if not create: - raise FleetError(f"no team named {name}: check --team or ODMDM_TEAM") + raise FleetError(f"no team named {name}: check the team's name") created = self._call("POST", "/api/latest/fleet/teams", {"name": name}) team = created.get("team", created) LOGGER.info("Created team %s", name) @@ -224,8 +288,10 @@ def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_ except FleetError as exc: if not here: raise - # Between the delete and the upload the team has no policy, and every phone in it loses the settings - raise FleetError( + # Between the delete and the upload the team has no policy, and every phone in it loses the settings. + # A token refused meanwhile is still a token refused, which the operator is asked for again. + kind = Unauthorized if isinstance(exc, Unauthorized) else FleetError + raise kind( f"policy {name} was being replaced in team {team} and may now be missing ({exc}). " "Run apply to put it back" ) from exc @@ -361,28 +427,34 @@ def ensure_authority(self, name: str, scep_url: str, challenge: str) -> int: standard for it and every MDM words it differently. Fleet happens to expose it, so here it is one less thing for an operator to get wrong by hand. - An existing one is repointed rather than left alone: the name is ours, so a drifted URL - means this deployment moved, not that somebody else owns it. And a challenge is always - sent when there is one: RASENMAEHER makes a new one for every enrolment window, and Fleet - never hands the old one back to compare against. + One authority of a name serves one Deploy App. An existing one with another URL is refused, + never repointed: the shipped template names the same authority for every Deploy App, so a + second Deploy App on the same Fleet would otherwise send the first one's phones to itself. + One with this URL gets the challenge whenever there is one: RASENMAEHER makes a new one for + every enrolment window, and Fleet never hands the old one back to compare against. """ authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) match = [a for a in authorities if a.get("name") == name] if match: authority_id = int(match[0]["id"]) - # The listing does not carry the url, only the detail does, so compare against the - # detail. Reading the url off the listing leaves it None forever, which turns every - # run into a repoint of something already pointing at us. - detail = self._call("GET", f"/api/latest/fleet/certificate_authorities/{authority_id}") - if detail.get("url") == scep_url and not challenge: + # The listing does not carry the url, only the detail does, so compare against the detail + serves = self._call("GET", f"/api/latest/fleet/certificate_authorities/{authority_id}").get("url") + if _same_case(serves or "") != _same_case(scep_url): + raise FleetError( + f"certificate authority {name} already serves {serves or 'another address'}: connect this " + "Deploy App to a Fleet of its own, give it a template that names another authority, or delete " + "that authority in Fleet if the Deploy App moved" + ) + if not challenge: return authority_id # The challenge is never logged. No name in the body: Fleet reads a name on a PATCH as # a rename and then refuses it as a conflict with the authority's own existing name, # so sending it turns every update into a 409. - LOGGER.info("Updating certificate authority %s at %s", name, scep_url) - proxy = {"url": scep_url, "challenge": challenge} if challenge else {"url": scep_url} + LOGGER.info("Giving certificate authority %s at %s the new challenge", name, scep_url) self._call( - "PATCH", f"/api/latest/fleet/certificate_authorities/{authority_id}", {"custom_scep_proxy": proxy} + "PATCH", + f"/api/latest/fleet/certificate_authorities/{authority_id}", + {"custom_scep_proxy": {"url": scep_url, "challenge": challenge}}, ) return authority_id @@ -486,7 +558,7 @@ def certificate_template(self, team: int, name: str) -> int: for template in self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []): if template.get("name") == name: return int(template["id"]) - raise FleetError(f"team {team} has no certificate template named {name}: run apply first") + raise FleetError(f"team {team} has no certificate template named {name}: set Fleet up first") def name_host(self, host: int, callsign: str) -> None: """Give the host its callsign @@ -532,10 +604,11 @@ def apply( nothing typed into Fleet by hand. Without it the authority must already be there, which is the case for an MDM we cannot create one in. """ + # The authority first: refusing it must leave Fleet as it was, a new team included + if template.certificate and scep_url: + self.ensure_authority(template.certificate.authority, scep_url, challenge) team = self.team_id(team_name, create=True) if template.certificate: - if scep_url: - self.ensure_authority(template.certificate.authority, scep_url, challenge) self.ensure_certificate( team, template.certificate.name, diff --git a/tests/test_fleet.py b/tests/test_fleet.py index d6db636..f03903c 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -5,13 +5,21 @@ pass never settles long enough for the device to finish installing anything. """ +import dataclasses +import http.client import json +import logging import re -from typing import Any +import ssl +import urllib.error +import urllib.request +from typing import Any, Self +from urllib.parse import parse_qsl, urlsplit -import httpx import pytest +from odmdm_connector import __version__ +from odmdm_connector import fleet as fleet_module from odmdm_connector.fleet import FleetError, FleetMdm from odmdm_connector.icon import launcher_icon from odmdm_connector.template import App, Certificate, LinkApp, MdmTemplate @@ -25,6 +33,42 @@ ) +@dataclasses.dataclass(frozen=True) +class Url: + path: str + params: dict[str, str] + + +@dataclasses.dataclass(frozen=True) +class Request: + """What the fake Fleet reads of a request""" + + method: str + url: Url + headers: dict[str, str] + content: bytes + + +_dumps = json.dumps + + +class Response: + """An answer of the fake Fleet, read as the real opener's answer is""" + + def __init__(self, status: int, json: Any = None, text: str = "") -> None: + self.status = status + self.content = _dumps(json).encode() if json is not None else text.encode() + + def read(self) -> bytes: + return self.content + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + return None + + class _Fleet: """A Fleet that records what it was told, in order""" @@ -41,19 +85,19 @@ def __init__(self) -> None: self.authorities: list[dict[str, Any]] = [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] self._next_id = 100 - def handler(self, request: httpx.Request) -> httpx.Response: + def handler(self, request: Request) -> Response: path = request.url.path self.calls.append((request.method, path)) if path.endswith("/hosts") and request.method == "GET": # Fleet answers one page at a time, the first being page 0 per_page = int(request.url.params.get("per_page", "100")) first = int(request.url.params.get("page", "0")) * per_page - return httpx.Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts[first : first + per_page]]}) + return Response(200, json={"hosts": [{"id": h["id"]} for h in self.hosts[first : first + per_page]]}) if path.endswith("/device_mapping") and request.method == "PUT": # The name shows in the host detail as its IdP user, which is what the certificate reads found = next(h for h in self.hosts if h["id"] == int(path.split("/")[-2])) found["end_users"] = [{"idp_username": json.loads(request.content)["email"], "idp_info_updated_at": None}] - return httpx.Response(200, json={}) + return Response(200, json={}) if path.endswith("/resend") and request.method == "POST": # Fleet finds the template through the host's own row, so a host without one is not # found (read in Fleet 4.90.1's source). A row still pending is refused, and any other @@ -66,9 +110,9 @@ def handler(self, request: httpx.Request) -> httpx.Response: if r.get("certificate_template_id") == template and r["operation_type"] == "install" ] if not rows: - return httpx.Response(404, json={"message": "Resource Not Found"}) + return Response(404, json={"message": "Resource Not Found"}) if rows[0]["status"] == "pending": - return httpx.Response( + return Response( 400, json={ "message": "Bad request", @@ -76,14 +120,14 @@ def handler(self, request: httpx.Request) -> httpx.Response: }, ) rows[0].update(status="pending", detail="") - return httpx.Response(200) + return Response(200) if "/hosts/" in path and request.method == "GET": which = int(path.rsplit("/", 1)[-1]) - return httpx.Response(200, json={"host": next(h for h in self.hosts if h["id"] == which)}) + return Response(200, json={"host": next(h for h in self.hosts if h["id"] == which)}) if path.endswith("/certificate_authorities") and request.method == "GET": # Fleet's listing omits the url; only the detail carries it. Mirrored so a check # that reads the url off the listing fails here too. - return httpx.Response( + return Response( 200, json={ "certificate_authorities": [{k: v for k, v in a.items() if k != "url"} for a in self.authorities] @@ -92,25 +136,25 @@ def handler(self, request: httpx.Request) -> httpx.Response: if "/certificate_authorities/" in path and request.method == "GET": which = int(path.rsplit("/", 1)[-1]) matching = [a for a in self.authorities if a["id"] == which] - return httpx.Response(200, json=matching[0] if matching else {}) + return Response(200, json=matching[0] if matching else {}) if path.endswith("/certificate_authorities") and request.method == "POST": body = json.loads(request.content)["custom_scep_proxy"] made = {"id": 55, "name": body["name"], "url": body["url"]} self.authorities.append(made) - return httpx.Response(200, json={"certificate_authority": made}) + return Response(200, json={"certificate_authority": made}) if "/certificate_authorities/" in path and request.method == "PATCH": which = int(path.rsplit("/", 1)[-1]) body = json.loads(request.content)["custom_scep_proxy"] if "name" in body: # Fleet reads a name on a PATCH as a rename and refuses it as a conflict with # the authority's own name. Measured against a live Fleet 4.90.1. - return httpx.Response(409, json={"message": "Conflict"}) + return Response(409, json={"message": "Conflict"}) for authority in self.authorities: if authority["id"] == which: authority.update(body) - return httpx.Response(200, json={}) + return Response(200, json={}) if path.endswith("/certificates") and request.method == "GET": - return httpx.Response(200, json={"certificates": self.certificates}) + return Response(200, json={"certificates": self.certificates}) if path.endswith("/certificates") and request.method == "POST": body = json.loads(request.content) made = { @@ -120,19 +164,19 @@ def handler(self, request: httpx.Request) -> httpx.Response: "certificate_authority_id": body["certificate_authority_id"], } self.certificates.append(made) - return httpx.Response(200, json=made) + return Response(200, json=made) if "/certificates/" in path and request.method == "DELETE": gone = int(path.rsplit("/", 1)[-1]) self.certificates = [c for c in self.certificates if c["id"] != gone] - return httpx.Response(200, json={}) + return Response(200, json={}) if path == "/api/latest/fleet/teams" and request.method == "GET": - return httpx.Response(200, json={"teams": [{"id": 7, "name": "rmscep"}]}) + return Response(200, json={"teams": [{"id": 7, "name": "rmscep"}]}) if path.endswith("/software/titles"): # Fleet scopes the listing to one team. A stub that ignored team_id would let a # lookup find another team's app and call that a pass. wanted_team = request.url.params.get("team_id") listed = [t for t in self.titles if wanted_team is None or str(t.get("team_id")) == str(wanted_team)] - return httpx.Response(200, json={"software_titles": listed}) + return Response(200, json={"software_titles": listed}) if path.endswith("/software/web_apps"): # Publishing the SAME url twice yields TWO package names: observed against the real # Fleet, where one url gave x023e... and then xb017.... Google does not dedupe by @@ -144,28 +188,28 @@ def handler(self, request: httpx.Request) -> httpx.Response: asked = title_match.group(1) if title_match else "" if len(asked) >= 30: # Google refuses a web app title of 30 characters or more, as a bare 400. - return httpx.Response(400, json={"message": "Couldn't create. Please check the provided data"}) + return Response(400, json={"message": "Couldn't create. Please check the provided data"}) if any(a["title"] == asked for a in self.web_apps): # Fleet refuses a name already published to the enterprise, whatever team it is # in and even if its team is gone. Publishing cannot be undone. - return httpx.Response(409, json={"message": "Web app with this name already exists in this fleet"}) + return Response(409, json={"message": "Web app with this name already exists in this fleet"}) self._next_id += 1 pkg = f"com.google.enterprise.webapp.x{self._next_id:08x}" self.web_apps.append( {"app_store_id": pkg, "url": wanted, "title": title_match.group(1) if title_match else ""} ) - return httpx.Response(200, json={"app_store_id": pkg}) + return Response(200, json={"app_store_id": pkg}) if path.endswith("/app_store_app") and request.method == "PATCH": - body = json.loads(request.read()) + body = json.loads(request.content) title_id = int(path.split("/")[-2]) for title in self.titles: if title["id"] == title_id and "display_name" in body: title["display_name"] = body["display_name"] - return httpx.Response(200, json={"app_store_app": {}}) + return Response(200, json={"app_store_app": {}}) if path.endswith("/software/app_store_apps"): # This is what puts an app in a team. A new web app is listed under its package name, # not its title, until a device reports it: seen on the real Fleet. - body = json.loads(request.read()) + body = json.loads(request.content) self._next_id += 1 self.titles.append( { @@ -176,16 +220,16 @@ def handler(self, request: httpx.Request) -> httpx.Response: "app_store_app": {"app_store_id": body["app_store_id"]}, } ) - return httpx.Response(200, json={"software_title_id": self._next_id}) + return Response(200, json={"software_title_id": self._next_id}) if path.endswith("/configuration_profiles"): if request.method == "GET": - return httpx.Response( + return Response( 200, json={"profiles": [{k: v for k, v in p.items() if k != "raw"} for p in self.profiles]} ) # An upload the MDM keeps, so a second pass can see it is already there. Without # this the adapter is right to upload again: a profile that has gone missing must # be restored whatever we remember pushing. - raw = re.search(rb"application/json\r\n\r\n(.*)\r\n--", request.read(), re.DOTALL) + raw = re.search(rb"application/json\r\n\r\n(.*)\r\n--", request.content, re.DOTALL) assert raw, "the policy must be uploaded as JSON" self.profiles.append( { @@ -196,24 +240,49 @@ def handler(self, request: httpx.Request) -> httpx.Response: "raw": json.loads(raw.group(1)), } ) - return httpx.Response(200, json={}) + return Response(200, json={}) if "/configuration_profiles/" in path and request.method == "GET": # Only alt=media answers with the policy; without it Fleet sends metadata. found = next(p for p in self.profiles if p["profile_uuid"] == path.rsplit("/", 1)[-1]) media = request.url.params.get("alt") == "media" - return httpx.Response(200, json=found["raw"] if media else {"name": found["name"]}) + return Response(200, json=found["raw"] if media else {"name": found["name"]}) if "/configuration_profiles/" in path and request.method == "DELETE": self.profiles.clear() - return httpx.Response(200, json={}) + return Response(200, json={}) if "/app_store_app" in path or path.endswith("/setup_experience/software"): - return httpx.Response(200, json={}) - return httpx.Response(200, json={}) + return Response(200, json={}) + return Response(200, json={}) + + +class _Opener: + """The opener, answering with a handler instead of the network""" + + def __init__(self, handler: Any) -> None: + self.handler = handler + self.sent: list[urllib.request.Request] = [] + + def open(self, request: urllib.request.Request, timeout: float) -> Any: + self.sent.append(request) + parts = urlsplit(request.full_url) + return self.handler( + Request( + request.get_method(), + Url(parts.path, dict(parse_qsl(parts.query))), + {name.lower(): value for name, value in request.header_items()}, + request.data if isinstance(request.data, bytes) else b"", + ) + ) + + +def _answering(handler: Any, monkeypatch: pytest.MonkeyPatch) -> _Opener: + opener = _Opener(handler) + monkeypatch.setattr(fleet_module, "_OPENER", opener) + return opener def _mdm(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> FleetMdm: - transport = httpx.MockTransport(fleet.handler) - monkeypatch.setattr(httpx, "request", lambda m, u, **kw: httpx.Client(transport=transport).request(m, u, **kw)) - monkeypatch.setattr(httpx, "post", lambda u, **kw: httpx.Client(transport=transport).post(u, **kw)) + # Looked up on every request, so a test can swap the handler after this + _answering(lambda request: fleet.handler(request), monkeypatch) return FleetMdm("https://mdm.test", "token") @@ -277,12 +346,26 @@ def test_force_reaches_a_host_that_just_joined(monkeypatch: pytest.MonkeyPatch) def test_a_refusal_is_reported_not_swallowed(monkeypatch: pytest.MonkeyPatch) -> None: """Applying half a template is worse than applying none""" - transport = httpx.MockTransport(lambda request: httpx.Response(403, text="nope")) - monkeypatch.setattr(httpx, "request", lambda m, u, **kw: httpx.Client(transport=transport).request(m, u, **kw)) + _answering(lambda request: Response(403, text="nope"), monkeypatch) with pytest.raises(FleetError): FleetMdm("https://mdm.test", "token").apply("rmscep", TEMPLATE) +@pytest.mark.parametrize("upload", [False, True]) +def test_a_token_fleet_does_not_accept_is_said_in_plain_words(monkeypatch: pytest.MonkeyPatch, upload: bool) -> None: + """A token from a signed-in account ends with that sign-in, days later: the operator must be told what to do""" + _answering(lambda request: Response(401, json={"message": "Authentication required"}), monkeypatch) + mdm = FleetMdm("https://mdm.test", "token") + + with pytest.raises(FleetError, match="the API token is not accepted.*give a new one") as raised: + if upload: + mdm._upload("/api/latest/fleet/configuration_profiles", {}, "policy.json", b"{}", "profile") + else: + mdm.team_id("Deploy App") + + assert "Authentication required" not in str(raised.value) + + def test_the_launcher_icon_is_a_valid_png() -> None: """Without one the web app is accepted and then never published, and every install says NOT_FOUND""" png = launcher_icon() @@ -464,16 +547,40 @@ def test_a_new_windows_challenge_reaches_an_authority_already_pointing_at_us( assert fleet.authorities[0]["url"] == "https://deployment.test/scep" -def test_a_drifted_authority_is_repointed_not_duplicated(monkeypatch: pytest.MonkeyPatch) -> None: - """The name is ours, so a different URL means the deployment moved +def test_an_authority_that_serves_another_deploy_app_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """The shipped template names the same authority for every Deploy App - Creating a second one would leave the certificate template pointing at whichever the lookup - happened to find first. + Repointing it would send the phones of the Deploy App it serves to the one connected now. """ fleet = _Fleet() - _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") - assert len(fleet.authorities) == 1, "a drifted authority must be repointed, not duplicated" - assert fleet.authorities[0]["url"] == "https://moved.test/scep" + with pytest.raises(FleetError) as raised: + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") + + assert str(raised.value) == ( + "certificate authority RMSCEP already serves https://deployment.test/scep: connect this Deploy App to a " + "Fleet of its own, give it a template that names another authority, or delete that authority in Fleet if " + "the Deploy App moved" + ) + assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_an_authority_kept_with_an_upper_case_host_is_still_ours(monkeypatch: pytest.MonkeyPatch) -> None: + """An earlier version kept the host as the line had it, and a host compares without case""" + fleet = _Fleet() + fleet.authorities[0]["url"] = "HTTPS://Deployment.TEST/scep" + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://deployment.test/scep", challenge="c3") + + assert fleet.authorities[0]["challenge"] == "c3" + + +def test_a_refused_authority_makes_no_team(monkeypatch: pytest.MonkeyPatch) -> None: + """A second Deploy App naturally gets a team of its own, and a refusal must not leave it behind empty""" + fleet = _Fleet() + with pytest.raises(FleetError, match="already serves https://deployment.test/scep"): + _mdm(fleet, monkeypatch).apply("Second unit", _with_cert(), scep_url="https://second.test/scep", challenge="c2") + + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" def test_without_a_scep_url_the_authority_must_already_exist(monkeypatch: pytest.MonkeyPatch) -> None: @@ -484,17 +591,6 @@ def test_without_a_scep_url_the_authority_must_already_exist(monkeypatch: pytest _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) -def test_repointing_does_not_try_to_rename(monkeypatch: pytest.MonkeyPatch) -> None: - """Fleet refuses a PATCH that carries a name, as a conflict with the name already there - - Found against a live Fleet: every repoint answered 409 and no deployment could be moved to - a new responder without deleting the authority by hand. - """ - fleet = _Fleet() - _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") - assert fleet.authorities[0]["url"] == "https://moved.test/scep", "the repoint must have gone through" - - def test_applying_twice_publishes_one_web_app(monkeypatch: pytest.MonkeyPatch) -> None: """A re-run reuses the launcher instead of leaving another permanent one behind @@ -619,3 +715,178 @@ def test_a_policy_without_a_time_is_reported(monkeypatch: pytest.MonkeyPatch) -> with pytest.raises(FleetError, match="the time '' could not be read"): mdm.resend_policy(7, mdm.phones(7, "rmscep")) assert not _policy_uploads(fleet) + + +# --- the transport -------------------------------------------------------------- + +TOKEN = "secret-token-4f2a" + + +@pytest.mark.parametrize("url", ["http://mdm.example.fi", "file:///etc", "ftp://192.0.2.10"]) +def test_only_https_is_sent(monkeypatch: pytest.MonkeyPatch, url: str) -> None: + """The token goes with every request, so it must not cross the network readable""" + opener = _answering(lambda request: Response(200, json={}), monkeypatch) + + with pytest.raises(FleetError, match="must start with https://"): + FleetMdm(url, TOKEN).team_id("rmscep") + + assert not opener.sent + + +def test_the_opener_only_proxies_and_speaks_https() -> None: + """No redirect is followed, no other scheme is spoken, no status is turned into an exception + + The proxy handler is there only while the environment names a proxy: without one it has nothing to open. + """ + handlers: list[object] = vars(fleet_module._OPENER)["handlers"] + + assert {type(handler) for handler in handlers} <= {urllib.request.ProxyHandler, urllib.request.HTTPSHandler} + https = next(handler for handler in handlers if isinstance(handler, urllib.request.HTTPSHandler)) + context: ssl.SSLContext = vars(https)["_context"] + assert context.verify_mode == ssl.CERT_REQUIRED + assert context.check_hostname + + +def test_a_request_says_who_asks_and_what_it_sends(monkeypatch: pytest.MonkeyPatch) -> None: + seen: list[Request] = [] + + def answer(request: Request) -> Response: + seen.append(request) + return Response(200, json={"team": {"id": 9}}) + + _answering(answer, monkeypatch) + + assert FleetMdm("https://mdm.example.fi/", TOKEN).team_id("Ålands", create=True) == 9 + + created = seen[-1] + assert (created.method, created.url.path) == ("POST", "/api/latest/fleet/teams") + assert created.headers["authorization"] == f"Bearer {TOKEN}" + assert created.headers["user-agent"] == f"odmdm-connector/{__version__}" + assert created.headers["content-type"] == "application/json" + assert json.loads(created.content) == {"name": "Ålands"} + + +def test_an_empty_answer_is_an_empty_object(monkeypatch: pytest.MonkeyPatch) -> None: + _answering(lambda request: Response(204), monkeypatch) + assert FleetMdm("https://mdm.example.fi", TOKEN)._call("DELETE", "/api/latest/fleet/teams/9") == {} + + +@pytest.mark.parametrize("status", [301, 302, 307, 404, 500]) +def test_an_answer_outside_2xx_is_a_refusal(monkeypatch: pytest.MonkeyPatch, status: int) -> None: + """A redirect is not followed either: it would carry the token on to wherever it points""" + opener = _answering(lambda request: Response(status, text="x" * 1000), monkeypatch) + + with pytest.raises(FleetError) as raised: + FleetMdm("https://mdm.example.fi", TOKEN)._call("GET", "/api/latest/fleet/teams") + + assert str(raised.value) == f"GET /api/latest/fleet/teams answered {status}: {'x' * 800}" + assert len(opener.sent) == 1 + + +def test_an_upload_refused_says_so(monkeypatch: pytest.MonkeyPatch) -> None: + _answering(lambda request: Response(302, text="y" * 300), monkeypatch) + + with pytest.raises(FleetError) as raised: + FleetMdm("https://mdm.example.fi", TOKEN)._upload("/api/x", {}, "p.json", b"{}", "profile") + + assert str(raised.value) == f"upload to /api/x answered 302: {'y' * 200}" + + +@pytest.mark.parametrize( + "failure", + [ + urllib.error.URLError(ConnectionRefusedError(61, "Connection refused")), + urllib.error.URLError(ssl.SSLCertVerificationError("certificate verify failed")), + TimeoutError("timed out"), + ssl.SSLError("record layer failure"), + http.client.RemoteDisconnected("Remote end closed connection without response"), + ], +) +def test_an_mdm_out_of_reach_is_said_without_the_token( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, failure: Exception +) -> None: + def failing(request: Request) -> Response: + raise failure + + _answering(failing, monkeypatch) + caplog.set_level(logging.DEBUG) + + with pytest.raises(FleetError, match="^could not reach the MDM: ") as raised: + FleetMdm("https://mdm.example.fi", TOKEN).team_id("rmscep") + + assert TOKEN not in str(raised.value) + assert TOKEN not in caplog.text + + +def test_a_request_that_cannot_be_carried_is_said_without_the_token( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """http.client refuses a header with a line break in a ValueError whose text quotes it, token and all""" + + def refusing(request: Request) -> Response: + raise ValueError(f"Invalid header value {request.headers['authorization'].encode()!r}") + + _answering(refusing, monkeypatch) + caplog.set_level(logging.DEBUG) + + with pytest.raises(FleetError) as raised: + FleetMdm("https://mdm.example.fi", TOKEN).team_id("rmscep") + + assert str(raised.value) == "the MDM address or the token holds a character a request cannot carry" + assert raised.value.__cause__ is None and raised.value.__suppress_context__ + assert TOKEN not in caplog.text + + +def test_the_upload_is_a_form_with_the_file_last(monkeypatch: pytest.MonkeyPatch) -> None: + seen: list[Request] = [] + + def answer(request: Request) -> Response: + seen.append(request) + return Response(200, json={"ok": True}) + + _answering(answer, monkeypatch) + + result = FleetMdm("https://mdm.example.fi", TOKEN)._upload( + "/api/x", + {"title": "Deploy App", "url": "https://deploy.example.fi"}, + "icon.png", + b"\x89PNG", + "icon", + "image/png", + ) + + assert result == {"ok": True} + kind, _, boundary = seen[0].headers["content-type"].partition("; boundary=") + assert kind == "multipart/form-data" + assert ( + seen[0].content + == ( + f'--{boundary}\r\nContent-Disposition: form-data; name="title"\r\n\r\nDeploy App\r\n' + f'--{boundary}\r\nContent-Disposition: form-data; name="url"\r\n\r\nhttps://deploy.example.fi\r\n' + f'--{boundary}\r\nContent-Disposition: form-data; name="icon"; filename="icon.png"\r\n' + f"Content-Type: image/png\r\n\r\n" + ).encode() + + b"\x89PNG\r\n" + + f"--{boundary}--\r\n".encode() + ) + + +@pytest.mark.parametrize( + "fields, filename, content_type", + [ + ({'ti"tle': "x"}, "p.json", "application/json"), + ({"title\r\n": "x"}, "p.json", "application/json"), + ({}, 'p".json', "application/json"), + ({}, "p\n.json", "application/json"), + ({}, "p.json", "application/json\r\nX-Evil: 1"), + ], +) +def test_a_name_that_would_break_the_form_is_refused( + monkeypatch: pytest.MonkeyPatch, fields: dict[str, str], filename: str, content_type: str +) -> None: + opener = _answering(lambda request: Response(200), monkeypatch) + + with pytest.raises(ValueError, match="cannot go in a multipart header"): + FleetMdm("https://mdm.example.fi", TOKEN)._upload("/api/x", fields, filename, b"{}", "profile", content_type) + + assert not opener.sent From 2591d464934cd88bd4d99483f3f10961a12c63e7 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 060/104] fix: sentences from a plugin name no command, and the token's help says which token ends --- .../src/odmdm_connector_demo/__init__.py | 3 +- src/odmdm_connector/fleet_plugin.py | 47 ++++++++----- tests/test_fleet_plugin.py | 66 ++++++++++++++++--- tests/test_testing.py | 8 +-- 4 files changed, 93 insertions(+), 31 deletions(-) diff --git a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py index 5488fab..c7f39d9 100644 --- a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py +++ b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py @@ -27,8 +27,7 @@ class DemoMdm: ) missing: ClassVar[Mapping[str, str]] = { SET_CHALLENGE: ( - "The demo MDM takes no challenge by API: paste it in its console under " - "Certificates > SCEP > Challenge, then run phones" + "The demo MDM takes no challenge by API: paste it in its console under Certificates > SCEP > Challenge" ), } diff --git a/src/odmdm_connector/fleet_plugin.py b/src/odmdm_connector/fleet_plugin.py index bd050f5..555514e 100644 --- a/src/odmdm_connector/fleet_plugin.py +++ b/src/odmdm_connector/fleet_plugin.py @@ -11,7 +11,7 @@ from urllib.parse import urlparse from . import template -from .fleet import FleetError, FleetMdm +from .fleet import FleetError, FleetMdm, Unauthorized from .fleet import Phone as FleetPhone from .mdm import API_VERSION, Field, MdmError, Phone, State, Step from .settings import Settings @@ -43,7 +43,7 @@ def _failure(phone: FleetPhone) -> tuple[State, str]: """What Fleet's detail on a failed request means""" if "does not have an IDP user" in phone.detail: # Naming does not send the request again, so a name beside this detail was given without a resend - return (State.NOT_ASKED, "run resend") if phone.callsign else (State.NEEDS_NAME, "") + return (State.NOT_ASKED, "ask again") if phone.callsign else (State.NEEDS_NAME, "") if "SCEP enrollment failed" in phone.detail: return State.REFUSED, "name taken or not allowed, enrolment closed, or Fleet has an old challenge" if "Network error" in phone.detail: @@ -52,26 +52,41 @@ def _failure(phone: FleetPhone) -> tuple[State, str]: return State.FAILED, phone.detail +def _refused(exc: FleetError, named: Mapping[str, str] | None = None, lines: Sequence[str] = ()) -> MdmError: + """Fleet's refusal as the contract's, marked when Fleet does not accept the token""" + return MdmError(f"Fleet refused: {exc}", named, lines, unauthorized=isinstance(exc, Unauthorized)) + + class FleetPlugin: """FleetDM, one team per Deploy App""" API_VERSION: ClassVar[int] = API_VERSION title: ClassVar[str] = "Fleet" fields: ClassVar[tuple[Field, ...]] = ( - Field("mdm_url", "Fleet address", help="Base URL of Fleet's API, https only"), + Field("mdm_url", "Fleet address", help="The address you open Fleet at, starting with https://", required=True), Field( "token", "API token", secret=True, - help="A Fleet API token. Giving Fleet a challenge needs a global admin's", + help=( + "A global admin's API token: in Fleet, My account, Get API token. That one ends after some days; " + "an API-only user's does not." + ), + required=True, ), Field("team", "Team", default="Deploy App", help="The team phones enrol into and get the certificate in"), - Field("template", "Template", help="A template file; without one, the one shipped with the connector"), + Field( + "template", + "Template", + help="A template file; without one, the one shipped with the connector", + advanced=True, + ), Field( "key_alias", "Key alias", default="rmscep", help="The certificate template's name, the Android keystore alias. Never change it for a deployment", + advanced=True, ), ) missing: ClassVar[Mapping[str, str]] = {} @@ -91,13 +106,13 @@ def _fleet(self) -> FleetMdm: if self._api: return self._api if not self._url: - raise MdmError("Give --mdm-url or set ODMDM_MDM_URL") + raise MdmError("The Fleet address is missing") if urlparse(self._url).scheme != "https": raise MdmError( "The MDM address must start with https://, or the API token would cross the network readable" ) if not self._token: - raise MdmError("Set ODMDM_TOKEN_FILE to a file holding the Fleet API token") + raise MdmError("The Fleet API token is missing") self._api = FleetMdm(self._url, self._token) return self._api @@ -129,18 +144,18 @@ def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> self.team, wanted, force_policy=force, scep_url=window.scep_url, challenge=window.challenge ) except FleetError as exc: - raise MdmError(f"Fleet refused: {exc}") from exc + raise _refused(exc) from exc yield Step(f"Applied to team {result['team_id']}: {len(result['assigned'])} apps assigned", True) def set_challenge(self, window: Settings) -> None: - """Repoint the template's certificate authority, and change nothing else""" + """Give the template's certificate authority the window's challenge, and change nothing else""" wanted = self._template(window) if not wanted.certificate: raise MdmError("The template states no certificate, so there is no authority to give it to") try: self._fleet().ensure_authority(wanted.certificate.authority, window.scep_url, window.challenge) except FleetError as exc: - raise MdmError(f"Fleet refused: {exc}") from exc + raise _refused(exc) from exc def _phones(self) -> dict[str, FleetPhone]: """The team's phones by id, read now: never kept between calls, so nothing shown is stale""" @@ -149,7 +164,7 @@ def _phones(self) -> dict[str, FleetPhone]: self._team_id = api.team_id(self.team) return {str(phone.id): phone for phone in api.phones(self._team_id, self.key_alias)} except FleetError as exc: - raise MdmError(f"Fleet refused: {exc}") from exc + raise _refused(exc) from exc def phones(self) -> list[Phone]: return [ @@ -182,13 +197,13 @@ def name(self, names: Mapping[str, str]) -> list[str]: for key, callsign in names.items(): old = found[key] if old.status == "verified" and old.callsign.lower() == callsign.lower(): - lines.append(f"Host {key} is already {old.callsign}") + lines.append(f"Phone {key} is already {old.callsign}") continue api.name_host(old.id, callsign) named[key] = callsign if old.status: api.resend(old.id, certificate) - line = f"Host {key} is {callsign}" + line = f"Phone {key} is {callsign}" if not old.status: line += ". Fleet has no certificate request for it, so nothing was sent" elif old.status == "verified" and old.callsign: @@ -199,7 +214,7 @@ def name(self, names: Mapping[str, str]) -> list[str]: if named: lines += self._policy_again(found) except FleetError as exc: - raise MdmError(f"Fleet refused: {exc}", named, lines) from exc + raise _refused(exc, named, lines) from exc return lines def ask_again(self, ids: Sequence[str]) -> list[str]: @@ -217,8 +232,8 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: certificate = api.certificate_template(self._team_id, self.key_alias) for key in chosen: api.resend(found[key].id, certificate) - lines.append(f"Host {key} ({found[key].callsign or 'no name'}): certificate asked for again") + lines.append(f"Phone {key} ({found[key].callsign or 'no name'}): certificate asked for again") lines += self._policy_again(found) except FleetError as exc: - raise MdmError(f"Fleet refused: {exc}", lines=lines) from exc + raise _refused(exc, lines=lines) from exc return lines diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py index d2aa2da..235bfe7 100644 --- a/tests/test_fleet_plugin.py +++ b/tests/test_fleet_plugin.py @@ -2,14 +2,13 @@ import datetime -import httpx import pytest from odmdm_connector.fleet_plugin import FleetPlugin from odmdm_connector.mdm import Mdm, MdmError, State from odmdm_connector.settings import Settings -from .test_fleet import _Fleet, _host, _mdm +from .test_fleet import Request, Response, _Fleet, _host, _mdm NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" REFUSED = "SCEP enrollment failed: Enrollment failed with SCEP failInfo: badMessageCheck" @@ -36,7 +35,7 @@ def _plugin(**values: str) -> Mdm: ("", "", "", State.NO_REQUEST, ""), ("verified", "OTTER4", "", State.READY, ""), ("failed", "", NO_NAME, State.NEEDS_NAME, ""), - ("failed", "OTTER4", NO_NAME, State.NOT_ASKED, "run resend"), + ("failed", "OTTER4", NO_NAME, State.NOT_ASKED, "ask again"), ("failed", "OTTER4", REFUSED, State.REFUSED, "name taken or not allowed"), ("failed", "OTTER4", UNREACHED, State.UNREACHABLE, ""), ("failed", "OTTER4", "Something new", State.FAILED, "Something new"), @@ -68,8 +67,8 @@ def test_name_answers_its_lines_and_reads_the_phones_once(fleet: _Fleet) -> None lines = _plugin().name({"32": "OTTER5", "31": "OTTER4"}) assert lines == [ - "Host 32 is OTTER5. Fleet has no certificate request for it, so nothing was sent", - "Host 31 is OTTER4", + "Phone 32 is OTTER5. Fleet has no certificate request for it, so nothing was sent", + "Phone 31 is OTTER4", ] assert _listings(fleet) == 1 @@ -101,9 +100,9 @@ def test_an_id_not_in_the_team_changes_nothing(fleet: _Fleet, call: str) -> None def test_a_batch_stopped_half_way_names_the_phones_named(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: answer = fleet.handler - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.url.path.endswith("/hosts/32/certificates/81/resend"): - return httpx.Response(500, text="database is locked") + return Response(500, text="database is locked") return answer(request) monkeypatch.setattr(fleet, "handler", refusing) @@ -114,14 +113,48 @@ def refusing(request: httpx.Request) -> httpx.Response: _plugin().name({"31": "OTTER1", "32": "OTTER2", "33": "OTTER3"}) assert raised.value.named == {"31": "OTTER1", "32": "OTTER2"} + assert not raised.value.unauthorized + + +def test_a_token_fleet_does_not_accept_is_marked(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """So the connector lets go of it and asks for it again""" + monkeypatch.setattr(fleet, "handler", lambda request: Response(401, json={"message": "Authentication required"})) + _mdm(fleet, monkeypatch) + + with pytest.raises(MdmError, match="Fleet refused: the API token is not accepted") as raised: + _plugin().phones() + + assert raised.value.unauthorized + + +def test_a_token_refused_while_the_policy_is_replaced_is_marked(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: + """The token ended between deleting the old policy and uploading the new one""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.method == "POST" and request.url.path.endswith("/configuration_profiles"): + return Response(401, json={"message": "Authentication required"}) + return answer(request) + + monkeypatch.setattr(fleet, "handler", refusing) + _mdm(fleet, monkeypatch) + fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled="2026-11-21T09:00:00Z")] + fleet.profiles = [ + {"name": "rmscep-policy", "profile_uuid": "g4bb", "created_at": "2026-11-20T21:02:44Z", "raw": {}} + ] + + with pytest.raises(MdmError, match="was being replaced in team 7 and may now be missing") as raised: + _plugin().name({"31": "OTTER1"}) + + assert raised.value.unauthorized @pytest.mark.parametrize( ("values", "says"), [ - ({"mdm_url": ""}, "ODMDM_MDM_URL"), + ({"mdm_url": ""}, "The Fleet address is missing"), ({"mdm_url": "http://mdm.test"}, "must start with https://"), - ({"token": ""}, "ODMDM_TOKEN_FILE"), + ({"token": ""}, "The Fleet API token is missing"), ], ) def test_fleet_is_reached_only_when_configured(fleet: _Fleet, values: dict[str, str], says: str) -> None: @@ -142,3 +175,18 @@ def test_ask_again_without_ids_and_nobody_failed_answers_nothing(fleet: _Fleet) assert _plugin().ask_again([]) == [] assert not [method for method, _ in fleet.calls if method != "GET"] + + +def test_the_template_and_key_alias_are_advanced() -> None: + """Rarely changed, and the key alias never for a deployment: the window shows them only when asked""" + assert [item.key for item in FleetPlugin.fields if item.advanced] == ["template", "key_alias"] + + +def test_the_token_help_says_which_token_lasts() -> None: + """The token My account gives ends after some days, and the refusal then says so""" + [token] = [each for each in FleetPlugin.fields if each.key == "token"] + + assert token.help == ( + "A global admin's API token: in Fleet, My account, Get API token. That one ends after some days; " + "an API-only user's does not." + ) diff --git a/tests/test_testing.py b/tests/test_testing.py index 0219d0c..c62bcc2 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -3,14 +3,13 @@ from collections.abc import Mapping, Sequence from typing import ClassVar -import httpx import pytest from odmdm_connector.fleet_plugin import FleetPlugin from odmdm_connector.mdm import CAPABILITIES, Mdm, MdmError, Phone, State from odmdm_connector.testing import FakeMdm, contract -from .test_fleet import _Fleet, _host, _mdm +from .test_fleet import Request, Response, _Fleet, _host, _mdm NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" CHECKS = pytest.mark.parametrize("check", contract.CHECKS, ids=lambda check: check.__name__) @@ -30,6 +29,7 @@ def fleet(monkeypatch: pytest.MonkeyPatch) -> contract.Factory: def factory(refuse_after: int | None = None) -> Mdm: stub = _Fleet() + stub.authorities = [{"id": 3, "name": "RMSCEP", "url": contract.WINDOW.scep_url}] stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": "CN=$X", "certificate_authority_id": 3}] stub.hosts = [ _host(31, "failed", detail=NO_NAME), @@ -39,10 +39,10 @@ def factory(refuse_after: int | None = None) -> Mdm: answer = stub.handler named: list[str] = [] - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.url.path.endswith("/device_mapping"): if refuse_after is not None and len(named) >= refuse_after: - return httpx.Response(500, text="database is locked") + return Response(500, text="database is locked") named.append(request.url.path) return answer(request) From 915eb2b77964fde994d6f75c6712bac151095754 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 061/104] refactor: read the command line with the standard library, and start the page with the web command The challenge is taken only from ODMDM_CHALLENGE or a hidden prompt, and the token from a file. --- src/odmdm_connector/__main__.py | 5 + src/odmdm_connector/config.py | 20 -- src/odmdm_connector/console.py | 523 ++++++++++++++++++------------- tests/test_console.py | 533 +++++++++++++++++++++----------- 4 files changed, 656 insertions(+), 425 deletions(-) create mode 100644 src/odmdm_connector/__main__.py delete mode 100644 src/odmdm_connector/config.py diff --git a/src/odmdm_connector/__main__.py b/src/odmdm_connector/__main__.py new file mode 100644 index 0000000..4c493b2 --- /dev/null +++ b/src/odmdm_connector/__main__.py @@ -0,0 +1,5 @@ +"""python -m odmdm_connector, the same as the odmdm-connector command""" + +from odmdm_connector.console import odmdm_connector_cli + +odmdm_connector_cli() diff --git a/src/odmdm_connector/config.py b/src/odmdm_connector/config.py deleted file mode 100644 index b24e90b..0000000 --- a/src/odmdm_connector/config.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Configuration, from the environment - -Every setting is prefixed ODMDM_. These are the deployment's; the MDM's own come from its plugin's -fields, read by the command line as ODMDM_. -""" - -import os - - -def _env(name: str, default: str = "") -> str: - return os.environ.get(f"ODMDM_{name}", default) - - -LOG_LEVEL: int = int(_env("LOG_LEVEL", "20")) - -#: The deployment's DNS name, which the template substitutes into URLs -DOMAIN: str = _env("DOMAIN") - -#: The challenge shown on Deploy App's MDM page. It is new for every enrolment window. -CHALLENGE: str = _env("CHALLENGE") diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index be56e80..650e65f 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -5,90 +5,88 @@ one built in. """ +import argparse +import codecs import datetime +import getpass +import inspect import logging import os -from collections.abc import Mapping +import sys +from collections.abc import Callable, Mapping, Sequence from pathlib import Path -from typing import NoReturn from urllib.parse import urlparse -import click -from libadvian.logging import init_logging - from odmdm_connector import __version__ -from . import config, core, plugins, settings +from . import core, plugins, settings, web +from .app import App from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError from .settings import Settings -LOGGER = logging.getLogger(__name__) - - -@click.group() -@click.version_option(version=__version__) -@click.pass_context -@click.option("-v", "--verbose", count=True, help="Shorthand for info/debug loglevel (-v/-vv)") -@click.option( - "--mdm", - "chosen", - envvar="ODMDM_MDM", - default="fleet", - show_default=True, - metavar="NAME", - help="The MDM to talk to (default: ODMDM_MDM, else fleet)", -) -@click.option( - "--set", - "given", - multiple=True, - metavar="KEY=VALUE", - help="A setting of the MDM, such as mdm_url; never a secret, which is read from the file ODMDM__FILE names", -) -def cli_group(ctx: click.Context, verbose: int, chosen: str, given: tuple[str, ...]) -> None: - """Connect an MDM, Fleet built in, to an OpenDefence deployment's device enrolment""" - loglevel = config.LOG_LEVEL - if verbose == 1: - loglevel = 20 - if verbose >= 2: - loglevel = 10 - init_logging(loglevel) - LOGGER.setLevel(loglevel) - # One line per MDM request buries what the command says; -vv brings them back - logging.getLogger("httpx").setLevel(max(loglevel, logging.WARNING) if verbose < 2 else loglevel) - sets: dict[str, str] = {} - for value in given: - key, equals, setting = value.partition("=") - if not key or not equals: - raise click.UsageError("--set takes KEY=VALUE") - sets[key] = setting - ctx.obj = {"mdm": chosen, "set": sets} +#: Said when ODMDM_LOG_LEVEL is not a number +LOG_LEVEL = "ODMDM_LOG_LEVEL must be a whole number, such as 10 for debug or 20 for info: change it, or unset it." +#: Said when Ctrl+C stops the page while a job is under way +STOPPED_BUSY = "Stopped while the MDM was still being worked with: refresh the phones when the connector runs again." -def odmdm_connector_cli() -> None: - """CLI entrypoint""" - cli_group() # pylint: disable=no-value-for-parameter +class _Usage(Exception): + """A command line the connector cannot act on: said with the command's usage, exit 2""" + + +class _Failed(Exception): + """A sentence on stderr, exit 1""" + + +def main(argv: Sequence[str] | None = None) -> int: + """Run the command line and answer its exit code; a usage error exits 2 through argparse""" + args = _parser().parse_args(argv) + try: + level = int(os.environ.get("ODMDM_LOG_LEVEL", "20")) + except ValueError: + print(LOG_LEVEL, file=sys.stderr) + return 1 + if args.verbose == 1: + level = logging.INFO + if args.verbose >= 2: + level = logging.DEBUG + logging.basicConfig(stream=sys.stderr, format="%(asctime)s %(levelname)s %(name)s: %(message)s") + logging.getLogger().setLevel(level) + run: Callable[[argparse.Namespace], int] = args.run + try: + for value in args.given: + key, equals, _ = value.partition("=") + if not key or not equals: + raise _Usage("--set takes KEY=VALUE") + return run(args) + except _Usage as exc: + args.parser.error(str(exc)) + except _Failed as exc: + print(exc, file=sys.stderr) + except (KeyboardInterrupt, EOFError): + print("Stopped before the command finished.", file=sys.stderr) + return 1 -def _fail(ctx: click.Context, message: str) -> NoReturn: - click.echo(message, err=True) - ctx.exit(1) +def odmdm_connector_cli() -> None: + """CLI entrypoint""" + sys.exit(main()) -def _chosen(ctx: click.Context, name: str) -> type[Mdm]: +def _chosen(name: str) -> type[Mdm]: """The class of the MDM of that name, saying first whose code it is when it is not built in""" try: plugin = plugins.find(name) if not plugin.built_in: - click.echo( + print( f"The MDM {name} is a plugin from {plugin.package} {plugin.version}: code that sees the MDM token", - err=True, + file=sys.stderr, ) return plugins.load(name) except plugins.NotInstalled as exc: - raise click.UsageError(str(exc)) from exc + raise _Usage(str(exc)) from exc except plugins.PluginError as exc: - _fail(ctx, str(exc)) + raise _Failed(str(exc)) from exc def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str]) -> dict[str, str]: @@ -100,49 +98,86 @@ def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str]) -> d keys = sorted(item.key for item in fields) unknown = sorted(set(given) - set(keys)) if unknown: - raise click.UsageError(f"{name} has no setting {unknown[0]}; it has {', '.join(keys)}") + raise _Usage(f"{name} has no setting {unknown[0]}; it has {', '.join(keys)}") values: dict[str, str] = {} for item in fields: env = f"ODMDM_{item.key.upper()}" if item.secret: if item.key in given: - raise click.UsageError(f"{item.key} is a secret: put it in a file and set {env}_FILE to that file") + raise _Usage(f"{item.key} is a secret: put it in a file and set {env}_FILE to that file") path = os.environ.get(f"{env}_FILE", "") - values[item.key] = Path(path).read_text(encoding="utf-8").strip() if path and Path(path).is_file() else "" + values[item.key] = _secret_file(Path(path), item.label) if path and Path(path).is_file() else "" + if not values[item.key].isprintable(): + raise _Failed( + f"The {item.label} holds a line break or another character that cannot be part of it: copy it again." + ) else: values[item.key] = given[item.key] if item.key in given else os.environ.get(env, item.default) return values -def _mdm(ctx: click.Context, capability: str = "", **shorthands: str | None) -> Mdm: - """The chosen MDM, configured; or the MDM's sentence for lacking the capability, and exit +def _secret_file(path: Path, label: str) -> str: + """A secret's file as text: UTF-16 by its byte order mark, as Windows PowerShell 5.1 writes, else UTF-8 - The shorthands are the per-command options such as --team, each the same as --set team=... + Never the bytes in a message: a decoding error quotes them. """ - name = str(ctx.obj["mdm"]) - chosen = _chosen(ctx, name) + try: + data = path.read_bytes() + if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)): + return data.decode("utf-16").strip() + return data.decode("utf-8-sig").strip() + except (OSError, UnicodeDecodeError): + raise _Failed(f"The file {path} cannot be read as plain text: save the {label} in it as plain text.") from None + + +def _missing(fields: tuple[Field, ...], values: Mapping[str, str]) -> str: + """How to give the first required setting that is empty; empty when none is""" + for item in fields: + if item.required and not values[item.key]: + env = f"ODMDM_{item.key.upper()}" + if item.secret: + return f"{item.label} is missing: put it in a file and set {env}_FILE to that file" + return f"{item.label} is missing: give --set {item.key}=... or set {env}" + return "" + + +def _mdm(args: argparse.Namespace, capability: str = "", complete: bool = True) -> Mdm: + """The chosen MDM, configured; or the MDM's sentence for lacking the capability + + The command's own options such as --team are each the same as --set team=... + complete: every required setting must be given, which a dry run does not need. + """ + given = {key: setting for key, _, setting in (value.partition("=") for value in args.given)} + chosen = _chosen(args.chosen) if capability in chosen.missing: - _fail(ctx, chosen.missing[capability]) - given = {**ctx.obj["set"], **{key: value for key, value in shorthands.items() if value is not None}} + raise _Failed(chosen.missing[capability]) + for key in ("mdm_url", "team", "template"): + if getattr(args, key, None) is not None: + given[key] = getattr(args, key) + values = _values(args.chosen, chosen.fields, given) + missing = _missing(chosen.fields, values) if complete else "" + if missing: + raise _Failed(missing) try: - return chosen(_values(name, chosen.fields, given)) + return chosen(values) except MdmError as exc: - _fail(ctx, str(exc)) + raise _Failed(str(exc)) from exc -def _domain(ctx: click.Context, domain: str | None) -> str: - the_domain = domain or config.DOMAIN +def _domain(args: argparse.Namespace) -> str: + the_domain: str = args.domain or os.environ.get("ODMDM_DOMAIN", "") if not the_domain: - _fail(ctx, "Give --domain or set ODMDM_DOMAIN") + raise _Failed("Give --domain or set ODMDM_DOMAIN") return the_domain def _now() -> datetime.datetime: - return datetime.datetime.now(datetime.UTC) + """Now, in this computer's time zone, which the times said are in""" + return datetime.datetime.now().astimezone() -def _window(ctx: click.Context, value: str, domain: str) -> Settings: - """The enrolment window, from a settings line or a bare challenge, or exit after saying why not +def _window(value: str, domain: str) -> Settings: + """The enrolment window, from a settings line or a bare challenge, or why not A bare challenge says nothing of when the window closes. The challenge is never in a message. """ @@ -151,40 +186,14 @@ def _window(ctx: click.Context, value: str, domain: str) -> Settings: try: line = settings.parse(value, _now()) except settings.SettingsError as exc: - _fail(ctx, str(exc)) + raise _Failed(str(exc)) from exc host = urlparse(line.scep_url).hostname or "" if host != domain.lower(): - _fail(ctx, f"The settings line is for {host}, not {domain}: copy it from this deployment's MDM page") + raise _Failed(f"The settings line is for {host}, not {domain}: copy it from this deployment's MDM page") return line -MDM_URL = click.option("--mdm-url", default=None, help="The MDM's address, as --set mdm_url (default: ODMDM_MDM_URL)") -TEAM = click.option("--team", default=None, help="The team the phones are in, as --set team (default: ODMDM_TEAM)") -TEMPLATE = click.option( - "--template", "path", default=None, help="What to install, as --set template (default: ODMDM_TEMPLATE)" -) -DOMAIN = click.option("--domain", default=None, help="The deployment's DNS name (default: ODMDM_DOMAIN)") - - -@cli_group.command(name="apply") -@click.pass_context -@TEMPLATE -@MDM_URL -@TEAM -@DOMAIN -@click.option( - "--force-policy", is_flag=True, help="Re-upload the policy even if unchanged, to reach a host that just joined" -) -@click.option("--dry-run", is_flag=True, help="Read and validate the template, then stop") -def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, - path: str | None, - mdm_url: str | None, - team: str | None, - domain: str | None, - force_policy: bool, - dry_run: bool, -) -> None: +def apply(args: argparse.Namespace) -> int: """Tell the MDM what this deployment's devices need Run it when a deployment is set up and whenever its template changes. A changed policy stops @@ -195,105 +204,66 @@ def apply( # pylint: disable=too-many-arguments,too-many-positional-arguments device that has already joined will not pick up a template applied afterwards -- it has to enrol again, under a callsign that has not been spent. """ - the_domain = _domain(ctx, domain) - window = Settings(f"https://{the_domain}/scep", "") if dry_run else _window(ctx, config.CHALLENGE, the_domain) - mdm = _mdm(ctx, SETUP, mdm_url=mdm_url, team=team, template=path) + the_domain = _domain(args) + if args.dry_run: + window = Settings(f"https://{the_domain}/scep", "") + else: + window = _window(os.environ.get("ODMDM_CHALLENGE", ""), the_domain) + mdm = _mdm(args, SETUP, complete=not args.dry_run) try: - for step in mdm.setup(window, force=force_policy, dry_run=dry_run): - click.echo(step.label if step.done else f"{step.label} (not done)") + for step in mdm.setup(window, force=args.force_policy, dry_run=args.dry_run): + print(step.label if step.done else f"{step.label} (not done)") if step.message: - click.echo(step.message) + print(step.message) except MdmError as exc: - _fail(ctx, str(exc)) - ctx.exit(0) - - -@cli_group.command(name="challenge") -@click.pass_context -@click.option( - "--challenge", - "value", - envvar="ODMDM_CHALLENGE", - default=None, - help="The new window's settings line or challenge (default: ODMDM_CHALLENGE, else asked for)", -) -@TEMPLATE -@MDM_URL -@DOMAIN -def challenge( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, value: str | None, path: str | None, mdm_url: str | None, domain: str | None -) -> None: + raise _Failed(str(exc)) from exc + return 0 + + +def challenge(args: argparse.Namespace) -> int: """Give the MDM the challenge of the enrolment window just opened Every opening makes a new one. Only the certificate authority changes, so phones still - installing apps are left alone. Asked for rather than taken as an argument, so it stays out of - shell history. Given the whole settings line, its SCEP URL must be on this deployment's domain. + installing apps are left alone. Taken from ODMDM_CHALLENGE, else asked for, never as an + argument, so it stays out of shell history and the process list. Given the whole settings line, + its SCEP URL must be on this deployment's domain. """ - the_domain = _domain(ctx, domain) - mdm = _mdm(ctx, SET_CHALLENGE, mdm_url=mdm_url, template=path) - if value is None: - value = str(click.prompt("Settings line or challenge from Deploy App's MDM page", hide_input=True)) - window = _window(ctx, value, the_domain) + the_domain = _domain(args) + mdm = _mdm(args, SET_CHALLENGE) + value = os.environ.get("ODMDM_CHALLENGE", "") + while not value.strip(): + value = getpass.getpass("Settings line or challenge from Deploy App's MDM page: ") + window = _window(value, the_domain) try: mdm.set_challenge(window) except MdmError as exc: - _fail(ctx, str(exc)) - until = f". The enrolment window is open until {window.closes:%Y-%m-%d %H:%M} UTC" if window.closes else "" - click.echo(f"{mdm.title} has the new challenge{until}") - ctx.exit(0) + raise _Failed(str(exc)) from exc + until = "" + if window.closes: + until = f". The enrolment window is open until {window.closes.astimezone(_now().tzinfo):%Y-%m-%d %H:%M}" + print(f"{mdm.title} has the new challenge{until}") + return 0 -@cli_group.command(name="phones") -@click.pass_context -@MDM_URL -@TEAM -def phones(ctx: click.Context, mdm_url: str | None, team: str | None) -> None: +def phones(args: argparse.Namespace) -> int: """List the team's phones and where each one's certificate is One line each: the id that name and resend take, the callsign, the model, the day it enrolled, and the certificate in plain words. """ - mdm = _mdm(ctx, mdm_url=mdm_url, team=team) + mdm = _mdm(args) try: found = mdm.phones() except MdmError as exc: - _fail(ctx, str(exc)) + raise _Failed(str(exc)) from exc for phone in found: - click.echo( - f"{phone.id:<5} {phone.callsign or '-':<12} {phone.model:<26} {phone.joined[:10]} {core.said(phone)}" - ) + print(f"{phone.id:<5} {phone.callsign or '-':<12} {phone.model:<26} {phone.joined[:10]} {core.said(phone)}") if not found: - click.echo("No phones in the team") - ctx.exit(0) - - -@cli_group.command(name="name") -@click.pass_context -@click.argument("pairs", nargs=-1, metavar="[ID=CALLSIGN]...") -@click.option( - "--all", - "prefix", - metavar="PREFIX", - default=None, - help="Name every phone that has no name PREFIX, in enrolment order", -) -@click.option( - "--start", - type=click.IntRange(min=1), - metavar="N", - default=None, - help="The first n for --all (default: one above the highest in use)", -) -@MDM_URL -@TEAM -def name( # pylint: disable=too-many-arguments,too-many-positional-arguments - ctx: click.Context, - pairs: tuple[str, ...], - prefix: str | None, - start: int | None, - mdm_url: str | None, - team: str | None, -) -> None: + print("No phones in the team") + return 0 + + +def name(args: argparse.Namespace) -> int: """Name phones, and have the MDM send them certificates ID=CALLSIGN for as many phones as you like, in any order, the id being what phones prints. Or @@ -308,43 +278,38 @@ def name( # pylint: disable=too-many-arguments,too-many-positional-arguments was last sent, because Fleet can overwrite a new phone's policy. So name phones once every phone in the team has its apps. """ - if bool(pairs) == bool(prefix) or (start is not None and not prefix): - raise click.UsageError("Give ID=CALLSIGN for each phone, or --all PREFIX") + if bool(args.pairs) == bool(args.prefix) or (args.start is not None and not args.prefix): + raise _Usage("Give ID=CALLSIGN for each phone, or --all PREFIX") try: - wanted = core.pairs(pairs) + wanted = core.pairs(args.pairs) except ValueError as exc: - raise click.UsageError(str(exc)) from exc - mdm = _mdm(ctx, mdm_url=mdm_url, team=team) + raise _Usage(str(exc)) from exc + mdm = _mdm(args) try: found = mdm.phones() - if prefix: - wanted = core.numbered(found, prefix, start) + if args.prefix: + wanted = core.numbered(found, args.prefix, args.start) refused = core.refusal(found, wanted) if refused: - _fail(ctx, f"Nothing named: {refused}") + raise _Failed(f"Nothing named: {refused}") if not wanted: - click.echo("Nothing to name") - ctx.exit(0) + print("Nothing to name") + return 0 lines = mdm.name(dict(wanted)) except MdmError as exc: for line in exc.lines: - click.echo(line) - click.echo(str(exc), err=True) + print(line) + print(exc, file=sys.stderr) if exc.named: done = " ".join(f"{phone}={callsign}" for phone, callsign in exc.named.items()) - click.echo(f"Already named before it stopped: {done}. phones shows where each is", err=True) - ctx.exit(1) + print(f"Already named before it stopped: {done}. phones shows where each is", file=sys.stderr) + return 1 for line in lines: - click.echo(line) - ctx.exit(0) + print(line) + return 0 -@cli_group.command(name="resend") -@click.pass_context -@click.argument("ids", nargs=-1) -@MDM_URL -@TEAM -def resend(ctx: click.Context, ids: tuple[str, ...], mdm_url: str | None, team: str | None) -> None: +def resend(args: argparse.Namespace) -> int: """Have phones ask for their certificates again For a refused phone once the cause is fixed, such as enrolment opened again and its new @@ -357,23 +322,21 @@ def resend(ctx: click.Context, ids: tuple[str, ...], mdm_url: str | None, team: name it holds and is refused, and reads as refused from then on though that certificate still works. As with name, the team's policy is sent again if a phone enrolled after it was last sent. """ - mdm = _mdm(ctx, ASK_AGAIN, mdm_url=mdm_url, team=team) + mdm = _mdm(args, ASK_AGAIN) try: - lines = mdm.ask_again(list(ids)) + lines = mdm.ask_again(list(args.ids)) except MdmError as exc: for line in exc.lines: - click.echo(line) - _fail(ctx, str(exc)) + print(line) + raise _Failed(str(exc)) from exc for line in lines: - click.echo(line) + print(line) if not lines: - click.echo("Nothing to resend") - ctx.exit(0) + print("Nothing to resend") + return 0 -@cli_group.command(name="mdms") -@click.pass_context -def mdms(ctx: click.Context) -> None: +def mdms(args: argparse.Namespace) -> int: """List the MDMs installed: the name --mdm takes, the package and its version, built in or a plugin Lists them without loading any. A plugin is code that sees the MDM token: install only one you trust. @@ -381,8 +344,134 @@ def mdms(ctx: click.Context) -> None: try: found = plugins.installed() except plugins.PluginError as exc: - _fail(ctx, str(exc)) + raise _Failed(str(exc)) from exc for plugin in found: kind = "built in" if plugin.built_in else "plugin" - click.echo(f"{plugin.name:<12} {plugin.package:<28} {plugin.version:<16} {kind}") - ctx.exit(0) + print(f"{plugin.name:<12} {plugin.package:<28} {plugin.version:<16} {kind}") + return 0 + + +def page(args: argparse.Namespace) -> int: + """Serve the connector as a page that only this computer can open, until Ctrl+C + + Open the address it prints: it holds a key that the page needs. It opens no browser itself. + """ + started = App.default() + try: + try: + server = web.Page(started, args.port) + except OSError as exc: + # Deploy App's button reaches the default port only, so another port is not the first advice there + advice = ( + "The connector may be running already: use its page. Another port, given with --port, works " + "for a pasted settings line only, as Deploy App's button reaches this port." + if args.port == web.PORT + else "Give another with --port." + ) + raise _Failed( + f"The page cannot listen on port {args.port} of this computer: {exc.strerror}. {advice}" + ) from exc + print(f"Open this address in your browser: {server.address}") + print("Press Ctrl+C to stop it.", flush=True) + with server: + try: + server.serve_forever() + except KeyboardInterrupt: + if started.busy(): + print(STOPPED_BUSY, file=sys.stderr) + finally: + started.close() + return 0 + + +def _between(low: int, high: int | None = None) -> Callable[[str], int]: + """An argparse type: a whole number from low, up to high when given""" + + def number(value: str) -> int: + try: + given = int(value) + except ValueError: + given = low - 1 + if given < low or (high is not None and given > high): + upto = f" to {high}" if high is not None else " up" + raise argparse.ArgumentTypeError(f"{value} is not a whole number from {low}{upto}") + return given + + return number + + +#: The options more than one command takes, with their help +SHARED = { + "--mdm-url": "The MDM's address, as --set mdm_url (default: ODMDM_MDM_URL)", + "--team": "The team the phones are in, as --set team (default: ODMDM_TEAM)", + "--template": "What to install, as --set template (default: ODMDM_TEMPLATE)", + "--domain": "The deployment's DNS name (default: ODMDM_DOMAIN)", +} + + +def _parser() -> argparse.ArgumentParser: + """The command line, its defaults read from the environment now""" + parser = argparse.ArgumentParser( + prog="odmdm-connector", + description="Connect an MDM, Fleet built in, to an OpenDefence deployment's device enrolment", + ) + parser.add_argument("--version", action="version", version=f"%(prog)s, version {__version__}") + parser.add_argument("-v", "--verbose", action="count", default=0, help="Shorthand for info/debug loglevel (-v/-vv)") + parser.add_argument( + "--mdm", + dest="chosen", + default=os.environ.get("ODMDM_MDM", "fleet"), + metavar="NAME", + help="The MDM to talk to (default: ODMDM_MDM, else fleet)", + ) + parser.add_argument( + "--set", + dest="given", + action="append", + default=[], + metavar="KEY=VALUE", + help="A setting of the MDM, such as mdm_url; never a secret, which is read from the file ODMDM__FILE names", + ) + commands = parser.add_subparsers(title="commands", metavar="COMMAND", required=True) + + def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) -> argparse.ArgumentParser: + doc = inspect.cleandoc(run.__doc__ or "") + sub = commands.add_parser( + called, + help=doc.splitlines()[0], + description=doc, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + sub.set_defaults(run=run, parser=sub) + for option in shared: + sub.add_argument(option, default=None, help=SHARED[option]) + return sub + + sub = command("apply", apply, "--template", "--mdm-url", "--team", "--domain") + sub.add_argument( + "--force-policy", + action="store_true", + help="Re-upload the policy even if unchanged, to reach a host that just joined", + ) + sub.add_argument("--dry-run", action="store_true", help="Read and validate the template, then stop") + command("challenge", challenge, "--template", "--mdm-url", "--domain") + command("phones", phones, "--mdm-url", "--team") + sub = command("name", name, "--mdm-url", "--team") + sub.add_argument("pairs", nargs="*", metavar="ID=CALLSIGN") + sub.add_argument( + "--all", dest="prefix", metavar="PREFIX", help="Name every phone that has no name PREFIX, in enrolment order" + ) + sub.add_argument( + "--start", + type=_between(1), + metavar="N", + help="The first n for --all (default: one above the highest in use)", + ) + sub = command("resend", resend, "--mdm-url", "--team") + sub.add_argument("ids", nargs="*", metavar="ID") + command("mdms", mdms) + sub = command("web", page) + sub.add_argument( + "--port", type=_between(1, 65535), default=web.PORT, help="The port on 127.0.0.1 (default: %(default)s)" + ) + return parser diff --git a/tests/test_console.py b/tests/test_console.py index 62f2f43..eb8bece 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -4,21 +4,64 @@ to say why, rather than end in a traceback. """ +import codecs import datetime +import getpass import json +import logging +import runpy +import sys +from dataclasses import dataclass from importlib.metadata import EntryPoint from pathlib import Path -import httpx import pytest -from click.testing import CliRunner -from odmdm_connector import config, console, plugins +from odmdm_connector import __version__, console, plugins from odmdm_connector import fleet as fleet_module -from odmdm_connector.console import cli_group from odmdm_connector.fleet_plugin import FleetPlugin -from .test_fleet import _Fleet, _host, _mdm +from .test_fleet import Request, Response, _Fleet, _host, _mdm + + +@dataclass +class Ran: + """What a run of the command line ended with and printed""" + + exit_code: int + stdout: str + stderr: str + + @property + def output(self) -> str: + return self.stdout + self.stderr + + +class Run: + """console.main on a list of arguments, what is typed at its prompt and extra environment""" + + def __init__(self, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> None: + self.capsys = capsys + self.monkeypatch = monkeypatch + + def __call__(self, arguments: list[str], typed: str | None = None, env: dict[str, str] | None = None) -> Ran: + for key, value in (env or {}).items(): + self.monkeypatch.setenv(key, value) + if typed is not None: + self.monkeypatch.setattr(getpass, "getpass", lambda prompt: typed) + self.capsys.readouterr() + try: + code = console.main(arguments) + except SystemExit as exc: + code = int(exc.code or 0) + out, err = self.capsys.readouterr() + return Ran(code, out, err) + + +@pytest.fixture +def run(capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch) -> Run: + return Run(capsys, monkeypatch) + #: The certificate subject the template loader accepts: the callsign the operator gave the phone NAMED = "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART" @@ -36,6 +79,7 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: monkeypatch.setenv("ODMDM_TOKEN_FILE", str(token)) monkeypatch.setenv("ODMDM_TEAM", "rmscep") stub = _Fleet() + stub.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep"}] stub.certificates = [{"id": 81, "name": "rmscep", "subject_name": NAMED, "certificate_authority_id": 3}] stub.profiles = [ { @@ -50,15 +94,15 @@ def fleet(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: return stub -@pytest.mark.parametrize("command", [["apply"], ["challenge", "--challenge", "new-window"]]) -def test_a_domain_is_required(command: list[str], monkeypatch: pytest.MonkeyPatch) -> None: +@pytest.mark.parametrize("command", [["apply"], ["challenge"]]) +def test_a_domain_is_required(command: list[str], monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """Without it there is nothing to state to Fleet; the template defaults to the one shipped""" - monkeypatch.setattr(config, "DOMAIN", "") + monkeypatch.delenv("ODMDM_DOMAIN", raising=False) - result = CliRunner().invoke(cli_group, command) + result = run(command, env={"ODMDM_CHALLENGE": "new-window"}) assert result.exit_code == 1 - assert "ODMDM_DOMAIN" in result.output + assert "ODMDM_DOMAIN" in result.stderr def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -74,15 +118,15 @@ def _template(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: encoding="utf-8", ) monkeypatch.setenv("ODMDM_TEMPLATE", str(path)) - monkeypatch.setattr(config, "DOMAIN", "example.fi") + monkeypatch.setenv("ODMDM_DOMAIN", "example.fi") -def test_apply_states_the_template(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_apply_states_the_template(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """One team: phones enrol into the team that has the certificate template""" _template(tmp_path, monkeypatch) - monkeypatch.setattr(config, "CHALLENGE", "new-window") + monkeypatch.setenv("ODMDM_CHALLENGE", "new-window") - result = CliRunner().invoke(cli_group, ["apply"]) + result = run(["apply"]) assert result.exit_code == 0, result.output assert "Applied to team 7" in result.output @@ -90,23 +134,25 @@ def test_apply_states_the_template(fleet: _Fleet, tmp_path: Path, monkeypatch: p assert fleet.authorities[0]["url"] == "https://example.fi/scep" -def test_a_dry_run_never_reaches_fleet(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_dry_run_never_reaches_fleet( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """Checking an edited template must not change the estate""" _template(tmp_path, monkeypatch) - result = CliRunner().invoke(cli_group, ["apply", "--dry-run"]) + result = run(["apply", "--dry-run"]) assert result.exit_code == 0, result.output assert not fleet.calls def test_a_new_window_touches_only_the_authority( - fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run ) -> None: """A rewritten policy stops apps installing on phones enrolling right now""" _template(tmp_path, monkeypatch) - result = CliRunner().invoke(cli_group, ["challenge"], input="new-window\n") + result = run(["challenge"], typed="new-window") assert result.exit_code == 0, result.output assert "new-window" not in result.output, "asked for without echoing it" @@ -115,14 +161,14 @@ def test_a_new_window_touches_only_the_authority( assert changed == {"/api/latest/fleet/certificate_authorities/3"} -def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: +def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """No Fleet configured is a sentence, not a traceback""" monkeypatch.delenv("ODMDM_MDM_URL", raising=False) - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 1 - assert "ODMDM_MDM_URL" in result.output + assert "Fleet address is missing: give --set mdm_url=... or set ODMDM_MDM_URL" in result.stderr NO_NAME = ( @@ -137,23 +183,12 @@ def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: ("status", "detail", "says"), [ ("", "", "no certificate requested"), - ("failed", NO_NAME, "named, but its certificate was not asked for again: run resend"), - ("pending", "", "requested, waiting for the phone: up to 15 minutes"), - ("delivering", "", "requested, waiting for the phone: up to 15 minutes"), - ("delivered", "", "requested, waiting for the phone: up to 15 minutes"), - ( - "pending", - REFUSED, - ( - "requested, waiting for the phone: up to 15 minutes; last time: refused by Deploy App: " - "name taken or not allowed, enrolment closed, or Fleet has an old challenge" - ), - ), - ( - "delivered", - UNREACHED, - "requested, waiting for the phone: up to 15 minutes; last time: could not reach Deploy App", - ), + ("failed", NO_NAME, "named, but its certificate was not asked for again: ask again"), + ("pending", "", "requested, waiting for the phone"), + ("delivering", "", "requested, waiting for the phone"), + ("delivered", "", "requested, waiting for the phone"), + ("pending", REFUSED, "requested, waiting for the phone"), + ("delivered", UNREACHED, "requested, waiting for the phone"), ("verified", "", "has its certificate"), ( "failed", @@ -169,29 +204,29 @@ def test_phones_needs_somewhere_to_ask(monkeypatch: pytest.MonkeyPatch) -> None: ), ], ) -def test_phones_says_where_each_certificate_is(fleet: _Fleet, status: str, detail: str, says: str) -> None: +def test_phones_says_where_each_certificate_is(fleet: _Fleet, status: str, detail: str, says: str, run: Run) -> None: """In words an operator can act on, rather than Fleet's status and detail""" fleet.hosts = [_host(31, status, "OTTER4", detail)] - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 0, result.output assert result.output.split()[:4] == ["31", "OTTER4", "Google", "sdk_gphone64_arm64"] assert result.output.rstrip("\n").split("2026-11-01 ", 1)[1] == says -def test_a_phone_fresh_from_enrolment_waits_for_a_name(fleet: _Fleet) -> None: +def test_a_phone_fresh_from_enrolment_waits_for_a_name(fleet: _Fleet, run: Run) -> None: """Its first request fails for want of one""" fleet.hosts = [_host(31, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 0, result.output assert result.output.split()[:2] == ["31", "-"] assert result.output.rstrip().endswith("waiting for a name") -def test_phones_lists_in_enrolment_order_with_the_callsign_fleet_issues(fleet: _Fleet) -> None: +def test_phones_lists_in_enrolment_order_with_the_callsign_fleet_issues(fleet: _Fleet, run: Run) -> None: """The certificate carries the name up to its "@"; an old remove row is history, not state""" fleet.hosts = [ _host(32, "verified", "OTTER1@CODE", enrolled="2026-11-02T08:00:00Z"), @@ -201,7 +236,7 @@ def test_phones_lists_in_enrolment_order_with_the_callsign_fleet_issues(fleet: _ 0, {"name": "rmscep", "status": "failed", "operation_type": "remove", "detail": REFUSED} ) - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 0, result.output lines = result.output.splitlines() @@ -210,9 +245,9 @@ def test_phones_lists_in_enrolment_order_with_the_callsign_fleet_issues(fleet: _ assert lines[1].endswith("has its certificate") -def test_an_empty_team_says_so(fleet: _Fleet) -> None: +def test_an_empty_team_says_so(fleet: _Fleet, run: Run) -> None: """Rather than printing nothing, which reads as a failure""" - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 0, result.output assert "No phones in the team" in result.output @@ -226,14 +261,14 @@ def _changes(fleet: _Fleet) -> list[tuple[str, str]]: return [(method, path.removeprefix("/api/latest/fleet")) for method, path in fleet.calls if method != "GET"] -def test_name_gives_any_number_of_phones_their_callsigns(fleet: _Fleet) -> None: +def test_name_gives_any_number_of_phones_their_callsigns(fleet: _Fleet, run: Run) -> None: """In any order, each named and then asked for its certificate again under the name""" fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] - result = CliRunner().invoke(cli_group, ["name", "33=OTTER5", "31=OTTER4"]) + result = run(["name", "33=OTTER5", "31=OTTER4"]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == ["Host 33 is OTTER5", "Host 31 is OTTER4"] + assert result.output.splitlines() == ["Phone 33 is OTTER5", "Phone 31 is OTTER4"] assert _named(fleet) == {31: "OTTER4", 32: "", 33: "OTTER5"} assert _changes(fleet) == [ ("PUT", "/hosts/33/device_mapping"), @@ -243,40 +278,40 @@ def test_name_gives_any_number_of_phones_their_callsigns(fleet: _Fleet) -> None: ] -def test_a_request_still_pending_takes_the_name_without_a_resend(fleet: _Fleet) -> None: +def test_a_request_still_pending_takes_the_name_without_a_resend(fleet: _Fleet, run: Run) -> None: """Fleet refuses to resend it, and it needs none: it is filled in when it goes""" fleet.hosts = [_host(31, "pending")] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == ["Host 31 is OTTER4"] + assert result.output.splitlines() == ["Phone 31 is OTTER4"] assert _named(fleet) == {31: "OTTER4"} -def test_a_phone_with_its_certificate_under_the_name_is_left_alone(fleet: _Fleet) -> None: +def test_a_phone_with_its_certificate_under_the_name_is_left_alone(fleet: _Fleet, run: Run) -> None: """Asked again under the name it holds, it is refused as taken and then reads as refused""" fleet.hosts = [_host(31, "verified", "OTTER4@CODE"), _host(32, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, ["name", "31=otter4", "32=OTTER5"]) + result = run(["name", "31=otter4", "32=OTTER5"]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == ["Host 31 is already OTTER4", "Host 32 is OTTER5"] + assert result.output.splitlines() == ["Phone 31 is already OTTER4", "Phone 32 is OTTER5"] assert _changes(fleet) == [("PUT", "/hosts/32/device_mapping"), ("POST", "/hosts/32/certificates/81/resend")] assert _named(fleet)[31] == "OTTER4@CODE" -def test_a_phone_with_no_request_is_named_and_the_batch_goes_on(fleet: _Fleet) -> None: +def test_a_phone_with_no_request_is_named_and_the_batch_goes_on(fleet: _Fleet, run: Run) -> None: """Fleet has no request to send it again, and fills the name in when it makes one""" fleet.hosts = [_host(31, "failed", detail=NO_NAME), _host(32), _host(33, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER"]) + result = run(["name", "--all", "OTTER"]) assert result.exit_code == 0, result.output assert result.output.splitlines() == [ - "Host 31 is OTTER1", - "Host 32 is OTTER2. Fleet has no certificate request for it, so nothing was sent", - "Host 33 is OTTER3", + "Phone 31 is OTTER1", + "Phone 32 is OTTER2. Fleet has no certificate request for it, so nothing was sent", + "Phone 33 is OTTER3", ] assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: "OTTER3"} assert ("POST", "/hosts/32/certificates/81/resend") not in _changes(fleet) @@ -291,7 +326,7 @@ def test_a_phone_with_no_request_is_named_and_the_batch_goes_on(fleet: _Fleet) - ], ) def test_name_all_numbers_the_phones_without_a_name( - fleet: _Fleet, first: str, start: list[str], expected: dict[int, str] + fleet: _Fleet, first: str, start: list[str], expected: dict[int, str], run: Run ) -> None: """In enrolment order, then host id, from one above the highest number in use unless told""" fleet.hosts = [ @@ -301,18 +336,18 @@ def test_name_all_numbers_the_phones_without_a_name( _host(42, "failed", detail=NO_NAME, enrolled="2026-11-02T08:00:00Z"), ] - result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER", *start]) + result = run(["name", "--all", "OTTER", *start]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == [f"Host {host} is {callsign}" for host, callsign in expected.items()] + assert result.output.splitlines() == [f"Phone {host} is {callsign}" for host, callsign in expected.items()] assert _named(fleet) == {40: first, **expected} -def test_name_all_with_every_phone_named_names_nothing(fleet: _Fleet) -> None: +def test_name_all_with_every_phone_named_names_nothing(fleet: _Fleet, run: Run) -> None: """A second run finds nobody waiting, and changes nothing""" fleet.hosts = [_host(31, "verified", "OTTER1")] - result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER"]) + result = run(["name", "--all", "OTTER"]) assert result.exit_code == 0, result.output assert "Nothing to name" in result.output @@ -332,7 +367,9 @@ def test_name_all_with_every_phone_named_names_nothing(fleet: _Fleet) -> None: (["31=OTTER4", "99=OTTER5"], "phone 99 is not in the group"), ], ) -def test_name_changes_nothing_unless_every_name_can_be_given(fleet: _Fleet, arguments: list[str], says: str) -> None: +def test_name_changes_nothing_unless_every_name_can_be_given( + fleet: _Fleet, arguments: list[str], says: str, run: Run +) -> None: """A typo refuses the whole command, rather than leaving half a batch named""" fleet.hosts = [ _host(31, "failed", detail=NO_NAME), @@ -340,57 +377,57 @@ def test_name_changes_nothing_unless_every_name_can_be_given(fleet: _Fleet, argu _host(33, "verified", "OTTER9@CODE"), ] - result = CliRunner().invoke(cli_group, ["name", *arguments]) + result = run(["name", *arguments]) assert result.exit_code == 1 - assert f"Nothing named: {says}" in result.output + assert f"Nothing named: {says}" in result.stderr assert not _changes(fleet) @pytest.mark.parametrize("arguments", [[], ["31=OTTER4", "--all", "OTTER"], ["31=OTTER4", "--start", "3"], ["OTTER4"]]) -def test_name_says_how_it_is_used(fleet: _Fleet, arguments: list[str]) -> None: +def test_name_says_how_it_is_used(fleet: _Fleet, arguments: list[str], run: Run) -> None: """Before Fleet is asked anything""" - result = CliRunner().invoke(cli_group, ["name", *arguments]) + result = run(["name", *arguments]) assert result.exit_code == 2 assert not fleet.calls -def test_renaming_a_phone_with_its_certificate_says_what_to_revoke(fleet: _Fleet) -> None: +def test_renaming_a_phone_with_its_certificate_says_what_to_revoke(fleet: _Fleet, run: Run) -> None: """The old callsign stays valid in Deploy App until an admin revokes it there""" fleet.hosts = [_host(31, "verified", "OTTER3")] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 0, result.output assert result.output.splitlines() == [ - "Host 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." + "Phone 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." ] -def test_renaming_a_refused_phone_says_nothing_to_revoke(fleet: _Fleet) -> None: +def test_renaming_a_refused_phone_says_nothing_to_revoke(fleet: _Fleet, run: Run) -> None: """A refused name was never issued to this phone, and may be another phone's""" fleet.hosts = [_host(31, "failed", "OTTER3", REFUSED)] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == ["Host 31 is OTTER4"] + assert result.output.splitlines() == ["Phone 31 is OTTER4"] -def test_name_without_a_certificate_template_says_so(fleet: _Fleet) -> None: +def test_name_without_a_certificate_template_says_so(fleet: _Fleet, run: Run) -> None: """Before a phone is named, so nothing is left half done""" fleet.certificates = [] fleet.hosts = [_host(31, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 1 - assert "no certificate template named rmscep: run apply first" in result.output + assert "no certificate template named rmscep: set Fleet up first" in result.stderr assert not _changes(fleet) -def test_resend_asks_again_for_every_named_phone_that_failed(fleet: _Fleet) -> None: +def test_resend_asks_again_for_every_named_phone_that_failed(fleet: _Fleet, run: Run) -> None: """A phone named in Fleet by hand is one of them: naming alone does not send the request again""" fleet.hosts = [ _host(31, "failed", "OTTER4", REFUSED), @@ -400,12 +437,12 @@ def test_resend_asks_again_for_every_named_phone_that_failed(fleet: _Fleet) -> N _host(35, "pending", "OTTER7"), ] - result = CliRunner().invoke(cli_group, ["resend"]) + result = run(["resend"]) assert result.exit_code == 0, result.output assert result.output.splitlines() == [ - "Host 31 (OTTER4): certificate asked for again", - "Host 34 (OTTER6): certificate asked for again", + "Phone 31 (OTTER4): certificate asked for again", + "Phone 34 (OTTER6): certificate asked for again", ] assert _changes(fleet) == [ ("POST", "/hosts/31/certificates/81/resend"), @@ -413,23 +450,23 @@ def test_resend_asks_again_for_every_named_phone_that_failed(fleet: _Fleet) -> N ] -def test_resend_given_hosts_asks_for_those(fleet: _Fleet) -> None: +def test_resend_given_hosts_asks_for_those(fleet: _Fleet, run: Run) -> None: """Whatever state they are in: the operator chose them""" fleet.hosts = [_host(31, "failed", "OTTER4", REFUSED), _host(32, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, ["resend", "32"]) + result = run(["resend", "32"]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == ["Host 32 (no name): certificate asked for again"] + assert result.output.splitlines() == ["Phone 32 (no name): certificate asked for again"] assert _changes(fleet) == [("POST", "/hosts/32/certificates/81/resend")] @pytest.mark.parametrize(("arguments", "says", "code"), [([], "Nothing to resend", 0), (["99"], "not in the team", 1)]) -def test_resend_says_when_it_sends_nothing(fleet: _Fleet, arguments: list[str], says: str, code: int) -> None: +def test_resend_says_when_it_sends_nothing(fleet: _Fleet, arguments: list[str], says: str, code: int, run: Run) -> None: """Nobody failed, or a host that is not in the team: said, and nothing sent""" fleet.hosts = [_host(31, "verified", "OTTER4")] - result = CliRunner().invoke(cli_group, ["resend", *arguments]) + result = run(["resend", *arguments]) assert result.exit_code == code, result.output assert says in result.output @@ -444,7 +481,7 @@ def _policy_changes(fleet: _Fleet) -> list[tuple[str, str]]: return [change for change in _changes(fleet) if "/configuration_profiles" in change[1]] -def test_name_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet) -> None: +def test_name_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet, run: Run) -> None: """Fleet can write a bare policy over a new phone's, and never sends ours again by itself Measured: the certificate installs, Chrome is not allowed to use it, and Deploy App says @@ -456,32 +493,32 @@ def test_name_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Flee _host(33, "verified", "OTTER1"), ] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 0, result.output assert result.stdout.splitlines() == [ - "Host 31 is OTTER4", + "Phone 31 is OTTER4", "Policy sent again: 2 phones enrolled after it was last sent", ] assert _policy_changes(fleet) == [("DELETE", "/configuration_profiles/g4bb"), ("POST", "/configuration_profiles")] assert [profile["raw"] for profile in fleet.profiles] == [{"defaultPermissionPolicy": "GRANT"}] -def test_resend_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet) -> None: +def test_resend_sends_the_policy_again_when_a_phone_enrolled_after_it(fleet: _Fleet, run: Run) -> None: """The phone asked again may be one whose policy Fleet overwrote""" fleet.hosts = [_host(31, "failed", "OTTER4", REFUSED, enrolled=LATER), _host(32, "verified", "OTTER5")] - result = CliRunner().invoke(cli_group, ["resend"]) + result = run(["resend"]) assert result.exit_code == 0, result.output assert result.stdout.splitlines() == [ - "Host 31 (OTTER4): certificate asked for again", + "Phone 31 (OTTER4): certificate asked for again", "Policy sent again: 1 phone enrolled after it was last sent", ] assert _policy_changes(fleet) == [("DELETE", "/configuration_profiles/g4bb"), ("POST", "/configuration_profiles")] -def test_a_policy_sent_again_is_then_left_alone(fleet: _Fleet) -> None: +def test_a_policy_sent_again_is_then_left_alone(fleet: _Fleet, run: Run) -> None: """Fleet stamps an upload with its own clock, so the policy is newer than every phone already there Sent on every run, it would be rewritten under phones still installing their apps. @@ -492,201 +529,213 @@ def test_a_policy_sent_again_is_then_left_alone(fleet: _Fleet) -> None: _host(32, "failed", detail=NO_NAME, enrolled=LATER), ] - first = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + first = run(["name", "31=OTTER4"]) fleet.calls.clear() - second = CliRunner().invoke(cli_group, ["name", "32=OTTER5"]) + second = run(["name", "32=OTTER5"]) assert first.stdout.splitlines()[-1] == "Policy sent again: 2 phones enrolled after it was last sent" assert second.exit_code == 0, second.output - assert second.stdout.splitlines() == ["Host 32 is OTTER5"] + assert second.stdout.splitlines() == ["Phone 32 is OTTER5"] assert not _policy_changes(fleet) @pytest.mark.parametrize(("policy", "enrolled"), [(True, "2026-11-01T19:38:12Z"), (False, LATER)]) -def test_the_policy_is_left_alone_unless_a_phone_enrolled_after_it(fleet: _Fleet, policy: bool, enrolled: str) -> None: +def test_the_policy_is_left_alone_unless_a_phone_enrolled_after_it( + fleet: _Fleet, policy: bool, enrolled: str, run: Run +) -> None: """Every phone enrolled before it was last sent, or the team has no policy to send""" if not policy: fleet.profiles = [] fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=enrolled)] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 0, result.output - assert result.output.splitlines() == ["Host 31 is OTTER4"] + assert result.output.splitlines() == ["Phone 31 is OTTER4"] assert _changes(fleet) == [("PUT", "/hosts/31/device_mapping"), ("POST", "/hosts/31/certificates/81/resend")] @pytest.mark.parametrize( ("command", "said"), [ - (["name", "31=OTTER4"], "Host 31 is already OTTER4"), + (["name", "31=OTTER4"], "Phone 31 is already OTTER4"), (["name", "--all", "OTTER"], "Nothing to name"), (["resend"], "Nothing to resend"), ], ) def test_the_policy_is_sent_again_only_after_a_phone_is_named_or_asked_again( - fleet: _Fleet, command: list[str], said: str + fleet: _Fleet, command: list[str], said: str, run: Run ) -> None: """A run that changed nothing leaves the policy alone, as it would a phone still installing apps""" fleet.hosts = [_host(31, "verified", "OTTER4", enrolled=LATER)] - result = CliRunner().invoke(cli_group, command) + result = run(command) assert result.exit_code == 0, result.output assert result.output.splitlines() == [said] assert not _changes(fleet) -def test_a_policy_fleet_refuses_is_said_after_the_names(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_policy_fleet_refuses_is_said_after_the_names( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """The phones are named all the same, and the refusal is said as any other""" answer = fleet.handler - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.url.params.get("alt") == "media": - return httpx.Response(500, text="database is locked") + return Response(500, text="database is locked") return answer(request) monkeypatch.setattr(fleet, "handler", refusing) _mdm(fleet, monkeypatch) fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=LATER)] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 1 - assert result.output.splitlines()[0] == "Host 31 is OTTER4" - assert "Fleet refused: GET /api/latest/fleet/configuration_profiles/g4bb?alt=media answered 500" in result.output + assert result.output.splitlines()[0] == "Phone 31 is OTTER4" + assert "Fleet refused: GET /api/latest/fleet/configuration_profiles/g4bb?alt=media answered 500" in result.stderr assert _named(fleet) == {31: "OTTER4"} assert not _policy_changes(fleet) -def test_a_policy_lost_between_delete_and_upload_is_said(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_policy_lost_between_delete_and_upload_is_said( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """The team then has no policy, every phone in it loses the settings, and a later run sees nothing""" answer = fleet.handler - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.method == "POST" and request.url.path.endswith("/configuration_profiles"): - return httpx.Response(502, text="Bad Gateway") + return Response(502, text="Bad Gateway") return answer(request) monkeypatch.setattr(fleet, "handler", refusing) _mdm(fleet, monkeypatch) fleet.hosts = [_host(31, "failed", detail=NO_NAME, enrolled=LATER)] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4"]) + result = run(["name", "31=OTTER4"]) assert result.exit_code == 1 - assert result.output.splitlines()[0] == "Host 31 is OTTER4" - assert "may now be missing" in result.output - assert "Run apply to put it back" in result.output + assert result.output.splitlines()[0] == "Phone 31 is OTTER4" + assert "may now be missing" in result.stderr + assert "Run apply to put it back" in result.stderr assert not fleet.profiles @pytest.mark.parametrize("command", [["phones"], ["name", "31=OTTER4"], ["resend"]]) -def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str]) -> None: +def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str], run: Run) -> None: """A typo must not leave an empty team behind for the next phone to enrol into""" fleet.hosts = [_host(31, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, [*command, "--team", "Typo"]) + result = run([*command, "--team", "Typo"]) assert result.exit_code == 1 - assert "no team named Typo" in result.output + assert "no team named Typo" in result.stderr assert not _changes(fleet) -def test_the_mdm_address_must_be_https(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_the_mdm_address_must_be_https(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """The token goes with every request, so it must not cross the network readable""" monkeypatch.setenv("ODMDM_MDM_URL", "http://mdm.test") - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 1 - assert "must start with https://" in result.output + assert "must start with https://" in result.stderr assert not fleet.calls @pytest.mark.parametrize("start", ["0", "-3"]) -def test_name_all_starts_from_one_or_more(fleet: _Fleet, start: str) -> None: +def test_name_all_starts_from_one_or_more(fleet: _Fleet, start: str, run: Run) -> None: """Callsigns are numbered from 1""" - result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER", "--start", start]) + result = run(["name", "--all", "OTTER", "--start", start]) assert result.exit_code == 2 assert not fleet.calls @pytest.mark.parametrize("count", [4, 5]) -def test_phones_reads_every_page_of_hosts(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, count: int) -> None: +def test_phones_reads_every_page_of_hosts(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, count: int, run: Run) -> None: """A team bigger than one page is listed whole, also when the last page is full""" monkeypatch.setattr(fleet_module, "HOSTS_PER_PAGE", 2) fleet.hosts = [_host(31 + n, "verified", f"OTTER{n + 1}") for n in range(count)] - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 0, result.output assert [line.split()[0] for line in result.output.splitlines()] == [str(31 + n) for n in range(count)] -def test_a_batch_stopped_half_way_says_which_phones_are_named(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_batch_stopped_half_way_says_which_phones_are_named( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """So the operator names only the rest, rather than guessing""" answer = fleet.handler - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.url.path.endswith("/hosts/32/certificates/81/resend"): - return httpx.Response(500, text="database is locked") + return Response(500, text="database is locked") return answer(request) monkeypatch.setattr(fleet, "handler", refusing) _mdm(fleet, monkeypatch) fleet.hosts = [_host(host, "failed", detail=NO_NAME) for host in (31, 32, 33)] - result = CliRunner().invoke(cli_group, ["name", "--all", "OTTER"]) + result = run(["name", "--all", "OTTER"]) assert result.exit_code == 1 - assert result.stdout.splitlines() == ["Host 31 is OTTER1"] - assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.output - assert "Already named before it stopped: 31=OTTER1 32=OTTER2. phones shows where each is" in result.output + assert result.stdout.splitlines() == ["Phone 31 is OTTER1"] + assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.stderr + assert "Already named before it stopped: 31=OTTER1 32=OTTER2. phones shows where each is" in result.stderr assert _named(fleet) == {31: "OTTER1", 32: "OTTER2", 33: ""} -def test_a_rename_stopped_half_way_still_says_what_to_revoke(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_rename_stopped_half_way_still_says_what_to_revoke( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """Nothing shows the old callsign afterwards, so its line must not be lost with the error""" answer = fleet.handler - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.url.path.endswith("/hosts/32/certificates/81/resend"): - return httpx.Response(500, text="database is locked") + return Response(500, text="database is locked") return answer(request) monkeypatch.setattr(fleet, "handler", refusing) _mdm(fleet, monkeypatch) fleet.hosts = [_host(31, "verified", "OTTER3"), _host(32, "failed", detail=NO_NAME)] - result = CliRunner().invoke(cli_group, ["name", "31=OTTER4", "32=OTTER5"]) + result = run(["name", "31=OTTER4", "32=OTTER5"]) assert result.exit_code == 1 assert result.stdout.splitlines() == [ - "Host 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." + "Phone 31 is OTTER4. It was OTTER3 and still has that certificate: revoke OTTER3 in Deploy App." ] - assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.output + assert "Fleet refused: POST /api/latest/fleet/hosts/32/certificates/81/resend answered 500" in result.stderr -def test_a_resend_stopped_half_way_says_what_was_asked(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_resend_stopped_half_way_says_what_was_asked( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """The phones asked before the error are said as on success""" answer = fleet.handler - def refusing(request: httpx.Request) -> httpx.Response: + def refusing(request: Request) -> Response: if request.url.path.endswith("/hosts/34/certificates/81/resend"): - return httpx.Response(500, text="database is locked") + return Response(500, text="database is locked") return answer(request) monkeypatch.setattr(fleet, "handler", refusing) _mdm(fleet, monkeypatch) fleet.hosts = [_host(31, "failed", "OTTER31", REFUSED), _host(34, "failed", "OTTER34", REFUSED)] - result = CliRunner().invoke(cli_group, ["resend"]) + result = run(["resend"]) assert result.exit_code == 1 - assert result.stdout.splitlines() == ["Host 31 (OTTER31): certificate asked for again"] - assert "Fleet refused: POST /api/latest/fleet/hosts/34/certificates/81/resend answered 500" in result.output + assert result.stdout.splitlines() == ["Phone 31 (OTTER31): certificate asked for again"] + assert "Fleet refused: POST /api/latest/fleet/hosts/34/certificates/81/resend answered 500" in result.stderr LINE = (Path(__file__).parent / "data" / "settings-line-v1.txt").read_text(encoding="utf-8").strip() @@ -697,28 +746,33 @@ def refusing(request: httpx.Request) -> httpx.Response: def window(fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> _Fleet: """The stub Fleet, a template, the vector's domain, and a clock before its window closes""" _template(tmp_path, monkeypatch) - monkeypatch.setattr(config, "DOMAIN", "unit.example.fi") + monkeypatch.setenv("ODMDM_DOMAIN", "unit.example.fi") monkeypatch.setattr(console, "_now", lambda: datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC)) + fleet.authorities[0]["url"] = "https://unit.example.fi/scep" return fleet @pytest.mark.parametrize( ("arguments", "typed", "env"), [ - ([], LINE + "\n", {}), - (["--challenge", LINE], None, {}), + ([], LINE, {}), ([], None, {"ODMDM_CHALLENGE": LINE}), ], ) def test_challenge_takes_the_settings_line( - window: _Fleet, caplog: pytest.LogCaptureFixture, arguments: list[str], typed: str | None, env: dict[str, str] + window: _Fleet, + caplog: pytest.LogCaptureFixture, + arguments: list[str], + typed: str | None, + env: dict[str, str], + run: Run, ) -> None: - """Typed at the hidden prompt, given as an option or from the environment""" - result = CliRunner().invoke(cli_group, ["-vv", "challenge", *arguments], input=typed, env=env) + """Typed at the hidden prompt or from the environment""" + result = run(["-vv", "challenge", *arguments], typed=typed, env=env) assert result.exit_code == 0, result.output assert result.stdout.splitlines()[-1] == ( - "Fleet has the new challenge. The enrolment window is open until 2026-11-21 14:00 UTC" + "Fleet has the new challenge. The enrolment window is open until 2026-11-21 14:00" ) assert window.authorities[0]["challenge"] == SECRET assert window.authorities[0]["url"] == "https://unit.example.fi/scep" @@ -726,46 +780,57 @@ def test_challenge_takes_the_settings_line( assert SECRET not in caplog.text +def test_challenge_is_never_an_argument(window: _Fleet, run: Run) -> None: + """An argument is in the process list and the shell history""" + result = run(["challenge", "--challenge", LINE]) + + assert result.exit_code == 2 + assert "unrecognized arguments: --challenge" in result.stderr + assert not window.calls + + @pytest.mark.parametrize( ("line", "says"), [ (LINE.replace("unit.example.fi", "other.example.fi"), "is for other.example.fi, not unit.example.fi"), - (LINE.replace("https://", "http://"), "must start with https://"), - (LINE.replace("2026-11-21T14", "2026-11-21T11"), "closed at 2026-11-21T11:00:00Z"), + (LINE.replace("https://", "http://"), "must be https:///"), + (LINE.replace("2026-11-21T14", "2026-11-21T11"), "closed at 11:00"), (LINE.replace("ODMDM1", "ODMDM2"), "not a settings line"), (LINE.replace("ODMDM1", "odmdm1"), "not a settings line"), (LINE.split(None, 1)[1], "not a settings line"), ('"' + LINE + '"', "not a settings line"), ], ) -def test_challenge_refuses_a_line_it_cannot_use(window: _Fleet, line: str, says: str) -> None: +def test_challenge_refuses_a_line_it_cannot_use(window: _Fleet, line: str, says: str, run: Run) -> None: """Before Fleet is asked anything, and without the challenge in the message""" - result = CliRunner().invoke(cli_group, ["challenge"], input=line + "\n") + result = run(["challenge"], typed=line) assert result.exit_code == 1 - assert says in result.output + assert says in result.stderr assert SECRET not in result.output assert not window.calls -def test_apply_takes_the_settings_line_from_the_environment(window: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_apply_takes_the_settings_line_from_the_environment( + window: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: """ODMDM_CHALLENGE may hold the line; apply must not send the whole line as the challenge""" - monkeypatch.setattr(config, "CHALLENGE", LINE) + monkeypatch.setenv("ODMDM_CHALLENGE", LINE) - result = CliRunner().invoke(cli_group, ["apply"]) + result = run(["apply"]) assert result.exit_code == 0, result.output assert window.authorities[0]["challenge"] == SECRET assert SECRET not in result.output -def test_apply_refuses_a_line_for_another_deployment(window: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(config, "CHALLENGE", LINE.replace("unit.example.fi", "other.example.fi")) +def test_apply_refuses_a_line_for_another_deployment(window: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + monkeypatch.setenv("ODMDM_CHALLENGE", LINE.replace("unit.example.fi", "other.example.fi")) - result = CliRunner().invoke(cli_group, ["apply"]) + result = run(["apply"]) assert result.exit_code == 1 - assert "is for other.example.fi" in result.output + assert "is for other.example.fi" in result.stderr assert not window.calls @@ -780,33 +845,92 @@ def test_apply_refuses_a_line_for_another_deployment(window: _Fleet, monkeypatch ], ) def test_the_mdm_and_its_settings_are_checked_first( - fleet: _Fleet, options: list[str], env: dict[str, str], says: str + fleet: _Fleet, options: list[str], env: dict[str, str], says: str, run: Run ) -> None: """Before the MDM is asked anything, and without a value in the message""" - result = CliRunner().invoke(cli_group, [*options, "phones"], env=env) + result = run([*options, "phones"], env=env) assert result.exit_code == 2 - assert says in result.output + assert says in result.stderr assert SECRET not in result.output assert not fleet.calls -def test_set_gives_an_mdm_setting(fleet: _Fleet) -> None: +def test_set_gives_an_mdm_setting(fleet: _Fleet, run: Run) -> None: """The same as the command's own shorthand, here --team""" - result = CliRunner().invoke(cli_group, ["--set", "team=Typo", "phones"]) + result = run(["--set", "team=Typo", "phones"]) assert result.exit_code == 1 - assert "no team named Typo" in result.output + assert "no team named Typo" in result.stderr -def test_a_secret_is_never_read_from_a_plain_variable(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_secret_is_never_read_from_a_plain_variable(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """Only from the file its _FILE variable names""" monkeypatch.delenv("ODMDM_TOKEN_FILE") - result = CliRunner().invoke(cli_group, ["phones"], env={"ODMDM_TOKEN": "token"}) + result = run(["phones"], env={"ODMDM_TOKEN": "token"}) assert result.exit_code == 1 - assert "Set ODMDM_TOKEN_FILE" in result.output + assert "API token is missing: put it in a file and set ODMDM_TOKEN_FILE to that file" in result.stderr + assert not fleet.calls + + +def test_a_secret_with_a_line_break_is_refused_and_never_shown( + fleet: _Fleet, tmp_path: Path, run: Run, caplog: pytest.LogCaptureFixture +) -> None: + caplog.set_level(logging.DEBUG) + token = tmp_path / "broken.token" + token.write_text("TOPSECRETA\nTOPSECRETB\n", encoding="utf-8") + + result = run(["phones"], env={"ODMDM_TOKEN_FILE": str(token)}) + + assert result.exit_code == 1 + assert result.stderr == ( + "The API token holds a line break or another character that cannot be part of it: copy it again.\n" + ) + assert "TOPSECRET" not in result.output + caplog.text + assert not fleet.calls + + +@pytest.mark.parametrize( + "written", + [ + b"TOPSECRET\n", + codecs.BOM_UTF8 + b"TOPSECRET\r\n", + "TOPSECRET\r\n".encode("utf-16"), + codecs.BOM_UTF16_BE + "TOPSECRET".encode("utf-16-be"), + ], + ids=["utf-8", "utf-8 with its mark", "utf-16 as PowerShell 5.1 writes", "utf-16 big-endian"], +) +def test_a_token_file_is_read_in_the_encodings_editors_write( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, written: bytes +) -> None: + token = tmp_path / "token" + token.write_bytes(written) + monkeypatch.setenv("ODMDM_TOKEN_FILE", str(token)) + + assert console._values("fleet", FleetPlugin.fields, {})["token"] == "TOPSECRET" + + +@pytest.mark.parametrize("unreadable", ["not text", "not readable"]) +def test_a_token_file_that_cannot_be_read_as_text_is_said_without_the_token( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run, unreadable: str +) -> None: + token = tmp_path / "broken.token" + token.write_bytes(b"TOPSECRET\xff\xfe") + if unreadable == "not readable": + token.write_text("TOPSECRET", encoding="utf-8") + + def refuse(self: Path) -> bytes: + raise PermissionError(13, "Permission denied", str(self)) + + monkeypatch.setattr(Path, "read_bytes", refuse) + + result = run(["phones"], env={"ODMDM_TOKEN_FILE": str(token)}) + + assert result.exit_code == 1 + assert result.stderr == f"The file {token} cannot be read as plain text: save the API token in it as plain text.\n" + assert "TOPSECRET" not in result.output assert not fleet.calls @@ -815,26 +939,26 @@ def test_a_secret_is_never_read_from_a_plain_variable(fleet: _Fleet, monkeypatch [(["challenge"], "set_challenge"), (["apply"], "setup"), (["resend"], "ask_again")], ) def test_a_capability_the_mdm_lacks_is_its_sentence( - fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str], capability: str + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str], capability: str, run: Run ) -> None: """Said instead of calling the MDM, and before a challenge is asked for""" _template(tmp_path, monkeypatch) monkeypatch.setattr(FleetPlugin, "missing", {capability: "Paste the challenge in the MDM's console by hand"}) - result = CliRunner().invoke(cli_group, command) + result = run(command) assert result.exit_code == 1 - assert result.output == "Paste the challenge in the MDM's console by hand\n" + assert result.stderr == "Paste the challenge in the MDM's console by hand\n" assert not fleet.calls -def test_a_dry_run_needs_no_mdm(monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_dry_run_needs_no_mdm(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """The template shipped with the connector, checked with nothing configured but the domain""" for setting in ("MDM_URL", "TOKEN_FILE", "TEMPLATE"): monkeypatch.delenv(f"ODMDM_{setting}", raising=False) - monkeypatch.setattr(config, "DOMAIN", "example.fi") + monkeypatch.setenv("ODMDM_DOMAIN", "example.fi") - result = CliRunner().invoke(cli_group, ["apply", "--dry-run"]) + result = run(["apply", "--dry-run"]) assert result.exit_code == 0, result.output assert result.stdout.splitlines()[0] == "Template names 3 apps, 3 installed at enrolment" @@ -852,14 +976,14 @@ def _declare(monkeypatch: pytest.MonkeyPatch, *found: tuple[str, str, str]) -> N FAKE = ("fake", "odmdm-connector-fake", "odmdm_connector.testing.fake:FakeMdm") -def test_mdms_lists_what_is_installed_without_loading_it(monkeypatch: pytest.MonkeyPatch) -> None: +def test_mdms_lists_what_is_installed_without_loading_it(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: _declare( monkeypatch, ("zeta", "odmdm-connector-zeta", "never_imported:Mdm"), ("fleet", "odmdm-connector", "odmdm_connector.never_imported:Mdm"), ) - result = CliRunner().invoke(cli_group, ["mdms"]) + result = run(["mdms"]) assert result.exit_code == 0, result.output assert [line.split() for line in result.stdout.splitlines()] == [ @@ -868,21 +992,21 @@ def test_mdms_lists_what_is_installed_without_loading_it(monkeypatch: pytest.Mon ] -def test_a_plugin_says_whose_code_it_is_before_it_runs(monkeypatch: pytest.MonkeyPatch) -> None: +def test_a_plugin_says_whose_code_it_is_before_it_runs(monkeypatch: pytest.MonkeyPatch, run: Run) -> None: """On stderr, so what the command prints stays the same""" _declare(monkeypatch, FAKE) - result = CliRunner().invoke(cli_group, ["--mdm", "fake", "phones"]) + result = run(["--mdm", "fake", "phones"]) assert result.exit_code == 0, result.output assert result.stderr == "The MDM fake is a plugin from odmdm-connector-fake 0.1.0: code that sees the MDM token\n" assert [line.split()[:2] for line in result.stdout.splitlines()] == [["a1", "-"], ["a2", "-"], ["a3", "OTTER1"]] -def test_the_built_in_mdm_says_nothing_of_itself(fleet: _Fleet) -> None: +def test_the_built_in_mdm_says_nothing_of_itself(fleet: _Fleet, run: Run) -> None: fleet.hosts = [_host(31)] - result = CliRunner().invoke(cli_group, ["phones"]) + result = run(["phones"]) assert result.exit_code == 0, result.output assert not result.stderr @@ -901,11 +1025,44 @@ def test_the_built_in_mdm_says_nothing_of_itself(fleet: _Fleet) -> None: ], ) def test_a_plugin_the_connector_cannot_use_is_said( - monkeypatch: pytest.MonkeyPatch, found: list[tuple[str, str, str]], command: list[str], says: str + monkeypatch: pytest.MonkeyPatch, found: list[tuple[str, str, str]], command: list[str], says: str, run: Run ) -> None: _declare(monkeypatch, *found) - result = CliRunner().invoke(cli_group, command) + result = run(command) assert result.exit_code == 1 assert says in result.stderr + + +def test_python_m_runs_the_command_line(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: + """The way to run it from a zip application or a checkout, without the installed script""" + monkeypatch.setattr(sys, "argv", ["odmdm-connector", "--version"]) + + with pytest.raises(SystemExit) as ended: + runpy.run_module("odmdm_connector", run_name="__main__") + + assert ended.value.code == 0 + assert capsys.readouterr().out == f"odmdm-connector, version {__version__}\n" + + +def test_ctrl_c_at_the_prompt_says_it_stopped(window: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """A sentence rather than a traceback, and the MDM is not asked""" + + def interrupted(prompt: str) -> str: + raise KeyboardInterrupt + + monkeypatch.setattr(getpass, "getpass", interrupted) + + result = run(["challenge"]) + + assert result.exit_code == 1 + assert result.stderr == "Stopped before the command finished.\n" + assert not window.calls + + +@pytest.mark.parametrize("level", ["debug", "", "1.5"]) +def test_a_log_level_that_is_not_a_number_is_said(run: Run, level: str) -> None: + result = run(["mdms"], env={"ODMDM_LOG_LEVEL": level}) + + assert (result.exit_code, result.stdout, result.stderr) == (1, "", f"{console.LOG_LEVEL}\n") From 4921dcd9daedef1e513c817711c75213c332b6a7 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 062/104] test: drive the connector's core against the fake MDM --- tests/test_app.py | 1380 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1380 insertions(+) create mode 100644 tests/test_app.py diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..ab7fb2b --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,1380 @@ +"""The page's core without a page: the FakeMdm, a temporary settings directory and the time given""" + +import datetime +import io +import logging +import sys +import threading +import time +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace +from importlib.metadata import EntryPoint +from pathlib import Path +from typing import ClassVar + +import pytest + +from odmdm_connector import app, plugins, store +from odmdm_connector.fleet_plugin import FleetPlugin +from odmdm_connector.mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step +from odmdm_connector.settings import Settings +from odmdm_connector.testing import FakeMdm +from odmdm_connector.testing.fake import PHONES + +from .test_store import MemoryBackend + +CHALLENGE = "0123456789abcdef0123456789abcdef" # pragma: allowlist secret +LINE = f"ODMDM1 https://unit.example.fi/scep {CHALLENGE} 2026-11-21T14:00:00Z" +OTHER = LINE.replace("unit.example.fi", "other.example.fi").replace("14:00:00Z", "15:30:00Z") +NOW = datetime.datetime(2026, 11, 21, 12, 0, tzinfo=datetime.UTC) +VALUES = {"group": "Deploy App", "password": "pa55word"} # pragma: allowlist secret +LACKING = FakeMdm.lacking(SETUP, SET_CHALLENGE, ASK_AGAIN) + + +class Rig: + """An App and everything handed to it""" + + def __init__(self, directory: Path, backend: MemoryBackend | None = None) -> None: + self.directory = directory + #: The keychain, kept across starts; none by default, as in the one-file build + self.backend = backend + self.loaded: list[str] = [] + self.classes: dict[str, type[Mdm]] = {"fake": FakeMdm, "demo": LACKING} + self.versions = {"demo": "1.0.0"} + #: What listing the plugins raises, if anything + self.unlisted: plugins.PluginError | None = None + #: What plugins.load says when it cannot load the plugin + self.refused = "" + self.app = self.start() + + def installed(self) -> list[plugins.Plugin]: + if self.unlisted: + raise self.unlisted + return [ + plugins.Plugin("fake", "odmdm-connector", "1.2.0", EntryPoint("fake", "odmdm_connector.testing:Fake", "g")), + plugins.Plugin("demo", "odmdm-connector-demo", self.versions["demo"], EntryPoint("demo", "demo:Demo", "g")), + ] + + def load(self, name: str) -> type[Mdm]: + self.loaded.append(name) + if self.refused: + raise plugins.PluginError(self.refused) + return self.classes[name] + + def start(self) -> app.App: + """The app as started afresh on the same computer""" + return app.App( + store.Store(self.directory), + installed=self.installed, + load=self.load, + log_path=self.directory / "the.log", + keychain=store.Keychain(self.backend), + ) + + def settle(self) -> list[app.Result]: + self.app.worker.wait() + return self.app.drain() + + def connected(self, name: str = "fake", values: Mapping[str, str] = VALUES, remember: bool = True) -> FakeMdm: + """Pasted, connected and the phones read""" + self.app.paste_settings(LINE, NOW) + if self.app.approval(name): + self.app.approve(name) + self.app.connect(name, values, remember) + self.app.refresh() + self.settle() + assert isinstance(self.app.mdm, FakeMdm) + return self.app.mdm + + +@pytest.fixture +def rig(tmp_path: Path) -> Iterator[Rig]: + made = Rig(tmp_path / "config") + yield made + made.app.close() + + +@pytest.fixture +def keyed(tmp_path: Path) -> Iterator[Rig]: + """A rig whose computer has a keychain""" + made = Rig(tmp_path / "config", MemoryBackend()) + yield made + made.app.close() + + +#: Where the fake MDM's password for unit.example.fi is kept +KEPT = ("odmdm-connector", "unit.example.fi:fake:password") + + +def test_first_setup_holds_the_secret_in_memory_and_the_rest_in_the_file(rig: Rig) -> None: + with pytest.raises( + app.AppError, match="^Add the Deploy App first: on its MDM page, press Open in the MDM connector.$" + ): + rig.app.connect("fake", VALUES) + + pasted = rig.app.paste_settings(f" {LINE}\n", NOW) + form = rig.app.form("fake") + said = rig.app.connect("fake", VALUES) + [result] = rig.settle() + + assert pasted == "Deploy App unit.example.fi accepts phones until 14:00." + assert (form.title, [(value.field.key, value.value) for value in form.fields]) == ( + "Fake MDM", + [("group", "Deploy App"), ("password", "")], + ) + assert said == "Setting Fake MDM up for Deploy App unit.example.fi." + assert (result.job, result.error) == (app.Job.SETUP, "") + assert [step.label for step in result.steps] == [ + "Group Deploy App enrols at https://unit.example.fi/scep", + "Certificate template stated", + ] + assert rig.app.status == "Fake MDM is set up for Deploy App unit.example.fi." + assert rig.app.form("fake").fields[1].value == "pa55word" + text = (rig.directory / "settings.json").read_text(encoding="utf-8") + assert CHALLENGE not in text and "pa55word" not in text + assert rig.app.saved == store.Saved( + connections={ + "unit.example.fi": store.Connection( + mdm="fake", values={"group": "Deploy App"}, closes="2026-11-21T14:00:00+00:00" + ) + }, + active="unit.example.fi", + ) + + +@pytest.mark.parametrize( + ("values", "says"), + [ + ({"mdm_url": "", "token": "t0ken"}, "Fill in Fleet address."), # pragma: allowlist secret + ({"mdm_url": "https://mdm.example.fi", "token": " "}, "Fill in API token."), + ], +) +def test_a_required_field_left_empty_is_said_and_nothing_kept(rig: Rig, values: dict[str, str], says: str) -> None: + rig.classes["fake"] = FleetPlugin + rig.app.paste_settings(LINE, NOW) + before = rig.app.saved + + with pytest.raises(app.AppError, match=f"^{says}$"): + rig.app.connect("fake", values) + + assert rig.app.form("fake").fields[1].value == "" + assert rig.app.saved == before + assert store.Store(rig.directory).load() == before + assert rig.app.mdm is None + + +class Addressed(FakeMdm): + """An MDM with an address, which records every one made, as each would send its token there""" + + fields: ClassVar[tuple[Field, ...]] = ( + Field("mdm_url", "Address", required=True), + Field("token", "Token", secret=True, required=True), + Field("team", "Team", default="Deploy App"), + ) + made: ClassVar[list[dict[str, str]]] = [] + + def __init__(self, values: Mapping[str, str]) -> None: + super().__init__(values) + Addressed.made.append(dict(values)) + + +TOKEN_VALUES = {"mdm_url": "https://mdm.example.fi", "token": "t0ken", "team": "Deploy App"} # pragma: allowlist secret + + +@pytest.mark.parametrize( + "changed", + [ + {"mdm_url": "https://attacker.example.fi"}, + {"team": "Other"}, + {"mdm_url": "https://mdm.example.fi", "team": ""}, + ], +) +def test_a_kept_secret_goes_only_with_the_settings_it_was_kept_for(keyed: Rig, changed: dict[str, str]) -> None: + keyed.classes["fake"] = Addressed + keyed.app.paste_settings(LINE, NOW) + keyed.app.connect("fake", TOKEN_VALUES) + keyed.settle() + Addressed.made.clear() + before, backend = keyed.app.saved, keyed.backend + assert backend is not None + kept = dict(backend.items) + + with pytest.raises(app.AppError, match="^Type the Token again: the settings changed.$"): + keyed.app.connect("fake", {**TOKEN_VALUES, "token": "", **changed}) + + assert Addressed.made == [], "no MDM made, so nothing sent" + assert (keyed.app.saved, store.Store(keyed.directory).load(), backend.items) == (before, before, kept) + assert not keyed.app.busy() + assert keyed.app.connect("fake", {**TOKEN_VALUES, "token": ""}) == ( + "Setting Fake MDM up for Deploy App unit.example.fi." + ) + assert Addressed.made == [TOKEN_VALUES], "the same settings take the kept token" + keyed.settle() + + +def test_a_secret_is_held_only_once_its_settings_are_written(rig: Rig) -> None: + """Held before, a new token would stay under the old saved address and go there on the next connect""" + rig.classes["fake"] = Addressed + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", TOKEN_VALUES) + rig.settle() + Addressed.made.clear() + rig.app.store = store.Store(rig.directory / "settings.json" / "not-a-directory") + + with pytest.raises(app.AppError, match="cannot be written"): + rig.app.connect("fake", {**TOKEN_VALUES, "mdm_url": "https://new.example.fi", "token": "NEWTOKEN"}) + rig.app.store = store.Store(rig.directory) + rig.app.connect("fake", {**TOKEN_VALUES, "token": ""}) + + assert Addressed.made == [TOKEN_VALUES], "the old address gets only the token typed for it" + rig.settle() + + +def test_a_kept_secret_does_not_go_to_another_mdm(rig: Rig) -> None: + rig.connected() + rig.app.approve("demo") + + rig.app.connect("demo", {"group": "Deploy App", "password": ""}) + + assert isinstance(rig.app.mdm, FakeMdm) + assert rig.app.mdm.values == {"group": "Deploy App", "password": ""} + rig.settle() + + +@pytest.mark.parametrize("token", ["TOPSECRETA\nTOPSECRETB", "TOPSECRET\r", "TOP\x00SECRET", "TOP\x7fSECRET"]) +def test_a_secret_with_a_control_character_is_refused_before_it_is_held( + rig: Rig, caplog: pytest.LogCaptureFixture, token: str +) -> None: + caplog.set_level(logging.DEBUG) + rig.classes["fake"] = Addressed + rig.app.paste_settings(LINE, NOW) + before = rig.app.saved + + with pytest.raises(app.AppError) as raised: + rig.app.connect("fake", {**TOKEN_VALUES, "token": token}) + + assert str(raised.value) == ( + "The Token holds a line break or another character that cannot be part of it: copy it again." + ) + assert (rig.app.saved, rig.app.mdm, rig.app.form("fake").fields[1].value) == (before, None, "") + assert "TOPSECRET" not in caplog.text + + +def test_a_restart_holds_no_secret_and_connects_without_a_window(rig: Rig) -> None: + """The token is typed again on another day, and the MDM already set up is only connected""" + rig.connected() + + again = rig.start() + held = again.form("fake").fields[1].value + said = again.connect("fake", VALUES) + + assert (held, again.window) == ("", None) + assert said == "Connected to Fake MDM for Deploy App unit.example.fi." + assert isinstance(again.mdm, FakeMdm) + assert (again.mdm.values, again.mdm.calls, again.busy()) == (VALUES, [], False) + assert again.banner(NOW).text == "Deploy App unit.example.fi accepts phones until 14:00" + again.approve("demo") + with pytest.raises( + app.AppError, + match="^To set Fake MDM up, open enrolment on the MDM page of Deploy App unit.example.fi, " + "then press Open in the MDM connector there.$", + ): + again.connect("demo", VALUES) + again.close() + + +def test_a_damaged_settings_file_is_said_and_the_app_starts_without_it(rig: Rig) -> None: + rig.directory.mkdir() + (rig.directory / "settings.json").write_text("{", encoding="utf-8") + + started = rig.start() + + assert started.saved == store.Saved() + assert started.status.endswith("is damaged, so the app starts without it.") + started.close() + + +@pytest.mark.parametrize( + ("line", "says"), + [ + ("0123", "This is not a settings line: it has four parts and starts with ODMDM1."), + (LINE.replace("https", "http"), "The SCEP URL in the settings line must be https:///"), + (LINE.replace("14:00:00Z", "11:00:00Z"), "The enrolment window closed at 11:00"), + ], +) +def test_a_line_that_is_not_one_is_refused_in_a_sentence(rig: Rig, line: str, says: str) -> None: + with pytest.raises(app.AppError) as raised: + rig.app.paste_settings(line, NOW) + + assert str(raised.value).startswith(says) + assert (rig.app.window, rig.app.saved) == (None, store.Saved()) + + +def test_a_line_for_another_deploy_app_adds_it_and_works_with_it(rig: Rig) -> None: + rig.connected() + rig.app.preview(["a1"], ["BEAR1"], NOW) + + said = rig.app.paste_settings(OTHER, NOW) + + assert said == "Deploy App other.example.fi accepts phones until 15:30." + assert rig.app.saved.active == "other.example.fi" + assert list(rig.app.saved.connections) == ["unit.example.fi", "other.example.fi"] + assert rig.app.saved.connections["unit.example.fi"].values == {"group": "Deploy App"} + assert (rig.app.conn, rig.app.mdm, rig.app.phones) == ( + store.Connection(closes="2026-11-21T15:30:00+00:00"), + None, + [], + ) + assert rig.app.window is not None and rig.app.window.scep_url == "https://other.example.fi/scep" + with pytest.raises(app.AppError, match="Connect to the MDM first."): + rig.app.name({"a1": "BEAR1"}) + + +def test_two_deploy_apps_side_by_side_each_with_its_own_mdm_and_token(rig: Rig) -> None: + unit = rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.connect("fake", {"group": "Other unit", "password": "0ther"}) # pragma: allowlist secret + rig.settle() + + back = rig.app.open("unit.example.fi", NOW) + unit_again = rig.app.mdm + other = rig.app.open("other.example.fi", NOW) + + assert back == "Deploy App unit.example.fi accepts phones until 14:00." + assert isinstance(unit_again, FakeMdm) and unit_again is not unit + assert unit_again.values == VALUES + assert other == "Deploy App other.example.fi accepts phones until 15:30." + assert isinstance(rig.app.mdm, FakeMdm) + assert rig.app.mdm.values == {"group": "Other unit", "password": "0ther"} # pragma: allowlist secret + assert rig.app.form("fake").fields[0].value == "Other unit" + + +def test_the_deploy_apps_as_listed(rig: Rig) -> None: + rig.connected() + rig.app.paste_settings(OTHER, NOW) + + listed = rig.app.connections(NOW.replace(hour=13, minute=55)) + + assert listed == [ + app.DeployApp( + "unit.example.fi", + app.Banner( + app.Level.CLOSING, + "Deploy App unit.example.fi accepts phones until 14:00, 5 minutes from now", + "enrolment open until 14:00, 5 minutes left", + ), + False, + ), + app.DeployApp( + "other.example.fi", + app.Banner( + app.Level.OPEN, "Deploy App other.example.fi accepts phones until 15:30", "enrolment open until 15:30" + ), + True, + ), + ] + + +def test_reading_a_line_takes_nothing_from_it(rig: Rig) -> None: + rig.connected() + before = (rig.app.saved, rig.app.window, rig.app.status) + + known = rig.app.read_settings(LINE, NOW) + new = rig.app.read_settings(OTHER, NOW) + + assert known == app.Reading("unit.example.fi", "Deploy App unit.example.fi accepts phones until 14:00.", True) + assert new == app.Reading("other.example.fi", "Deploy App other.example.fi accepts phones until 15:30.", False) + assert (rig.app.saved, rig.app.window, rig.app.status) == before + with pytest.raises(app.AppError, match="This is not a settings line"): + rig.app.read_settings("ODMDM1", NOW) + + +def test_opening_a_deploy_app_without_its_token_says_so(rig: Rig) -> None: + rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.close() + rig.app = rig.start() + + said = rig.app.open("unit.example.fi", NOW) + + assert said == ( + "Deploy App unit.example.fi accepts phones until 14:00. " + "Type the Password again to connect: it is kept only while the connector runs." + ) + assert rig.app.mdm is None + assert rig.app.open("unit.example.fi", NOW) == said, "said again while it is not connected" + with pytest.raises(app.AppError, match="^There is no Deploy App nope.example.fi in this app.$"): + rig.app.open("nope.example.fi", NOW) + + +def test_removing_a_deploy_app_lets_go_of_its_token(rig: Rig) -> None: + rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + other = rig.app.remove("unit.example.fi") + kept = (rig.app.saved.active, rig.app.connected) + active = rig.app.remove("other.example.fi") + + assert other == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + assert kept == ("other.example.fi", True) + assert active == "Deploy App other.example.fi is removed from this app, and its MDM token from this computer." + assert (rig.app.saved, rig.app.mdm, rig.app.window) == (store.Saved(), None, None) + assert rig.app.banner(NOW).level is app.Level.NONE + with pytest.raises(app.AppError, match="^There is no Deploy App unit.example.fi in this app.$"): + rig.app.remove("unit.example.fi") + rig.app.paste_settings(LINE, NOW) + assert rig.app.form("fake").fields[1].value == "", "added again, its token is typed again" + + +def test_a_deploy_app_whose_plugin_is_gone_is_removed(rig: Rig) -> None: + rig.app.paste_settings(LINE, NOW) + rig.app.approve("demo") + rig.app.connect("demo", VALUES) + rig.settle() + rig.app.paste_settings(OTHER, NOW) + rig.refused = "The MDM demo cannot be loaded" + + said = rig.app.remove("unit.example.fi") + + assert said == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + assert list(rig.app.saved.connections) == ["other.example.fi"] + assert rig.app.remove("other.example.fi") == "Deploy App other.example.fi is removed from this app.", ( + "no MDM, no token" + ) + + +def test_a_result_for_a_deploy_app_no_longer_active_changes_nothing(rig: Rig) -> None: + rig.app.paste_settings(LINE, NOW) + rig.app.keep_callsigns("", ["BEAR1"]) + rig.connected() + rig.app.name(rig.app.preview(["a1"], ["BEAR1"], NOW).names) + rig.app.refresh() + rig.app.paste_settings(OTHER, NOW) + + rig.settle() + + assert (rig.app.phones, rig.app.status) == ([], "1 phone named.") + assert rig.app.saved.connections["unit.example.fi"].callsigns == ["BEAR1"] + + +def test_callsigns_are_kept_only_for_a_deploy_app(rig: Rig) -> None: + with pytest.raises( + app.AppError, match="^Add the Deploy App first: on its MDM page, press Open in the MDM connector.$" + ): + rig.app.keep_callsigns("BEAR", ["BEAR1"]) + + +def test_a_new_window_gives_the_mdm_its_challenge(rig: Rig) -> None: + fake = rig.connected() + + said = rig.app.paste_settings(LINE, NOW + datetime.timedelta(minutes=55)) + [result] = rig.settle() + + assert said == "Deploy App unit.example.fi accepts phones until 14:00. Giving the MDM the new challenge." + assert (result.job, fake.challenge, rig.app.status) == ( + app.Job.CHALLENGE, + CHALLENGE, + "Fake MDM has the new challenge.", + ) + assert (rig.app.challenge_note(), rig.app.challenge()) == ("", "") + + +def test_a_plugin_is_approved_before_it_is_imported(rig: Rig) -> None: + """Asked again when its package's version changes; only the chosen one is ever imported""" + asked = rig.app.approval("demo") + with pytest.raises(app.AppError, match="The MDM demo is a plugin that has not been approved in this app."): + rig.app.form("demo") + rig.app.approve("demo") + rig.app.form("demo") + rig.versions["demo"] = "1.0.1" + + assert asked == ( + "The MDM demo comes from the package odmdm-connector-demo 1.0.0, not with this app. " + "A plugin is code that sees the MDM token: use it only if you trust where it comes from." + ) + assert rig.app.approval("fake") == "" + assert rig.app.approval("demo").startswith("The MDM demo comes from the package odmdm-connector-demo 1.0.1") + assert rig.loaded == ["demo"] + assert rig.start().saved.approved == ["demo odmdm-connector-demo 1.0.0"] + rig.app.approve("demo") + assert rig.app.saved.approved == ["demo odmdm-connector-demo 1.0.1"] + with pytest.raises(app.AppError, match="No MDM named nope is installed."): + rig.app.approval("nope") + + +def test_an_mdm_set_up_but_given_the_challenge_by_hand_says_so(rig: Rig) -> None: + rig.classes["demo"] = FakeMdm.lacking(SET_CHALLENGE) + rig.app.paste_settings(LINE, NOW) + rig.app.approve("demo") + rig.app.connect("demo", VALUES) + rig.settle() + + assert rig.app.status == "Do the steps by hand to finish setting Fake MDM up for Deploy App unit.example.fi." + + +def test_an_mdm_lacking_everything_says_so_and_shows_the_challenge_only_to_be_copied(rig: Rig) -> None: + rig.app.paste_settings(LINE, NOW) + rig.app.approve("demo") + rig.app.connect("demo", VALUES) + [result] = rig.settle() + status = rig.app.status + said = rig.app.paste_settings(LINE, NOW) + + assert result.steps == (Step("The fake MDM cannot setup", False),) + assert status == "Do the steps by hand to finish setting Fake MDM up for Deploy App unit.example.fi." + assert said == "Deploy App unit.example.fi accepts phones until 14:00." + assert rig.app.challenge_note() == "The fake MDM cannot set_challenge" + assert rig.app.challenge() == CHALLENGE + assert not rig.app.busy() + with pytest.raises(app.AppError, match="The fake MDM cannot ask_again"): + rig.app.ask_again([]) + + +@pytest.mark.parametrize( + ("now", "level", "text", "short"), + [ + (NOW, app.Level.OPEN, "Deploy App unit.example.fi accepts phones until 14:00", "enrolment open until 14:00"), + ( + NOW.astimezone(datetime.timezone(datetime.timedelta(hours=2))), + app.Level.OPEN, + "Deploy App unit.example.fi accepts phones until 16:00", + "enrolment open until 16:00", + ), + ( + NOW.replace(hour=13, minute=50), + app.Level.CLOSING, + "Deploy App unit.example.fi accepts phones until 14:00, 10 minutes from now", + "enrolment open until 14:00, 10 minutes left", + ), + ( + NOW.replace(hour=13, minute=59, second=30), + app.Level.CLOSING, + "Deploy App unit.example.fi accepts phones until 14:00, 1 minute from now", + "enrolment open until 14:00, 1 minute left", + ), + ( + NOW.replace(hour=14), + app.Level.CLOSED, + ( + "Enrolment closed at 14:00. Open enrolment again on the MDM page of Deploy App, " + "then press Open in the MDM connector there." + ), + "enrolment closed at 14:00", + ), + ], +) +def test_the_banner_follows_the_window( + rig: Rig, now: datetime.datetime, level: app.Level, text: str, short: str +) -> None: + before = rig.app.banner(NOW) + rig.app.paste_settings(LINE, NOW) + + assert before == app.Banner( + app.Level.NONE, + "On the MDM page of Deploy App, press Open in the MDM connector to let phones enrol.", + "no enrolment window known", + ) + assert rig.app.banner(now) == app.Banner(level, text, short) + + +def test_the_phones_are_counted_by_where_they_are(rig: Rig) -> None: + assert rig.app.summary() == "" + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.app.refresh() + assert rig.app.summary() == "", "nothing is said of the phones before they are listed" + rig.settle() + fake = rig.app.mdm + assert isinstance(fake, FakeMdm) + assert rig.app.summary() == "3 phones: 1 ready, 2 without a name" + + fake.group = [ + *PHONES, + replace(PHONES[2], id="a4", state=State.REFUSED), + replace(PHONES[2], id="a5", state=State.WAITING), + replace(PHONES[0], id="a6", state=State.REFUSED), + ] + rig.app.refresh() + rig.settle() + assert rig.app.summary() == "6 phones: 1 ready, 1 waiting for the phone, 1 failed, 3 without a name" + + fake.group = [PHONES[0]] + rig.app.refresh() + rig.settle() + assert rig.app.summary() == "1 phone: 1 without a name" + + fake.group = [] + rig.app.refresh() + rig.settle() + assert rig.app.summary() == "No phones yet." + + +def test_a_listing_that_failed_is_not_no_phones(rig: Rig) -> None: + rig.classes["fake"] = Broken + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.app.refresh() + rig.settle() + + assert rig.app.summary() == "", "the MDM never listed its phones, so none is not said" + + +def test_after_a_restart_the_app_says_why_the_token_is_asked_for(rig: Rig) -> None: + rig.connected() + rig.app.close() + rig.app = rig.start() + typed = "Type the Password again to connect: it is kept only while the connector runs." + + first = rig.app.status + pasted = rig.app.paste_settings(LINE, NOW) + + assert (first, rig.app.mdm) == (typed, None) + assert pasted == f"Deploy App unit.example.fi accepts phones until 14:00. {typed}" + + +def test_after_a_restart_an_mdm_without_a_secret_is_connected_at_once(rig: Rig) -> None: + class NoSecret(FakeMdm): + fields: ClassVar = FakeMdm.fields[:1] + + rig.classes["fake"] = NoSecret + rig.connected() + rig.app.close() + rig.app = rig.start() + + assert (rig.app.status, rig.app.connected) == ("", True) + + +def test_several_secrets_not_at_hand_are_all_named(rig: Rig) -> None: + class TwoSecrets(FakeMdm): + fields: ClassVar = (*FakeMdm.fields, Field("pin", "PIN", secret=True)) + + rig.classes["fake"] = TwoSecrets + rig.connected(values={**VALUES, "pin": "1234"}) + rig.app.paste_settings(OTHER, NOW) + rig.app.close() + rig.app = rig.start() + + rig.app.open("unit.example.fi", NOW) + + assert rig.app.status.endswith( + "Type the Password and PIN again to connect: they are kept only while the connector runs." + ) + + +def test_the_table(rig: Rig) -> None: + fake = rig.connected() + fake.group = [*PHONES[:2], replace(PHONES[2], state=State.REFUSED, detail="name taken")] + rig.app.refresh() + rig.settle() + + rows = rig.app.rows(NOW.astimezone(datetime.timezone(datetime.timedelta(hours=2)))) + + assert rows == [ + app.Row("a1", "", "Pretend Phone 7", "2026-11-01 11:00", "waiting for a name", True, False, False, False), + app.Row("a2", "", "Pretend Phone 7", "2026-11-01 11:05", "waiting for a name", True, False, False, False), + app.Row( + "a3", + "OTTER1", + "Pretend Tablet 2", + "2026-11-01 11:10", + "refused by Deploy App: name taken", + False, + True, + False, + True, + ), + ] + + +def test_a_batch_numbered_on_from_the_callsigns_in_use(rig: Rig) -> None: + fake = rig.connected() + ids = rig.app.targets([]) + callsigns = rig.app.numbered("OTTER", rig.app.first_number("otter"), len(ids)) + + preview = rig.app.preview(ids, callsigns, NOW) + said = rig.app.name(preview.names) + results = rig.settle() + + assert (ids, callsigns) == (["a1", "a2"], ["OTTER2", "OTTER3"]) + assert (preview.ok, preview.button, preview.warning) == (True, "Name 2 phones", "") + assert [(row.phone, row.joined, row.callsign, row.refusal) for row in preview.rows] == [ + ("Pretend Phone 7", "2026-11-01 09:00", "OTTER2", ""), + ("Pretend Phone 7", "2026-11-01 09:05", "OTTER3", ""), + ] + assert said == "Naming 2 phones." + assert [result.job for result in results] == [app.Job.NAME] + assert (rig.app.status, rig.app.lines) == ("2 phones named.", ("Phone a1 is OTTER2", "Phone a2 is OTTER3")) + rig.settle() + assert rig.app.lines, "the lines stay while the phones are listed again" + assert [row.callsign for row in rig.app.rows(NOW)] == ["OTTER2", "OTTER3", "OTTER1"] + assert fake.calls[-3:] == ["phones", "name", "phones"] + + +def test_the_list_is_kept_and_used_up(rig: Rig) -> None: + """Typed and saved before any phone joined; what was given is gone from it next time""" + rig.app.paste_settings(LINE, NOW) + rig.app.keep_callsigns("BEAR", rig.app.listed("BEAR7\n\n BEAR9 \nBEAR11\n")) + rig.connected() + + preview = rig.app.preview(["a2"], rig.app.conn.callsigns, NOW) + rig.app.name(preview.names) + rig.settle() + + assert rig.start().conn.callsigns == ["BEAR9", "BEAR11"] + assert rig.app.conn.prefix == "BEAR" + + +@pytest.mark.parametrize( + ("ids", "callsigns", "refusals", "batch"), + [ + (["a1", "a2"], ["BEAR1"], ["", "no callsign left in the list"], "2 phones to name, but only 1 callsign."), + (["a1", "a2"], ["BEAR1", "bear1"], ["", "bear1 is given twice"], ""), + (["a1", "a1"], ["BEAR1", "BEAR2"], ["", "phone a1 is named twice"], ""), + (["a1"], ["otter1"], ["otter1 already belongs to phone a3"], ""), + (["a1", "zz"], ["-BEAR", "BEAR2"], ["-BEAR: a callsign is 3-32", "phone zz is not in the group"], ""), + ([], ["BEAR1"], [], "No phone is waiting for a name. To give a phone another callsign, select it first."), + ], +) +def test_every_refusal_is_said_and_stops_the_naming( + rig: Rig, ids: list[str], callsigns: list[str], refusals: list[str], batch: str +) -> None: + rig.connected() + + preview = rig.app.preview(ids, callsigns, NOW) + + assert [row.refusal[: len(said)] for row, said in zip(preview.rows, refusals, strict=True)] == refusals + assert (preview.refusal, preview.ok) == (batch, False) + with pytest.raises( + app.AppError, match="Preview the callsigns first: nothing is named without a preview that passed." + ): + rig.app.name(dict(zip(ids, callsigns, strict=False))) + + +def test_only_the_names_previewed_are_given(rig: Rig) -> None: + rig.connected() + rig.app.preview(["a1"], ["BEAR1"], NOW) + + with pytest.raises(app.AppError, match="Preview the callsigns first"): + rig.app.name({"a1": "BEAR2"}) + rig.app.name({"a1": "BEAR1"}) + with pytest.raises(app.AppError, match="Preview the callsigns first"): + rig.app.name({"a1": "BEAR1"}) + + +def test_a_phone_that_just_joined_is_warned_of(rig: Rig) -> None: + fake = rig.connected() + just = (NOW - datetime.timedelta(minutes=4)).isoformat() + fake.group = [replace(phone, joined=just) for phone in PHONES] + rig.app.refresh() + rig.settle() + + one = rig.app.preview(["a1"], ["BEAR1"], NOW) + fake.group = [*PHONES[:2], replace(PHONES[2], joined=just)] + rig.app.refresh() + rig.settle() + single = rig.app.preview(["a1"], ["BEAR1"], NOW) + + assert one.warning == ( + "3 phones joined less than 10 minutes ago and may still be installing their apps. Naming now sends the " + "policy to every phone again, which stops apps that are still installing: wait until they have their apps." + ) + assert single.warning == ( + "A phone joined less than 10 minutes ago and may still be installing its apps. Naming now sends the " + "policy to every phone again, which stops apps that are still installing: wait until it has its apps." + ) + assert single.ok + + +def test_phones_changed_since_the_preview_name_nothing(rig: Rig) -> None: + fake = rig.connected() + preview = rig.app.preview(["a1"], ["BEAR1"], NOW) + fake.group = [replace(PHONES[1], callsign="BEAR1"), *PHONES[::2]] + + rig.app.name(preview.names) + [result] = rig.settle() + + assert result.error == "Nothing named: BEAR1 already belongs to phone a2. Refresh and give callsigns again." + assert "name" not in fake.calls + + +class Refusing(FakeMdm): + """Refuses after the first phone, as an MDM failing half-way does""" + + def __init__(self, values: Mapping[str, str]) -> None: + super().__init__(values, refuse_after=1) + + +def test_a_batch_stopped_half_way_says_what_it_named(rig: Rig) -> None: + rig.classes["fake"] = Refusing + rig.app.paste_settings(LINE, NOW) + rig.app.keep_callsigns("", ["BEAR1", "BEAR2", "BEAR3"]) + rig.connected() + + rig.app.name(rig.app.preview(["a1", "a2"], ["BEAR1", "BEAR2"], NOW).names) + [result] = rig.settle() + + assert result.named == {"a1": "BEAR1"} + assert rig.app.status == "The fake MDM refused phone a2 Named before it stopped: a1 as BEAR1." + assert rig.app.lines == ("Phone a1 is BEAR1",) + assert rig.app.conn.callsigns == ["BEAR2", "BEAR3"] + + +def test_the_lines_go_once_anything_else_is_said(rig: Rig) -> None: + rig.connected() + rig.app.name(rig.app.preview(["a1"], ["BEAR1"], NOW).names) + rig.settle() + assert rig.app.lines == ("Phone a1 is BEAR1",) + + rig.app.paste_settings(LINE, NOW) + + assert not rig.app.lines + + +def test_asking_again(rig: Rig) -> None: + fake = rig.connected() + fake.group[2] = replace(fake.group[2], state=State.REFUSED) + rig.app.refresh() + rig.settle() + + rig.app.ask_again(["a3"]) + rig.settle() + first = (rig.app.status, rig.app.lines) + said = rig.app.ask_again([]) + rig.settle() + + assert first == ("Asked again.", ("Phone a3: certificate asked for again",)) + assert said == "Asking every named phone whose certificate failed again." + assert (rig.app.status, rig.app.lines) == ("No phone needed asking again.", ()) + assert "ask_again" in fake.calls + + +def test_a_phone_with_its_certificate_is_not_asked_again(rig: Rig) -> None: + fake = rig.connected() + calls = len(fake.calls) + + with pytest.raises( + app.AppError, + match="Nothing to ask again: the selected phones have their certificates, or have no callsign yet.", + ): + rig.app.ask_again(["a3"]) + + assert len(fake.calls) == calls + assert not rig.app.detail("a3", NOW).can_ask_again + + +def test_a_phone_without_a_callsign_is_not_asked_again(rig: Rig) -> None: + fake = rig.connected() + fake.group[0] = replace(fake.group[0], state=State.FAILED) + rig.app.refresh() + rig.settle() + + with pytest.raises(app.AppError, match="Nothing to ask again"): + rig.app.ask_again(["a1"]) + + assert not rig.app.detail("a1", NOW).can_ask_again + + +def test_a_mixed_selection_asks_only_the_failed_again(rig: Rig) -> None: + fake = rig.connected() + fake.group[2] = replace(fake.group[2], state=State.WAITING) + rig.app.refresh() + rig.settle() + + said = rig.app.ask_again(["a1", "a2", "a3"]) + rig.settle() + + assert said == "Asking 1 phone again; 2 phones left alone." + assert rig.app.detail("a3", NOW).can_ask_again + assert (rig.app.status, rig.app.lines) == ("Asked again.", ("Phone a3: certificate asked for again",)) + + +class Broken(FakeMdm): + """Fails the way no MDM is meant to""" + + failure: ClassVar[type[Exception]] = RuntimeError + + def phones(self) -> list[Phone]: + raise self.failure("the token is pa55word") + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return ["Asked"] + + +class Unreachable(Broken): + failure = ConnectionRefusedError + + +@pytest.mark.parametrize( + ("broken", "says"), + [(Unreachable, "Cannot reach the MDM."), (Broken, "The MDM plugin failed; the log says more: ")], +) +def test_any_failure_is_one_sentence_and_the_worker_goes_on(rig: Rig, broken: type[FakeMdm], says: str) -> None: + rig.classes["fake"] = broken + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + rig.app.refresh() + [result] = rig.settle() + rig.app.ask_again([]) + rig.settle() + + assert result.error.startswith(says) + assert "Traceback" not in result.error + assert (rig.app.status, rig.app.lines) == ("Asked again.", ("Asked",)) + + +def test_a_settings_file_that_cannot_be_written_is_said(rig: Rig) -> None: + rig.app.store = store.Store(rig.directory / "settings.json" / "not-a-directory") + rig.directory.mkdir() + (rig.directory / "settings.json").write_text("{}", encoding="utf-8") + + with pytest.raises(app.AppError, match="cannot be written"): + rig.app.paste_settings(LINE, NOW) + assert rig.app.window is None + + +def test_a_listing_of_the_plugins_that_failed_is_said(rig: Rig) -> None: + rig.unlisted = plugins.PluginError("Two packages declare the MDM demo") + with pytest.raises(app.AppError, match="Two packages declare the MDM demo"): + rig.app.mdms() + + +def test_a_phones_detail(rig: Rig) -> None: + fake = rig.connected() + fake.group = [replace(PHONES[0], callsign="OTTER2", state=State.FAILED, detail="Fleet's own words")] + rig.app.refresh() + rig.settle() + + detail = rig.app.detail("a1", NOW) + + assert detail == app.Detail( + "a1", + "OTTER2", + "Pretend Phone 7", + "2026-11-01 09:00", + "failed", + "Fleet's own words", + "Deploy App unit.example.fi accepts phones until 14:00", + True, + ) + with pytest.raises(app.AppError, match="Phone zz is no longer in the MDM's list: refresh."): + rig.app.detail("zz", NOW) + + +def test_the_log_holds_no_secret(tmp_path: Path) -> None: + redact = app.Redact() + path = app.open_log(tmp_path / "logs", redact) + redact.add(CHALLENGE) + redact.add("") + try: + logging.getLogger("odmdm_connector.test").info("pasted %s", CHALLENGE) + try: + raise RuntimeError(f"challenge {CHALLENGE}") + except RuntimeError: + logging.getLogger("odmdm_connector.test").exception("failed") + finally: + handlers = [ + handler for handler in logging.getLogger().handlers if getattr(handler, "formatter", None) is redact + ] + for handler in handlers: + logging.getLogger().removeHandler(handler) + handler.close() + + text = path.read_text(encoding="utf-8") + assert CHALLENGE not in text + assert text.count("[secret]") == 2 + + +class Echoing(FakeMdm): + """An MDM whose answers repeat the secrets it was given""" + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step(f"Signed in with {self.values['password']}", True, f"challenge {window.challenge}") + raise MdmError(f"Refused {window.challenge} for {self.values['password']}") + + def set_challenge(self, window: Settings) -> None: + raise MdmError(f"Bad challenge {window.challenge}", lines=[f"password {self.values['password']}"]) + + def ask_again(self, ids: Sequence[str]) -> list[str]: + return [f"Asked with {self.values['password']}"] + + +def test_no_secret_reaches_the_operator_or_the_log(rig: Rig, tmp_path: Path) -> None: + rig.classes["fake"] = Echoing + terminal = io.StringIO() + stderr = logging.StreamHandler(terminal) + logging.getLogger().addHandler(stderr) + redact = app.Redact() + path = app.open_log(tmp_path / "logs", redact) + rig.app.redact = redact + try: + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + results = rig.settle() + statuses = [rig.app.status] + rig.app.paste_settings(LINE, NOW) + results += rig.settle() + statuses.append(rig.app.status) + rig.app.ask_again([]) + rig.settle() + finally: + for handler in [stderr, *(each for each in logging.getLogger().handlers if each.formatter is redact)]: + logging.getLogger().removeHandler(handler) + handler.close() + + shown = [ + *statuses, + *(result.error for result in results), + *(line for result in results for line in result.lines), + *(part for result in results for step in result.steps for part in (step.label, step.message)), + ] + assert statuses == ["Refused [secret] for [secret]", "Bad challenge [secret]"] + assert [step.label for result in results for step in result.steps] == ["Signed in with [secret]"] + for text in [*shown, path.read_text(encoding="utf-8"), terminal.getvalue()]: + assert CHALLENGE not in text + assert VALUES["password"] not in text + assert "[secret]" in terminal.getvalue() + assert rig.app.lines == ("Asked with [secret]",) + + +def test_the_app_on_this_computer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """Its settings file and log in one directory, here a temporary one, and the system's keychain""" + backend = MemoryBackend() + monkeypatch.setattr(store, "directory", lambda: tmp_path) + monkeypatch.setattr(store, "platform_backend", lambda: backend) + before = list(logging.getLogger().handlers) + + started = app.App.default() + try: + assert started.log_path == tmp_path / "odmdm-connector.log" + assert started.store.path == tmp_path / "settings.json" + assert (started.keychain.backend, started.keeps) == (backend, True) + finally: + started.close() + for handler in set(logging.getLogger().handlers) - set(before): + logging.getLogger().removeHandler(handler) + handler.close() + + +class HalfSetUp(FakeMdm): + """Stops its setup after the first step""" + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True) + raise MdmError("The fake MDM refused the template") + + +def test_a_setup_that_stops_shows_the_steps_done(rig: Rig) -> None: + rig.classes["fake"] = HalfSetUp + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + + [result] = rig.settle() + + assert (result.steps, result.error) == ((Step("Group found", True),), "The fake MDM refused the template") + assert rig.app.status == "The fake MDM refused the template" + + +class Unconfigurable(FakeMdm): + def __init__(self, values: Mapping[str, str]) -> None: + raise MdmError("The fake MDM needs a group") + + +def test_a_plugin_that_cannot_be_used_is_said(rig: Rig) -> None: + rig.connected() + rig.classes["fake"] = Unconfigurable + + with pytest.raises(app.AppError, match="The fake MDM needs a group"): + rig.app.connect("fake", VALUES) + later = rig.start() + with pytest.raises(app.AppError, match="The fake MDM needs a group"): + later.connect("fake", VALUES) + rig.refused = "The MDM fake cannot be loaded" + + assert later.mdm is None + with pytest.raises(app.AppError, match="The MDM fake cannot be loaded"): + rig.start().form("fake") + later.close() + + +def test_nothing_reaches_the_mdm_before_it_is_connected(rig: Rig) -> None: + rig.app.refresh() + + with pytest.raises(app.AppError, match="Connect to the MDM first."): + rig.app.name({}) + with pytest.raises(app.AppError, match="Connect to the MDM first."): + rig.app.ask_again([]) + assert not rig.app.busy() + + +def test_one_listing_at_a_time(rig: Rig) -> None: + """A refresh asked while one is under way is not queued behind it""" + fake = rig.connected() + fake.calls.clear() + + rig.app.refresh() + rig.app.refresh() + rig.settle() + + assert fake.calls == ["phones"] + + +def test_a_time_that_is_not_one_is_shown_as_it_is(rig: Rig) -> None: + fake = rig.connected() + fake.group = [replace(PHONES[0], joined="yesterday"), replace(PHONES[1], joined="2026-11-01T09:05:00")] + rig.app.refresh() + rig.settle() + + assert [row.joined for row in rig.app.rows(NOW)] == ["yesterday", "2026-11-01 09:05"] + assert not rig.app.preview(["a1"], ["BEAR1"], NOW).warning + + +class Expired(FakeMdm): + """Does not accept its password, as an MDM does once a token has ended""" + + def phones(self) -> list[Phone]: + raise MdmError("The fake MDM does not accept the password", unauthorized=True) + + +def test_a_secret_the_mdm_does_not_accept_is_typed_again(rig: Rig) -> None: + rig.connected() + rig.classes["fake"] = Expired + rig.app.connect("fake", VALUES) + rig.settle() + + rig.app.refresh() + [result] = rig.settle() + + assert result.unauthorized + assert (rig.app.connected, rig.app.phones, rig.app.summary()) == (False, [], "") + assert rig.app.status == "The fake MDM does not accept the password" + assert rig.app.form("fake").fields[1].value == "" + assert rig.app.connect("fake", VALUES) == "Setting Fake MDM up for Deploy App unit.example.fi." + + +def test_a_refusal_of_an_mdm_no_longer_held_lets_go_of_nothing(rig: Rig) -> None: + """The token was typed again while a listing with the old one was under way""" + rig.connected() + rig.classes["fake"] = Expired + rig.app.connect("fake", VALUES) + rig.settle() + rig.app.refresh() + rig.classes["fake"] = FakeMdm + rig.app.connect("fake", VALUES) + + rig.settle() + + assert rig.app.connected + assert rig.app.form("fake").fields[1].value == "pa55word" + + +@pytest.mark.parametrize("sender", ["", "https://unit.example.fi", "https://mtls.unit.example.fi"]) +def test_a_line_is_taken_from_its_own_deploy_app(rig: Rig, sender: str) -> None: + """Or typed by hand, which names no sender""" + assert rig.app.read_settings(LINE, NOW, sender).host == "unit.example.fi" + assert rig.app.paste_settings(LINE, NOW, sender) == "Deploy App unit.example.fi accepts phones until 14:00." + + +@pytest.mark.parametrize( + "sender", + [ + "https://other.example.fi", + "http://mtls.unit.example.fi", + "https://mtls.unit.example.fi:8443", + "https://evil.example.fi.unit.example.fi", + "https://unit.example.fi.evil.example", + "null", + ], +) +def test_a_line_sent_by_another_page_is_refused(rig: Rig, sender: str) -> None: + says = ( + f"These settings are for Deploy App unit.example.fi, but the page that sent them is {sender}: " + "use the button on that Deploy App's own MDM page." + ) + + for take in (rig.app.read_settings, rig.app.paste_settings): + with pytest.raises(app.AppError) as raised: + take(LINE, NOW, sender) + assert str(raised.value) == says + assert (rig.app.window, rig.app.saved) == (None, store.Saved()) + + +def test_a_remembered_token_connects_at_the_next_start(keyed: Rig) -> None: + assert keyed.app.keeps + keyed.connected() + keyed.app.paste_settings(OTHER, NOW) + keyed.app.connect("fake", {"group": "Other unit", "password": "0ther"}) # pragma: allowlist secret + keyed.settle() + assert keyed.backend is not None and keyed.backend.items[KEPT] == VALUES["password"] + keyed.app.close() + + keyed.app = keyed.start() + at_start = (keyed.app.status, keyed.app.connected) + opened = keyed.app.open("unit.example.fi", NOW) + + assert at_start == ("", True) + assert opened == "Deploy App unit.example.fi accepts phones until 14:00." + assert isinstance(keyed.app.mdm, FakeMdm) and keyed.app.mdm.values == VALUES + assert keyed.app.form("fake").fields[1].value == VALUES["password"] + keyed.app.close() + keyed.app = keyed.start() + assert keyed.app.paste_settings(LINE, NOW).endswith("Giving the MDM the new challenge."), "connected, no typing" + + +def test_the_keychain_is_read_once_until_the_token_changes(keyed: Rig, monkeypatch: pytest.MonkeyPatch) -> None: + """A keychain may ask the operator before it answers, and every request would wait for that""" + keyed.connected() + keyed.app.close() + backend = keyed.backend + assert backend is not None + reads: list[str] = [] + read = backend.get_password + + def counted(service: str, account: str) -> str | None: + reads.append(account) + return read(service, account) + + monkeypatch.setattr(backend, "get_password", counted) + keyed.app = keyed.start() + for _ in range(3): + assert [each.remembered for each in keyed.app.form("fake").fields] == [False, True] + keyed.app.banner(NOW) + assert reads == ["unit.example.fi:fake:password"] + + keyed.app.connect("fake", VALUES, remember=False) + keyed.settle() + reads.clear() + assert [[each.remembered for each in keyed.app.form("fake").fields] for _ in range(2)] == [[False, False]] * 2 + assert reads == ["unit.example.fi:fake:password"], "read once more after connecting" + + +def test_a_token_not_remembered_is_removed_from_the_keychain(keyed: Rig) -> None: + keyed.connected() + + said = keyed.app.connect("fake", VALUES, remember=False) + + assert keyed.backend is not None and keyed.backend.items == {} + assert said == "Setting Fake MDM up for Deploy App unit.example.fi." + assert keyed.app.connected, "held until the connector stops" + keyed.app.close() + keyed.app = keyed.start() + assert (keyed.app.status, keyed.app.connected) == ( + "Type the Password again to connect: it is not kept on this computer.", + False, + ) + + +def test_a_keychain_that_does_not_take_the_token_is_said(keyed: Rig) -> None: + assert keyed.backend is not None + keyed.backend.broken = True + keyed.app.paste_settings(LINE, NOW) + + said = keyed.app.connect("fake", VALUES) + + assert said == ( + "This computer's keychain cannot be used, so the Password is kept only until the connector stops. " + "Setting Fake MDM up for Deploy App unit.example.fi." + ) + # The page shows the line while the setup runs, beside a heading that already says what the sentence does + assert (keyed.app.status, keyed.app.lines) == ( + "Setting Fake MDM up for Deploy App unit.example.fi.", + ("This computer's keychain cannot be used, so the Password is kept only until the connector stops.",), + ) + assert keyed.app.connected + assert VALUES["password"] not in (keyed.directory / "settings.json").read_text(encoding="utf-8") + + +def test_a_token_the_mdm_does_not_accept_leaves_the_keychain(keyed: Rig) -> None: + keyed.connected() + keyed.classes["fake"] = Expired + keyed.app.connect("fake", VALUES) + keyed.settle() + + keyed.app.refresh() + keyed.settle() + + assert keyed.backend is not None and keyed.backend.items == {} + assert not keyed.app.connected + keyed.app.close() + keyed.app = keyed.start() + assert keyed.app.status == "Type the Password again to connect: it is not kept on this computer." + + +def test_removing_a_deploy_app_removes_its_kept_token(keyed: Rig) -> None: + keyed.connected() + + said = keyed.app.remove("unit.example.fi") + + assert said == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + assert keyed.backend is not None and keyed.backend.items == {} + + +@pytest.mark.parametrize("why", ["undeletable", "plugin gone"]) +def test_a_kept_token_that_cannot_be_removed_is_said(keyed: Rig, why: str) -> None: + keyed.connected() + assert keyed.backend is not None + if why == "undeletable": + keyed.backend.undeletable = True + else: + keyed.refused = "The MDM fake cannot be loaded" + + said = keyed.app.remove("unit.example.fi") + + assert said == ( + "Deploy App unit.example.fi is removed from this app, but its MDM token may still be in this computer's " + "keychain: delete the odmdm-connector item of unit.example.fi there by hand." + ) + assert keyed.app.saved == store.Saved() + + +def test_without_keyring_the_app_holds_the_token_for_the_session(rig: Rig, monkeypatch: pytest.MonkeyPatch) -> None: + """As in the one-file build, which leaves keyring out""" + monkeypatch.setitem(sys.modules, "keyring", None) + + def start() -> app.App: + keychain = store.Keychain(store.platform_backend()) + return app.App(store.Store(rig.directory), installed=rig.installed, load=rig.load, keychain=keychain) + + rig.app.close() + rig.app = start() + assert not rig.app.keeps + assert rig.connected().values == VALUES + rig.app.close() + rig.app = start() + assert (rig.app.status, rig.app.connected) == ( + "Type the Password again to connect: it is kept only while the connector runs.", + False, + ) + + +def test_a_setup_shows_its_steps_as_they_are_done(rig: Rig) -> None: + """A setup can take minutes, so each step is there to tick as soon as it is done, secrets blanked out""" + go = threading.Event() + + class Slow(FakeMdm): + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True, f"with {self.values['password']}") + go.wait(5) + yield Step("Certificate template stated", True) + + rig.classes["fake"] = Slow + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + for _ in range(500): + if rig.app.progress: + break + time.sleep(0.01) + + assert rig.app.progress == (Step("Group found", True, "with [secret]"),) + go.set() + (result,) = rig.settle() + assert [step.label for step in result.steps] == ["Group found", "Certificate template stated"] + + go.clear() + rig.app.connect("fake", VALUES) + assert rig.app.progress in ((), (Step("Group found", True, "with [secret]"),)), "the last setup's steps are gone" + go.set() + rig.settle() From b8c3b30c167acf24563b1445ba0ec5e245ba8b15 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 063/104] test: the page's server against the fake MDM --- tests/test_web.py | 750 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 750 insertions(+) create mode 100644 tests/test_web.py diff --git a/tests/test_web.py b/tests/test_web.py new file mode 100644 index 0000000..211c43e --- /dev/null +++ b/tests/test_web.py @@ -0,0 +1,750 @@ +"""The page's server against the fake MDM: on a free port in a thread, with http.client as the browser""" + +import http.client +import json +import logging +import socket +import threading +import time +from collections.abc import Iterator +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest + +from odmdm_connector import app, console, web +from odmdm_connector.mdm import ASK_AGAIN, State, Step +from odmdm_connector.settings import Settings +from odmdm_connector.testing import FakeMdm + +from .test_app import CHALLENGE, KEPT, LINE, NOW, TOKEN_VALUES, VALUES, Addressed, HalfSetUp, Rig +from .test_store import MemoryBackend + +Answer = tuple[int, http.client.HTTPMessage, bytes] + + +class WebRig(Rig): + """The App of test_app's Rig, and a clock for the page that the test moves""" + + def __init__(self, directory: Path, backend: MemoryBackend | None = None) -> None: + self.ticks = 0.0 + super().__init__(directory, backend) + + +class Served: + """The page on a free port, and a browser that has opened the address printed""" + + def __init__(self, rig: WebRig) -> None: + self.rig = rig + self.page = web.Page(rig.app, 0, now=lambda: NOW, clock=lambda: rig.ticks) + self.host = f"127.0.0.1:{self.page.port}" + self.origin = f"http://{self.host}" + self.key = self.page.key + #: Every answer's body, to look for secrets in + self.bodies: list[bytes] = [] + threading.Thread(target=self.page.serve_forever, args=(0.01,), daemon=True).start() + + def request(self, method: str, path: str, body: bytes | None = None, **headers: str) -> Answer: + sent = {"Host": self.host, "X-ODMDM-Key": self.key, **headers} + connection = http.client.HTTPConnection("127.0.0.1", self.page.port, timeout=5) + try: + connection.request(method, path, body, {name.replace("_", "-"): value for name, value in sent.items()}) + response = connection.getresponse() + answer = (response.status, response.msg, response.read()) + finally: + connection.close() + self.bodies.append(answer[2]) + return answer + + def post(self, path: str, body: Any = None, status: int = 200) -> Any: + given = json.dumps({} if body is None else body).encode() + got, _, data = self.request("POST", path, given, Origin=self.origin, Content_Type="application/json") + assert got == status, data + return json.loads(data) + + def state(self) -> Any: + self.rig.app.worker.wait() + status, _, data = self.request("GET", "/api/state") + assert status == 200, data + return json.loads(data) + + +def _served(rig: WebRig) -> Iterator[Served]: + made = Served(rig) + yield made + made.page.shutdown() + made.page.server_close() + made.rig.app.close() + + +@pytest.fixture +def served(tmp_path: Path) -> Iterator[Served]: + yield from _served(WebRig(tmp_path / "config")) + + +@pytest.fixture +def keyed(tmp_path: Path) -> Iterator[Served]: + """The page on a computer with a keychain""" + yield from _served(WebRig(tmp_path / "config", MemoryBackend())) + + +def test_nothing_under_api_is_answered_without_the_key_header(served: Served) -> None: + status, _, body = served.request("GET", "/api/state", X_ODMDM_Key="") + assert (status, body.decode()) == ( + 403, + "Open the address that the connector printed when it started. This page then goes on by itself.", + ) + assert served.request("GET", "/api/state", X_ODMDM_Key="wrong")[0] == 403 + assert served.request("GET", "/api/nothing", X_ODMDM_Key="")[0] == 403 + assert served.request("POST", "/api/refresh", b"{}", X_ODMDM_Key="", Origin=served.origin)[0] == 403 + assert served.request("GET", "/api/state")[0] == 200 + + +def test_the_key_is_in_the_fragment_and_never_a_cookie(served: Served) -> None: + """A browser sends a cookie for 127.0.0.1 to every port of it, and a fragment to no server""" + assert served.page.address == f"http://127.0.0.1:{served.page.port}/#key={served.page.key}" + status, headers, body = served.request("GET", f"/?key={served.page.key}", X_ODMDM_Key="") + assert (status, headers["Set-Cookie"], headers["Location"]) == (200, None, None) + assert body.startswith(b"") + assert served.request("GET", "/api/state", X_ODMDM_Key="", Cookie=f"odmdm={served.page.key}")[0] == 403 + + +def test_two_key_headers_are_refused(served: Served) -> None: + with socket.create_connection(("127.0.0.1", served.page.port), timeout=5) as raw: + raw.sendall( + f"GET /api/state HTTP/1.1\r\nHost: {served.host}\r\nX-ODMDM-Key: {served.key}\r\n" + f"X-ODMDM-Key: {served.key}\r\nConnection: close\r\n\r\n".encode() + ) + answer = raw.recv(4096) + assert answer.startswith(b"HTTP/1.0 403") + + +@pytest.mark.parametrize("path", ["/", "/?key=wrong", "/app.css", "/app.js"]) +def test_the_three_files_need_no_key(served: Served, path: str) -> None: + """They are public code, and the page explains itself to a browser that has no key yet""" + status, headers, _ = served.request("GET", path, X_ODMDM_Key="") + + assert (status, headers["Set-Cookie"]) == (200, None) + + +def test_the_server_header_names_the_connector_alone(served: Served) -> None: + assert served.request("GET", "/app.css")[1]["Server"] == "odmdm-connector" + + +@pytest.mark.parametrize("host", ["example.fi", "127.0.0.1", "127.0.0.1:1", "attacker.example.fi:8737"]) +def test_another_host_is_refused(served: Served, host: str) -> None: + assert served.request("GET", "/", Host=host)[0] == 403 + assert served.request("GET", "/app.js", Host=host)[0] == 403 + assert served.request("GET", "/api/state", Host=host)[0] == 403 + assert served.request("POST", "/api/refresh", b"{}", Host=host, Origin=served.origin)[0] == 403 + + +@pytest.mark.parametrize("second", ["{host}", "example.fi"]) +def test_two_host_headers_are_refused(served: Served, second: str) -> None: + with socket.create_connection(("127.0.0.1", served.page.port), timeout=5) as raw: + raw.sendall( + f"GET /api/state HTTP/1.1\r\nHost: {served.host}\r\nHost: {second.format(host=served.host)}\r\n" + f"X-ODMDM-Key: {served.key}\r\nConnection: close\r\n\r\n".encode() + ) + answer = raw.recv(4096) + assert answer.startswith(b"HTTP/1.0 403") + + +def test_localhost_is_this_computer_too(served: Served) -> None: + host = f"localhost:{served.page.port}" + status, _, data = served.request("POST", "/api/refresh", b"{}", Host=host, Origin=f"http://{host}") + assert (status, json.loads(data)) == (200, {}) + + +@pytest.mark.parametrize("origin", [None, "http://example.fi", "null", "https://127.0.0.1:8737"]) +def test_a_post_from_anywhere_but_the_page_is_refused(served: Served, origin: str | None) -> None: + headers = {"Origin": origin} if origin else {} + status, _, body = served.request("POST", "/api/add", json.dumps({"line": LINE}).encode(), **headers) + + assert (status, body.decode()) == (403, web.FORBIDDEN) + assert served.rig.app.saved.connections == {} + + +@pytest.mark.parametrize( + ("body", "headers", "says"), + [ + (b"{}", {"Content-Length": str(web.LIMIT + 1)}, "The request has no length or is too large."), + (b"{", {}, "The request is not a JSON object."), + (b"[1]", {}, "The request is not a JSON object."), + (b"\xff", {}, "The request is not a JSON object."), + (b"[" * 5000 + b"]" * 5000, {}, "The request is not a JSON object."), + (b"{}", {"Content-Length": "-1"}, "The request has no length or is too large."), + ], +) +def test_a_broken_or_oversized_body_is_refused(served: Served, body: bytes, headers: dict[str, str], says: str) -> None: + status, _, answer = served.request("POST", "/api/refresh", body, Origin=served.origin, **headers) + + assert (status, answer.decode()) == (400, says) + + +def test_a_value_of_the_wrong_kind_is_said(served: Served) -> None: + assert served.post("/api/read", {"line": 1}, 400) == {"error": "The page sent line as something other than text."} + assert served.post("/api/again", {"ids": "a1"}, 400) == { + "error": "The page sent ids as something other than a list of text." + } + assert served.post("/api/connect", {"mdm": "fake", "values": {"group": 1}}, 400) == { + "error": "The page sent the values as something other than text." + } + assert served.post("/api/connect", {"mdm": "fake", "values": VALUES, "remember": "yes"}, 400) == { + "error": "The page sent remember as something other than yes or no." + } + assert served.post("/api/name", {"names": ["a1"]}, 400) == { + "error": "The page sent the names as something other than text." + } + assert served.post("/api/name", {"names": {}, "save": "yes"}, 400) == { + "error": "The page sent save as something other than yes or no." + } + + +@pytest.mark.parametrize( + ("path", "kind", "starts"), + [ + ("/", "text/html; charset=utf-8", b""), + ("/app.css", "text/css; charset=utf-8", b"/*"), + ("/app.js", "text/javascript; charset=utf-8", b'"use strict";'), + ], +) +def test_the_three_files_and_their_headers(served: Served, path: str, kind: str, starts: bytes) -> None: + status, headers, body = served.request("GET", path) + + assert (status, headers["Content-Type"]) == (200, kind) + assert body.startswith(starts) + for name, value in web.HEADERS.items(): + assert headers[name] == value + + +@pytest.mark.parametrize( + "path", ["/index.html", "/static/app.js", "/../pyproject.toml", "/%2e%2e/web.py", "/api/nothing", "/web.py"] +) +def test_nothing_else_is_served(served: Served, path: str) -> None: + status, headers, _ = served.request("GET", path) + + assert status == 404 + assert headers["Content-Security-Policy"] == web.HEADERS["Content-Security-Policy"] + assert served.request("POST", path, b"{}", Origin=served.origin)[0] == 404 + + +def test_http_servers_own_refusals_are_plain_and_carry_the_headers(served: Served) -> None: + status, headers, body = served.request("PUT", "/api/state") + assert (status, body) == (501, b"Unsupported method ('PUT')") + assert headers["X-Content-Type-Options"] == "nosniff" + + with socket.create_connection(("127.0.0.1", served.page.port), timeout=5) as raw: + raw.sendall(b"GET / HTTP/1.1\r\nX: " + b"a" * 70000 + b"\r\n\r\n") + answer = raw.recv(4096) + assert answer.startswith(b"HTTP/1.0 431") and b"Cache-Control: no-store" in answer + + +def test_an_idle_connection_does_not_delay_an_answer(served: Served) -> None: + """A browser opens spare connections and leaves them idle until the timeout""" + with ( + socket.create_connection(("127.0.0.1", served.page.port), timeout=5), + socket.create_connection(("127.0.0.1", served.page.port), timeout=5), + ): + began = time.monotonic() + assert served.request("GET", "/api/state")[0] == 200 + assert time.monotonic() - began < web.TIMEOUT / 2 + + +@pytest.mark.parametrize("failure", [ConnectionResetError(54, "Connection reset by peer"), TimeoutError("timed out")]) +def test_a_dropped_connection_is_one_line_naming_its_kind( + served: Served, caplog: pytest.LogCaptureFixture, failure: OSError +) -> None: + caplog.set_level(logging.DEBUG) + try: + raise failure + except OSError: + served.page.handle_error(None, ("127.0.0.1", 1)) + + [record] = caplog.records + assert record.getMessage() == f"A connection to the page ended: {type(failure).__name__}" + assert record.exc_info is None + + +def test_a_request_that_failed_otherwise_is_logged_whole(served: Served, caplog: pytest.LogCaptureFixture) -> None: + try: + raise RuntimeError("a bug") + except RuntimeError: + served.page.handle_error(None, ("127.0.0.1", 1)) + + [record] = caplog.records + assert (record.getMessage(), record.exc_info is not None) == ("The page could not answer a request", True) + + +def test_the_app_sees_one_caller_at_a_time(served: Served, monkeypatch: pytest.MonkeyPatch) -> None: + inside, most = [0], [0] + approval = served.rig.app.approval + + def slow(name: str) -> str: + inside[0] += 1 + most[0] = max(most[0], inside[0]) + time.sleep(0.05) + inside[0] -= 1 + return approval(name) + + monkeypatch.setattr(served.rig.app, "approval", slow) + callers = [threading.Thread(target=served.post, args=("/api/form", {"mdm": "fake"})) for _ in range(4)] + for each in callers: + each.start() + for each in callers: + each.join() + + assert most == [1] + + +def test_the_whole_flow(served: Served) -> None: + first = served.state() + assert (first["connections"], first["active"], first["connected"], first["needs"]) == ([], "", False, "") + assert first["keeps"] is False, "no keychain on this computer" + assert (first["steps"], first["setup_error"]) == ([], "") + assert [mdm["name"] for mdm in first["mdms"]] == ["fake", "demo"] + + reading = served.post("/api/read", {"line": LINE}) + assert reading == { + "host": "unit.example.fi", + "until": "Deploy App unit.example.fi accepts phones until 14:00.", + "known": False, + } + assert served.state()["connections"] == [], "reading takes nothing" + + added = served.post("/api/add", {"line": LINE}) + state = served.state() + assert added == {"said": "Deploy App unit.example.fi accepts phones until 14:00."} + assert (state["active"], state["needs"], state["banner"], state["mdm_page"]) == ( + "unit.example.fi", + "mdm", + {"level": "open", "text": "Deploy App unit.example.fi accepts phones until 14:00"}, + "https://mtls.unit.example.fi/mdm", + ) + + form = served.post("/api/form", {"mdm": "fake"}) + assert (form["title"], [(each["key"], each["value"], each["secret"], each["kept"]) for each in form["fields"]]) == ( + "Fake MDM", + [("group", "Deploy App", False, False), ("password", "", True, False)], + ) + + connected = served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + state = served.state() + assert connected == {"said": "Setting Fake MDM up for Deploy App unit.example.fi."} + assert [step["label"] for step in state["steps"]] == [ + "Group Deploy App enrols at https://unit.example.fi/scep", + "Certificate template stated", + ] + state = served.state() + assert (state["connected"], state["needs"], state["summary"]) == (True, "", "3 phones: 1 ready, 2 without a name") + assert state["rows"][2] == { + "id": "a3", + "callsign": "OTTER1", + "phone": "Pretend Tablet 2", + "joined": "2026-11-01 09:10", + "certificate": "has its certificate", + "waiting": False, + "failed": False, + "ready": True, + "askable": False, + } + assert served.post("/api/form", {"mdm": "fake"})["fields"][1]["kept"] is True + + numbered = {"ids": [], "how": "numbered", "prefix": "OTTER", "first": "", "list": ""} + preview = served.post("/api/preview", numbered) + assert (preview["ok"], preview["button"], preview["first"]) == (True, "Name 2 phones", 2) + assert [(row["id"], row["callsign"]) for row in preview["rows"]] == [("a1", "OTTER2"), ("a2", "OTTER3")] + + named = served.post("/api/name", {"names": {"a1": "OTTER2", "a2": "OTTER3"}, "how": "numbered", "prefix": "OTTER "}) + served.state() + state = served.state() + assert named == {"said": "Naming 2 phones."} + assert (state["status"], state["lines"]) == ("2 phones named.", ["Phone a1 is OTTER2", "Phone a2 is OTTER3"]) + assert (state["prefix"], state["callsigns"]) == ("OTTER", []) + + again = served.post("/api/again", {"ids": ["a1"]}) + assert again == {"said": "Asking again."} + detail = served.post("/api/detail", {"id": "a1"}) + assert (detail["callsign"], detail["state"], detail["can_ask_again"]) == ( + "OTTER2", + "requested, waiting for the phone", + True, + ) + + assert served.post("/api/remove", {"host": "unit.example.fi"}) == { + "said": "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + } + assert served.state()["connections"] == [] + + +def test_naming_from_a_list_names_what_the_preview_held(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + listed = {"ids": ["a1"], "how": "list", "list": "BEAR1\n\n BEAR2 \nBEAR3"} + shown = served.post("/api/preview", listed) + assert (shown["ok"], shown["rows"][0]["callsign"]) == (True, "BEAR1") + + named = served.post("/api/name", {"names": {"a1": "BEAR1"}, "how": "list", "list": listed["list"], "save": True}) + served.state() + state = served.state() + + assert named == {"said": "Naming 1 phone."} + assert (state["prefix"], state["callsigns"]) == ("", ["BEAR2", "BEAR3"]), "kept, less what was named" + + +def test_a_list_is_kept_only_when_saved(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + served.post("/api/preview", {"ids": ["a1"], "how": "list", "list": "BEAR1\nBEAR2"}) + + served.post("/api/name", {"names": {"a1": "BEAR1"}, "how": "list", "list": "BEAR1\nBEAR2", "save": False}) + + assert served.state()["callsigns"] == [] + + +def test_only_the_preview_that_passed_is_named(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + unseen = {"names": {"a1": "BEAR1"}, "how": "list", "list": "BEAR1", "save": True} + first = "Preview the callsigns first: nothing is named without a preview that passed." + + assert served.post("/api/name", unseen, 400) == {"error": first} + refused = served.post("/api/preview", {"ids": ["a1"], "how": "list", "list": "OTTER1"}) + assert (refused["ok"], refused["rows"][0]["refusal"]) == (False, "OTTER1 already belongs to phone a3") + assert served.post("/api/name", {**unseen, "names": {"a1": "OTTER1"}}, 400) == {"error": first} + served.post("/api/preview", {"ids": ["a1"], "how": "list", "list": "BEAR1"}) + assert served.post("/api/name", {**unseen, "names": {"a1": "BEAR2"}}, 400) == {"error": first} + too_few = served.post("/api/preview", {"ids": ["a1", "a2"], "how": "list", "list": "BEAR1"}) + assert (too_few["ok"], too_few["refusal"]) == (False, "2 phones to name, but only 1 callsign.") + assert served.post("/api/preview", {"how": "numbered", "prefix": "BEAR", "first": "x"}, 400) == { + "error": "The first number must be a whole number." + } + assert served.state()["callsigns"] == [], "nothing kept from a refusal" + assert served.request("POST", "/api/keep", b"{}", Origin=served.origin)[0] == 404 + + +def test_a_kept_secret_is_used_without_going_to_the_page(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + + served.post("/api/connect", {"mdm": "fake", "values": {"group": "Deploy App", "password": ""}}) + served.state() + + assert isinstance(served.rig.app.mdm, FakeMdm) + assert served.rig.app.mdm.values == VALUES + + +def test_a_kept_secret_is_not_sent_with_another_address(served: Served) -> None: + """Whoever can post to the page cannot have the kept token sent to a host of their choosing""" + served.rig.classes["fake"] = Addressed + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": TOKEN_VALUES}) + served.state() + Addressed.made.clear() + before = served.rig.app.saved + + moved = {**TOKEN_VALUES, "mdm_url": "https://attacker.example.fi", "token": ""} + refused = served.post("/api/connect", {"mdm": "fake", "values": moved}, 400) + + assert refused == {"error": "Type the Token again: the settings changed."} + assert Addressed.made == [] + assert served.rig.app.saved == before + + +def test_a_plugin_is_approved_and_its_challenge_given_by_hand(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + + asked = served.post("/api/form", {"mdm": "demo"}) + assert asked["approval"].startswith("The MDM demo comes from the package odmdm-connector-demo 1.0.0") + assert served.post("/api/approve", {"mdm": "demo"}) == {} + assert served.post("/api/form", {"mdm": "demo"})["title"] == "Fake MDM" + + served.post("/api/connect", {"mdm": "demo", "values": VALUES}) + state = served.state() + assert [(step["label"], step["done"]) for step in state["steps"]] == [("The fake MDM cannot setup", False)] + assert state["setup_error"] == "" + assert (state["challenge_note"], state["challenge"]) == ("The fake MDM cannot set_challenge", CHALLENGE) + assert served.post("/api/again", {"ids": []}, 400) == {"error": "The fake MDM cannot ask_again"} + + +def test_opening_a_deploy_app_and_the_refusals(served: Served) -> None: + other = LINE.replace("unit.example.fi", "other.example.fi") + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.post("/api/add", {"line": other}) + + assert served.post("/api/read", {"line": LINE})["known"] is True + assert served.post("/api/open", {"host": "unit.example.fi"}) == { + "said": "Deploy App unit.example.fi accepts phones until 14:00." + } + state = served.state() + assert state["connections"] == [ + {"host": "unit.example.fi", "level": "open", "short": "enrolment open until 14:00", "active": True}, + {"host": "other.example.fi", "level": "open", "short": "enrolment open until 14:00", "active": False}, + ] + assert state["mdm_page"] == "https://mtls.unit.example.fi/mdm" + assert state["connected"] + assert served.post("/api/open", {"host": "nowhere.example.fi"}, 400) == { + "error": "There is no Deploy App nowhere.example.fi in this app." + } + assert served.post("/api/read", {"line": "not a line"}, 400)["error"].startswith("This is not a settings line") + + +def test_the_page_that_sent_a_line_is_checked(served: Served) -> None: + sent = {"line": LINE, "from": "https://mtls.unit.example.fi"} + forged = {"line": LINE, "from": "https://other.example.fi"} + + assert served.post("/api/read", sent)["host"] == "unit.example.fi" + assert served.post("/api/add", forged, 400)["error"].startswith( + "These settings are for Deploy App unit.example.fi, but the page that sent them is https://other.example.fi" + ) + assert served.state()["connections"] == [] + assert served.post("/api/add", sent) == {"said": "Deploy App unit.example.fi accepts phones until 14:00."} + + +def test_the_phones_are_refreshed_every_minute_while_the_page_asks(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + fake = served.rig.app.mdm + assert isinstance(fake, FakeMdm) + fake.calls.clear() + + served.state() + served.rig.ticks += web.REFRESH + served.state() + served.state() + + assert fake.calls == ["phones"] + assert served.post("/api/refresh") == {} + served.state() + assert fake.calls == ["phones", "phones"] + + +def test_the_state_says_when_the_phones_were_last_listed(served: Served) -> None: + assert served.state()["updated"] == "" + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + + assert served.state()["updated"] == "12:00" + served.post("/api/add", {"line": LINE.replace("unit.example.fi", "other.example.fi")}) + assert served.state()["updated"] == "", "not the other Deploy App's" + + +def test_a_failure_is_one_sentence_pointing_at_the_log(served: Served, monkeypatch: pytest.MonkeyPatch) -> None: + def broken(name: str) -> str: + raise RuntimeError("a bug") + + monkeypatch.setattr(served.rig.app, "approval", broken) + + assert served.post("/api/form", {"mdm": "fake"}, 500) == { + "error": f"The connector failed; the log says more: {served.rig.app.log_path}" + } + + +def test_no_answer_and_no_log_line_holds_a_secret(served: Served, caplog: pytest.LogCaptureFixture) -> None: + caplog.set_level(logging.DEBUG) + served.post("/api/read", {"line": LINE}) + served.post("/api/add", {"line": LINE}) + served.post("/api/form", {"mdm": "fake"}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + served.post("/api/add", {"line": LINE}) + state = served.state() + served.post("/api/detail", {"id": "a1"}) + served.post("/api/read", {"line": LINE.replace("2026", "1999")}, 400) + + assert isinstance(served.rig.app.mdm, FakeMdm) + assert served.rig.app.mdm.challenge == CHALLENGE, "the MDM takes the challenge by API" + assert state["challenge"] == "" + logged = "\n".join(record.getMessage() for record in caplog.records) + for secret in (VALUES["password"], CHALLENGE, LINE, served.page.key): + assert secret not in logged + assert all(secret.encode() not in body for body in served.bodies) + + +def _web(rig: WebRig, monkeypatch: pytest.MonkeyPatch, busy: bool = False) -> list[web.Page]: + """The web command will serve rig's App until a Ctrl+C, at once, with a job under way or none""" + monkeypatch.setattr(app.App, "default", lambda: rig.app) + monkeypatch.setattr(rig.app, "busy", lambda job=None: busy) + started: list[web.Page] = [] + + def serve(page: web.Page, poll_interval: float = 0.5) -> None: + started.append(page) + raise KeyboardInterrupt + + monkeypatch.setattr(web.Page, "serve_forever", serve) + return started + + +def _free_port() -> int: + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port: int = probe.getsockname()[1] + return port + + +def test_the_web_command_prints_where_and_how_to_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + started = _web(WebRig(tmp_path / "config"), monkeypatch) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + printed = capsys.readouterr() + assert printed.out.splitlines() == [ + f"Open this address in your browser: http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert not printed.err + + +def test_ctrl_c_during_a_job_says_what_to_do_next( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """The MDM may be half way through it, and the phones' rows are from before""" + _web(WebRig(tmp_path / "config"), monkeypatch, busy=True) + + assert console.main(["web", "--port", str(_free_port())]) == 0 + assert capsys.readouterr().err == f"{console.STOPPED_BUSY}\n" + + +def test_the_web_command_says_when_the_port_is_taken( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + rig = WebRig(tmp_path / "config") + monkeypatch.setattr(app.App, "default", lambda: rig.app) + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + port = taken.getsockname()[1] + + code = console.main(["web", "--port", str(port)]) + + said = capsys.readouterr().err + assert code == 1 + assert said.startswith(f"The page cannot listen on port {port} of this computer: ") + assert said.endswith(". Give another with --port.\n") + + +def test_the_web_command_says_the_connector_may_be_running_when_its_own_port_is_taken( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Deploy App's button reaches the default port only, so another port is not the first advice""" + rig = WebRig(tmp_path / "config") + monkeypatch.setattr(app.App, "default", lambda: rig.app) + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + monkeypatch.setattr(web, "PORT", taken.getsockname()[1]) + + code = console.main(["web"]) + + said = capsys.readouterr().err + assert code == 1 + assert "The connector may be running already: use its page." in said + assert said.endswith("as Deploy App's button reaches this port.\n") + + +def test_after_a_restart_the_token_is_typed_again_and_the_phones_listed(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + again = served.rig.start() + + page = web.Page(again, 0) + try: + needs = page.state()["needs"] + said = page.connect({"mdm": "fake", "values": VALUES}) + again.worker.wait() + again.drain() + assert needs == "secret" + assert said == {"said": "Connected to Fake MDM for Deploy App unit.example.fi."} + assert [row.id for row in again.rows(NOW)] == ["a1", "a2", "a3"], "listed once connected" + finally: + page.server_close() + again.close() + + +def test_a_failed_setup_is_said_beside_its_steps(served: Served) -> None: + served.post("/api/add", {"line": LINE}) + served.rig.classes["fake"] = HalfSetUp + + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + state = served.state() + + assert [step["label"] for step in state["steps"]] == ["Group found"] + assert (state["setup_error"], state["connected"]) == ("The fake MDM refused the template", True) + served.rig.classes["fake"] = FakeMdm + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + assert served.state()["setup_error"] == "", "a new setup starts with no error" + + +def test_a_running_setups_steps_are_in_the_state_as_they_are_done(served: Served) -> None: + """A setup can take minutes: the page ticks each step when it is done, not all of them at the end""" + go = threading.Event() + + class Slow(FakeMdm): + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True) + go.wait(5) + yield Step("Certificate template stated", True) + + served.post("/api/add", {"line": LINE}) + served.rig.classes["fake"] = Slow + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + running: Any = {} + for _ in range(500): + running = json.loads(served.request("GET", "/api/state")[2]) + if running["steps"]: + break + time.sleep(0.01) + + assert ([step["label"] for step in running["steps"]], "setup" in running["busy"]) == (["Group found"], True) + go.set() + done = served.state() + assert [step["label"] for step in done["steps"]] == ["Group found", "Certificate template stated"] + assert "setup" not in done["busy"] + + +def test_the_token_is_kept_in_the_keychain_only_when_remembered(keyed: Served) -> None: + backend = keyed.rig.backend + assert backend is not None and keyed.state()["keeps"] is True + keyed.post("/api/add", {"line": LINE}) + + keyed.post("/api/connect", {"mdm": "fake", "values": VALUES, "remember": True}) + remembered = dict(backend.items) + said = [(each["kept"], each["remembered"]) for each in keyed.post("/api/form", {"mdm": "fake"})["fields"]] + keyed.post("/api/connect", {"mdm": "fake", "values": {"group": "Deploy App", "password": ""}}) + + assert remembered == {KEPT: VALUES["password"]} + assert said == [(False, False), (True, True)] + assert backend.items == {}, "remember left out is not remembered, and the kept copy goes" + assert keyed.post("/api/form", {"mdm": "fake"})["fields"][1]["remembered"] is False, ( + "held until the connector stops" + ) + assert keyed.state()["connected"] is True + + +@pytest.mark.parametrize(("mdm", "askable"), [(FakeMdm, True), (FakeMdm.lacking(ASK_AGAIN), False)]) +def test_the_phones_say_which_have_their_certificates_and_which_asking_again_can_help( + served: Served, mdm: type[FakeMdm], askable: bool +) -> None: + served.rig.classes["fake"] = mdm + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + fake = served.rig.app.mdm + assert isinstance(fake, FakeMdm) + fake.group = [replace(fake.group[0], callsign="OTTER2", state=State.REFUSED), *fake.group[1:]] + served.post("/api/refresh") + + rows = [(row["id"], row["ready"], row["askable"]) for row in served.state()["rows"]] + + assert rows == [("a1", False, askable), ("a2", False, False), ("a3", True, False)] From 043bd6d073e4100a2b452e97f62a6f28d8129fed Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:50 +0200 Subject: [PATCH 064/104] test: runtime code imports only the standard library, and keyring in one module --- tests/test_standard_library.py | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 tests/test_standard_library.py diff --git a/tests/test_standard_library.py b/tests/test_standard_library.py new file mode 100644 index 0000000..fab4be1 --- /dev/null +++ b/tests/test_standard_library.py @@ -0,0 +1,53 @@ +"""The connector needs Python and nothing else, and runs from inside a zip file + +So it goes into a network without internet as one file, see README.rst. Its one dependency, keyring, +reaches the system's keychain for the MDM token, is imported in store.py alone, and the connector +runs without it. +""" + +import ast +import sys +from pathlib import Path + +import pytest + +PACKAGE = Path(__file__).parent.parent / "src" / "odmdm_connector" +MODULES = sorted(PACKAGE.rglob("*.py")) +#: The one module that may import something else, and what +ALLOWED = {PACKAGE / "store.py": {"keyring"}} + + +def _nodes(path: Path) -> list[ast.AST]: + return list(ast.walk(ast.parse(path.read_text(encoding="utf-8"), str(path)))) + + +def test_every_module_is_checked() -> None: + assert PACKAGE / "app.py" in MODULES + assert PACKAGE / "testing" / "contract.py" in MODULES + + +@pytest.mark.parametrize("path", MODULES, ids=lambda path: path.relative_to(PACKAGE).as_posix()) +def test_runtime_code_imports_only_the_standard_library(path: Path) -> None: + imported: set[str] = set() + for node in _nodes(path): + if isinstance(node, ast.Import): + imported.update(alias.name.split(".")[0] for alias in node.names) + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + imported.add(node.module.split(".")[0]) + + assert imported - sys.stdlib_module_names - {"odmdm_connector"} - ALLOWED.get(path, set()) == set() + + +@pytest.mark.parametrize("path", MODULES, ids=lambda path: path.relative_to(PACKAGE).as_posix()) +def test_a_shipped_file_is_read_through_importlib_resources(path: Path) -> None: + """Never beside __file__, which is no directory when the package runs from a zip""" + assert "__file__" not in {node.id for node in _nodes(path) if isinstance(node, ast.Name)} + + +def test_keyring_is_imported_only_when_the_keychain_is_asked_for() -> None: + """Never when the module is, so that the connector runs without keyring""" + body = ast.parse((PACKAGE / "store.py").read_text(encoding="utf-8")).body + imported = {alias.name for node in body if isinstance(node, ast.Import) for alias in node.names} + imported |= {node.module or "" for node in body if isinstance(node, ast.ImportFrom)} + + assert not {name for name in imported if name.split(".")[0] == "keyring"} From dd0138cbccbbcf289450289190a273f6b2ba3435 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:51 +0200 Subject: [PATCH 065/104] build: keyring as the one dependency, and a coverage floor of 88% --- pyproject.toml | 11 +++-------- uv.lock | 51 +++----------------------------------------------- 2 files changed, 6 insertions(+), 56 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 559a0b6..7e80f0f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,19 +1,14 @@ [project] name = "odmdm-connector" version = "1.1.0+261121" -description = "Connects FleetDM to an OpenDefence deployment's SCEP device enrolment" +description = "Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, ] license = "MIT" readme = "README.rst" requires-python = ">=3.11,<4.0" -dependencies = [ - "libadvian>=1.4,<2.0", - "click>=8.1,<9.0", - "httpx>=0.28,<1.0", - "keyring>=25.6,<26.0", -] +dependencies = ["keyring>=25.6,<26.0"] [project.urls] homepage = "https://github.com/pvarki/python-odmdm-fleet" @@ -106,7 +101,7 @@ disallow_untyped_decorators=false junit_family="xunit2" # The demo plugin, a package of its own, runs its contract tests here from its source pythonpath=["examples/odmdm-connector-demo/src"] -addopts="--cov=odmdm_connector --cov-fail-under=65 --cov-branch" +addopts="--cov=odmdm_connector --cov-fail-under=88 --cov-branch" [tool.coverage.run] omit = ["tests/*"] diff --git a/uv.lock b/uv.lock index 28ff603..42c1862 100644 --- a/uv.lock +++ b/uv.lock @@ -21,8 +21,8 @@ name = "anyio" version = "4.15.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "idna" }, - { name = "typing-extensions", marker = "python_full_version < '3.15'" }, + { name = "idna", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, + { name = "typing-extensions", marker = "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a9/d2/f4d173e22df740bc37b1db102b386ba719b66e95b0f0d751f556b387e6d2/anyio-4.15.1.tar.gz", hash = "sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94", size = 276966, upload-time = "2026-09-05T10:42:39.44Z" } wheels = [ @@ -553,19 +553,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] -[[package]] -name = "httpcore" -version = "1.0.9" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "certifi" }, - { name = "h11" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, -] - [[package]] name = "httpcore2" version = "2.16.0" @@ -579,21 +566,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, ] -[[package]] -name = "httpx" -version = "0.28.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "anyio" }, - { name = "certifi" }, - { name = "httpcore" }, - { name = "idna" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, -] - [[package]] name = "httpx2" version = "2.16.0" @@ -723,15 +695,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0a/28/7ded071d0975dcc6d5d106ffbf7b3ca420f7caa3b8a235fa604b6e37032a/lazy_importer-0.1.0-py3-none-any.whl", hash = "sha256:bd93fab7bef18e842eea02b839410954d37889140dc64ca4d9680aec6880c739", size = 12580, upload-time = "2026-10-20T00:36:57.176Z" }, ] -[[package]] -name = "libadvian" -version = "1.9.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/f2/e9/86ce7c1ffb486abe8506909a8c41db6da2de9703a0326a10178b205d47ae/libadvian-1.9.0.tar.gz", hash = "sha256:97c78963cb08a70d856be409faa3c9f9bb088787d036dfce68b8e449a199b736", size = 14334, upload-time = "2025-05-23T13:38:27.089Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c4/47/95f5435cd98c9fe52a8bfaeeaade1fc97ec75ee86f05c054c67b122af5d4/libadvian-1.9.0-py3-none-any.whl", hash = "sha256:2461145e0980c9af95480f063d565c01cd68f52c90f19818ec5efbc537d1f702", size = 16085, upload-time = "2025-05-23T13:38:26.018Z" }, -] - [[package]] name = "librt" version = "0.16.0" @@ -942,10 +905,7 @@ name = "odmdm-connector" version = "1.1.0+261121" source = { editable = "." } dependencies = [ - { name = "click" }, - { name = "httpx" }, { name = "keyring" }, - { name = "libadvian" }, ] [package.dev-dependencies] @@ -964,12 +924,7 @@ dev = [ ] [package.metadata] -requires-dist = [ - { name = "click", specifier = ">=8.1,<9.0" }, - { name = "httpx", specifier = ">=0.28,<1.0" }, - { name = "keyring", specifier = ">=25.6,<26.0" }, - { name = "libadvian", specifier = ">=1.4,<2.0" }, -] +requires-dist = [{ name = "keyring", specifier = ">=25.6,<26.0" }] [package.metadata.requires-dev] dev = [ From 593c8483c4fb423df17aa8f60ffde688aabb26f2 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:51 +0200 Subject: [PATCH 066/104] ci: build the one-file connector with the demo plugin and check that it runs without keyring --- .github/workflows/pull_request.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index c562997..667ea0f 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -81,6 +81,22 @@ jobs: cat plugin.txt grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' plugin.txt grep -Eq '^d1 +- +Pretend Phone 7' phones.txt + # The one file README.rst describes for a network without internet, run by a Python with nothing installed + - name: One file with the demo plugin inside, on Python 3.11 + run: | + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl dist/odmdm_connector_demo-*.whl + bare() { uv run --no-project --isolated --python 3.11 python "$@"; } + bare -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o dist/odmdm-connector.pyz + bare dist/odmdm-connector.pyz --version + # Built without keyring: the file runs, and has no keychain + bare -c "import sys; sys.path.insert(0, 'dist/odmdm-connector.pyz'); from odmdm_connector import store; assert store.platform_backend() is None" + bare dist/odmdm-connector.pyz mdms | tr -d '\r' | tr -s ' ' | tee pyz-mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' pyz-mdms.txt + grep -Fqx 'demo odmdm-connector-demo 1.0.0 plugin' pyz-mdms.txt + bare dist/odmdm-connector.pyz --mdm demo phones 2> pyz-plugin.txt | tee pyz-phones.txt + cat pyz-plugin.txt + grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' pyz-plugin.txt + grep -Eq '^d1 +- +Pretend Phone 7' pyz-phones.txt snyk-test: name: Run Snyk test From 5d4daaa4d0435560a7d9970159d1e7669bf8d8e1 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:51 +0200 Subject: [PATCH 067/104] docs: the page, the keychain, the one file and the command line as they are --- README.rst | 161 ++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 147 insertions(+), 14 deletions(-) diff --git a/README.rst b/README.rst index 5adc295..6461ae5 100644 --- a/README.rst +++ b/README.rst @@ -2,7 +2,7 @@ odmdm-connector =============== -Connects FleetDM to an OpenDefence deployment's device enrolment. +Connects an MDM, FleetDM built in, to an OpenDefence deployment's device enrolment. The deployment knows no MDM. It answers standard SCEP (RFC 8894) at ``https:///scep``, asks for a challenge that is new every time an admin opens enrolment in Deploy App, and makes the @@ -23,7 +23,123 @@ installed too:: uv tool install git+https://github.com/pvarki/python-odmdm-fleet odmdm-connector --help -From a checkout, ``uv tool install .`` does the same. +From a checkout, ``uv tool install .`` does the same. Installed this way it brings its one +dependency, keyring, which keeps the MDM token in this computer's keychain: Windows Credential +Manager, the macOS Keychain, or the Secret Service on Linux. + +The page +-------- + +The connector's everyday face is a page in your browser, served by this computer. Start it, and +open the address it prints:: + + odmdm-connector web + +It goes on until Ctrl+C. ``--port N`` serves it on another port than 8737. The connector starts no +browser: open the address yourself. A page opened without it says so, and goes on by itself once the +address has been opened in the same browser. + +The first time, the page sets up one thing at a time, on cards under a bar of three parts: Deploy +App, the MDM, Connect. Have at hand Deploy App's MDM page, open as an admin, your MDM's address and +an API token for it. Add the Deploy App: on its MDM page press **Open in the MDM connector**, or +copy its settings line and paste it into the page, and confirm it. Choose the MDM when more than one +is installed, then fill in what it asks, one field to a card: for Fleet its address, an API token +and the team, with the rarely changed ones under **More settings**. **Connect** sets the MDM up and +ticks off its steps; it says what is left to do by hand, if anything, or why it failed, and **Show +the phones** goes on. + +The daily work is one view of the phones, as wide as the window. At the top, whether Deploy App +accepts phones now and until when; once enrolment has closed, **Open Deploy App** opens its MDM page +in a new tab. Under it one row of buttons, the ways to select, and the table: each phone's ID, +callsign, model, when it joined and where its certificate is. Click a row to select it, and +double-click it, or select one and press **Details**, to see that phone alone. The line at the +bottom says what was done last and, at its right end, when the phones were last listed: every +minute while the page is open, or at once with **Refresh**. **Settings** shows the MDM's +settings, whether its token is kept on this computer, and where the log is. The Deploy App's name +at the top right lists the Deploy Apps added, opens another, adds one or removes the one open. +Each Deploy App needs a Fleet of its own: the shipped template names one certificate +authority for every Deploy App, and the connector refuses to point an authority that serves one +Deploy App at another. + +For every batch: open enrolment in Deploy App and press **Open in the MDM connector** again, or +**New settings** and paste the line, so the MDM gets the new challenge. Let the phones enrol, then +**Give callsigns**, to the phones selected or else to every phone waiting for a name: numbered or +from a list. The preview below follows what you type, and **Name** names exactly the preview +shown, once it has passed. **Ask again** asks refused or failed phones for their certificates +again once the cause is fixed. + +The MDM token is never in the settings file, the log or the page. With **Remember on this +computer** ticked, as it is at first, it is kept in this computer's keychain, under +``odmdm-connector``, and the page connects to the MDM at the next start without asking for it. +Without a keychain, as in the one file, the page says the token is kept only until the connector +stops, and asks for it after a restart: then it shows the phones of the MDM set up before, without +new settings from Deploy App. It asks for it the same way, with the MDM's reason, when the MDM no +longer accepts it, and removes the copy kept. + +To stop keeping the token on this computer, connect again with **Remember on this computer** +unticked, or remove the Deploy App: either removes it from the keychain. If the keychain does not +let it be removed, the page says so: delete the ``odmdm-connector`` item of that Deploy App there by +hand. + +What guards the page: + +- It listens on this computer only (127.0.0.1), and answers only a request addressed to this + computer (its Host header), so that a web page elsewhere cannot reach it through DNS rebinding. +- Its three files are public code. Everything else answers only a page that carries the key the + address printed at start holds, new at every start. The key is in the address's fragment, after + ``#``, which a browser sends to no server. The page takes it out of the address, keeps it only + once the connector accepts it, so that a page elsewhere cannot put a wrong one in its place, and + sends it with each request in a header of its own, never in a cookie, which a browser would also send to every + other program listening on this computer. +- The browser keeps exactly one thing, that key, in the page's own storage, so that every tab of + the page has it. It is worthless once the connector stops. Nothing else is ever kept there. The + browser's history also keeps the address you opened, key and all; that matters only while the + connector runs, as the next start makes a new key. +- A request that changes something must come from the page itself (its Origin header). +- **Open in the MDM connector** opens the page and hands it the settings line in a message, never in + the address. The page takes a line only from the page that opened it, and the connector only from + that Deploy App's own pages, ``https://`` or ``https://mtls.``. + +Its limits: + +- The button in Deploy App talks to whatever listens on port 8737 of this computer. On a computer + that other users share, one of them could listen there first and take the settings line: copy the + line by hand instead. A program that listens on port 8737 while the connector is not running can + also send the Deploy App tab that opened it elsewhere. +- Any web page can open the connector and offer a Deploy App of its own: read the Deploy App's name + on the confirm card before pressing **Add**. +- Another program on this computer can slow the page down, but without the key it can neither read + nor drive it. A program that runs as you can read the key from your browser's storage, as it can + read anything else of yours. + +Into a network without internet +------------------------------- + +The connector runs on Python's standard library alone, so it can be carried in as one file. On the +other computer it needs Python 3.11 or newer, and nothing else. The file leaves keyring out, so it +has no keychain: the MDM token is asked for at each start, and kept only until the connector stops. + +Build the file from a checkout, on a computer that has uv. The wheel goes into the file whole, with +its metadata, which is how the connector finds Fleet and any plugin:: + + uv build --wheel --out-dir dist + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl + python3 -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o dist/odmdm-connector.pyz + +A plugin goes into the same file: build its wheel and name it in the same install line, after the +connector's. Start from an empty ``build/pyz`` each time, or what was installed there before stays in +the file. + +Copy ``dist/odmdm-connector.pyz`` across and run it as the command, ``py`` in place of ``python3`` on +Windows:: + + python3 odmdm-connector.pyz --version + python3 odmdm-connector.pyz mdms + python3 odmdm-connector.pyz web + +An MDM whose certificate comes from a private authority is trusted by pointing the +``SSL_CERT_FILE`` environment variable at that authority's certificate file, in PEM form, before +the connector starts. Enrolling phones ---------------- @@ -156,10 +272,15 @@ in the package, is a working one for Deploy App, with its reasoning in the comme The certificate subject is the contract with the deployment. Its common name becomes the callsign: 3 to 32 letters, digits or hyphens, no hyphen at either end. It is the name ``name`` gives the -phone, optionally followed by Fleet's id for the host, and the tool refuses any other:: +phone, followed by Fleet's id for the host, and the tool refuses any other:: - CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID + CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART + +The shipped template uses the first: the id lets the deployment tell later which device a callsign +was issued to. A subject cannot change on a team that has phones, since replacing the certificate +template removes every phone's certificate, so a team set up without the id keeps the second form +in a template of its own. A name the phone supplies, such as its serial number, would make a leaked enrolment link enough for an identity. @@ -178,17 +299,20 @@ separated by whitespace:: ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z 1. The mark ``ODMDM1``. -2. The SCEP URL. It must be https. +2. The SCEP URL, ``https:///`` and nothing else: no user name, password, port, query, + fragment or backslash. Deploy App writes ``https:///scep``. 3. The challenge: 32 lowercase hex characters. It is a secret, and the tool never prints or logs it. 4. When the enrolment window closes, in UTC, as ``YYYY-MM-DDTHH:MM:SSZ``. Whitespace and line breaks before and after the line are ignored. A line with another mark or -another number of fields, a URL that is not https, a malformed challenge or time, or a window that -has already closed is refused. A value with whitespace inside it is read as a line, never as a -bare challenge, so a damaged paste is refused instead of being sent to Fleet. ``challenge`` takes -the line at its prompt, from ``--challenge`` or from ``ODMDM_CHALLENGE``, refuses one whose SCEP -URL is not on ``ODMDM_DOMAIN``, and says until when the window is open. The line above is the -shared test vector, in ``tests/data/settings-line-v1.txt``. +another number of fields, a URL that is not just https, a host and a path, a malformed challenge or +time, or a window that has already closed is refused. A line that a page hands to the connector is +taken only from that Deploy App's own pages, ``https://`` or ``https://mtls.``; one +typed or pasted by hand names no page. A value with whitespace inside it is read as a line, never +as a bare challenge, so a damaged paste is refused instead of being sent to Fleet. ``challenge`` +takes the line from ``ODMDM_CHALLENGE``, else at its hidden prompt, never as an argument; it refuses +one whose SCEP URL is not on ``ODMDM_DOMAIN``, and says until when the window is open, in this +computer's time. The line above is the shared test vector, in ``tests/data/settings-line-v1.txt``. The order that works -------------------- @@ -217,6 +341,10 @@ What Fleet does that you would not guess launcher and leaves the old one orphaned. Google refuses a title of 30 characters or more. - **A web app's display name is unique within a team** (409). A title in a team's setup experience has to be removed there before it can be removed from the team. +- **A token copied from a signed-in account ends with that sign-in.** **My account → Get API token** + gives the token of your own session, which Fleet ends after five days by default, or when you + sign out. The connector then says the token is not accepted. For a connector that stays set up, + give the token of an API-only user (``fleetctl user create --api-only``), which does not end. - **A phone enrols before it has a name**, so its first certificate request fails (``does not have an IDP user``) until it is named, and naming it does not send the request again. ``name`` resends. A resend is one more attempt, which the phone acts on at its next check-in, every 15 @@ -245,15 +373,20 @@ A plugin is one class that satisfies ``Mdm`` in ``src/odmdm_connector/mdm.py``, library only: - ``API_VERSION = 1``, a ``title``, the ``fields`` it needs (each a ``Field``; mark a token - ``secret``) and ``missing``: for each of ``setup``, ``set_challenge`` and ``ask_again`` it cannot - do, the sentence the operator reads instead. + ``secret``, one that must be given ``required``, and one rarely changed ``advanced``, which the + window shows only when asked) and ``missing``: for each of ``setup``, + ``set_challenge`` and ``ask_again`` it cannot do, the sentence the operator reads instead. - ``__init__(values)`` takes the fields' values by key. - ``setup(window, force, dry_run)`` yields ``Step`` objects; ``set_challenge(window)``; ``phones()`` answers ``Phone`` objects, oldest first, each with a ``State``; ``name(names)`` and ``ask_again(ids)`` answer the lines to show. - It raises only ``MdmError``. One that stops half-way through ``name`` says in ``named`` which phones it had already named, and in ``lines`` the lines already due to the operator, such as an - old callsign to revoke, which are shown before the error. + old callsign to revoke, which are shown before the error. One raised because the MDM does not + accept the secret it was given, such as a token that has ended, sets ``unauthorized``: the + connector then lets go of that secret, the copy in the keychain too, and asks for it again. +- Its sentences, in ``missing``, a ``Step``, the lines and an ``MdmError``, are shown as they are + by the command line and the window alike, so they name no command, option or button. Publish it as ``odmdm-connector-``, depending on ``odmdm-connector>=1.1,<2``, with the class under the entry point group ``odmdm_connector.mdm``:: From ee8966d12514d30842ede219062a2ea4857acfed Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:51 +0200 Subject: [PATCH 068/104] docs: the rules for the page and its key, and the one dependency --- AGENTS.md | 100 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 98 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 49fad6e..3dc8c46 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,86 @@ The connector starts no process and runs no code it was given: ruff bans `subpro `conftest.py` at the root makes every way to start a process raise for the whole test run. A missing feature is not a reason to shell out. +## One dependency: keyring, for the token + +Runtime code under `src/` imports nothing but Python's standard library and the package itself, +with one exception: `store.py` imports keyring, inside `platform_backend()`, to keep the MDM token in +the system's keychain. Nothing else uses keyring, and the connector must run without it: the +one-file build leaves it out, and there `platform_backend()` is None and the token is held until the +connector stops. `tests/test_standard_library.py` fails on any other import, and on keyring anywhere +but there; CI runs the one file without it. The owner decided on 2026-11-21 first that the connector +goes into a network without internet as one file with no dependencies (README.rst, "Into a network +without internet"), as every dependency is one more thing to carry in and keep up, and then: "We +may have a dependency to manage the token." The operating systems' keychains cannot be reached from +the standard library without starting a process. The connector departs from the organisation's +Python template, which uses click and libadvian: the command line is argparse and Fleet is reached +with urllib. A file the package ships is read through `importlib.resources`, never beside `__file__`, +so that it is found inside the zip too. A missing feature is not a reason to add a dependency: say +it is missing and let the owner decide. Development tools are not runtime code and stay in the `dev` +group. + +## The page + +`web.py` serves the connector as a page on the operator's computer; `static/` holds its three files. +The page draws what `App` answers and decides nothing: a rule that a test of `App` cannot reach does +not belong in `web.py` or `app.js`. Setting up is a row of cards, one thing each, with a bar of three +parts (Deploy App, the MDM's title, Connect) during a first set-up; the daily work is one view of +the phones in the earlier desktop window's layout, with the browser's own `dialog` element for +giving callsigns, one phone, the settings and removing a Deploy App. Keep these when changing either: + +- Standard library only, no framework, no library and no build step: three static files. + `ThreadingHTTPServer` bound to 127.0.0.1, a daemon thread per connection, so that a connection a + browser leaves idle holds nothing up. `Page.lock` is held around every call into `App`, the state + and every action, so `App` sees one caller at a time; the static files take no lock. No timer: + `Page.state()` asks for the phones once `web.REFRESH` seconds have passed, so they are listed only + while a page is open and asking, and never beside a request. +- Every request: the Host header is `127.0.0.1:` or `localhost:` (no DNS rebinding). + The three files in `STATIC` are public code and need nothing more, so that a browser without the + key gets a page that says what to do; `/` reads no query. Everything under `/api/` carries one + header `X-ODMDM-Key` that equals the key, compared with `secrets.compare_digest`. Never a cookie: + a browser sends a cookie for 127.0.0.1 to every port of it, so any program listening on another + port would receive the key as soon as a web page sends the browser there. Every POST: the Origin + is the page's own and the body a JSON object of at most 64 kB. GET changes nothing. +- Every answer carries `web.HEADERS`: no caching, a Content-Security-Policy of `'self'` only, no + framing, no sniffing, no referrer. Hence no inline script or style, and no external resource. +- Only the three files in `STATIC` are served, by a fixed table. No path from a request reaches the + file system. +- No request log on the terminal: the first request's address holds the key. Failures go to the + app's log. +- The page builds elements with `createElement` and text nodes, never `innerHTML` with anything from + the server. The browser keeps exactly one thing, the page's key, in `localStorage`, which a + browser keeps apart for each port, so that every tab of the page has it; it is worthless once the + connector stops. Nothing else may ever be kept there: no other storage, no cookie. Every sentence it + shows comes from an answer; `app.js` adds labels, headings, the lines of the Add card that say + where Deploy App's button is, that it opens a new tab and what to have at hand, the Remove + dialog's line on what removing changes, and the sentences for a connector that refuses this + browser or does not answer. A tab waits for Deploy App only when Deploy App's button opened it, + and a card that holds nothing typed follows a Deploy App added, opened or connected in another + tab. Focus starts in the first field, else on the main button; in the Remove dialog and on the + confirm card for a new Deploy App, on Cancel. The picture of Deploy App's button on the Add card + is no control: a `span`, hidden from assistive technology. Each card and each dialog is a form whose + main button submits it; a button that cannot act is disabled, not hidden. +- Deploy App's MDM page is the address `App.mdm_page` hands in the state, opened in a new tab with + `rel="noopener noreferrer"`; the page makes no address of its own. +- A secret, the token, the settings line or the challenge, is a text input masked by the style + (`-webkit-text-security`), never `type=password`, so that no password manager offers to keep it + and sync it away. +- A settings line arrives by window message from the page that opened this one, never in the + address: the page takes it only when `event.source` is `window.opener`, and passes the message's + origin to `/api/read` and `/api/add` as `from`, where `App` takes a line only from its own Deploy + App's pages. A line typed or pasted has an empty `from`. +- `/api/name` sends the names the preview shown held, and `App` names them only if they are the + last preview that passed. The page asks for one preview at a time, a moment after the typing + stops, and shows only the answer to the last one asked; **Name** waits while one is asked. + Nothing previews again behind the operator's back. +- No answer holds the MDM token or the settings line. A secret field's value never goes to the + page: left empty, the kept one is used. The challenge is answered only where `App.challenge()` + gives it, for an MDM given it by hand. +- Known limits: the button in Deploy App talks to whatever listens on port 8737 of this computer, + so on a computer shared with other users the settings line is copied by hand instead. Another + program on this computer can slow the page down, but cannot read or drive it without the key. +- The connector opens no browser; `web` prints the address. + ## Facts measured against a live Fleet Comments in `fleet.py` say what each request shape and wait was measured against. Keep that habit: @@ -52,7 +132,7 @@ strands every enrolled phone's key. ## Commands - Setup: `uv sync` -- Test: `uv run pytest` (coverage floor: 65%, set in `pyproject.toml`). Needs no network, no Fleet +- Test: `uv run pytest` (coverage floor: 88%, set in `pyproject.toml`). Needs no network, no Fleet and no phone. - Hooks, before every commit: `uv run prek run --all-files`. Once per clone: `uv run prek install --hook-type pre-commit --hook-type commit-msg` @@ -67,6 +147,22 @@ strands every enrolled phone's key. The chosen plugin gets it in memory; `FleetPlugin` hands it to `FleetMdm`, which sends it only as the `Authorization` header to the MDM URL. A plugin from another package sees it too, so the command line names that package on stderr before loading it. -- The tool never logs it, prints it, takes it as an option or argument, or writes it to a file. +- The page takes it typed, and `App` holds it in memory, by Deploy App, MDM and field, until the + connector stops. With "Remember on this computer" ticked and a keychain at hand (`App.keeps`), it + is kept in the keychain too, service `odmdm-connector`, account `::`, through + the one keyring back end `store.platform_backend()` names for the system and sets as keyring's, so + that neither `PYTHON_KEYRING_BACKEND`, keyring's configuration file nor another back end installed + chooses where it goes. A secret is looked for in memory first, then in the keychain. Connecting + with remember off, removing the Deploy App and the MDM refusing it (`MdmError.unauthorized`) all + remove the kept copy; there is no other way to forget it. Whatever a back end raises is "the + keychain did not answer", logged by its kind only. Never a plaintext fallback. +- The tool never logs it, prints it, takes it as an option or argument, or writes it to a file: only + the keychain keeps it. Keep it that way: no `--token` option, no token in an environment variable, no token in an error message. `.gitignore` ignores `*.token` so a token file in the checkout cannot be committed. +- **The page's key**, made at start by `odmdm-connector web` and printed once, in the address's + fragment (`/#key=…`), which a browser sends to no server: whoever has it drives the connector and + so the MDM. `app.js` takes it out of the address, keeps it in `localStorage` only once + `/api/state` accepts it (any web page can send the browser to the address with a wrong one), and + sends it only as the `X-ODMDM-Key` header to the page's own `/api/`. Never log it, never put it in + an answer, never in a cookie or a query. From 7b63aa53c1ea4d19d7d32264edebf85890bb74c1 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 17:35:54 +0200 Subject: [PATCH 069/104] chore: bump version to 1.2.0+261121 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/odmdm_connector/__init__.py | 2 +- tests/test_odmdm_connector.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index fc587d6..c1c1995 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.1.0+261121" +current_version = "1.2.0+261121" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index 7e80f0f..b21cce3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "1.1.0+261121" +version = "1.2.0+261121" description = "Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index ac0f708..15a69a7 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ """Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" -__version__ = "1.1.0+261121" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.2.0+261121" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index 184ed0b..895773d 100644 --- a/tests/test_odmdm_connector.py +++ b/tests/test_odmdm_connector.py @@ -5,4 +5,4 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.1.0+261121" + assert __version__ == "1.2.0+261121" diff --git a/uv.lock b/uv.lock index 42c1862..00c1d12 100644 --- a/uv.lock +++ b/uv.lock @@ -902,7 +902,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "1.1.0+261121" +version = "1.2.0+261121" source = { editable = "." } dependencies = [ { name = "keyring" }, From c40293a799e24224b60f307deccd143f1a29cefe Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 20:56:05 +0200 Subject: [PATCH 070/104] feat: open the page in the browser at start, through a file that keeps its key out of any program's arguments --- pyproject.toml | 5 +- src/odmdm_connector/browser.py | 75 +++++++++++++++ src/odmdm_connector/console.py | 16 +++- tests/test_browser.py | 168 +++++++++++++++++++++++++++++++++ tests/test_web.py | 76 ++++++++++++++- 5 files changed, 332 insertions(+), 8 deletions(-) create mode 100644 src/odmdm_connector/browser.py create mode 100644 tests/test_browser.py diff --git a/pyproject.toml b/pyproject.toml index b21cce3..b7f20cc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,6 +55,9 @@ extend-select = ["TID251", "S102", "S307"] # The guard that makes those raise during the tests, and its test "conftest.py" = ["TID251"] "tests/test_no_processes.py" = ["TID251"] +# The one exception, decided by the owner: the web command opens the page in the default browser. +# The address goes through a file only the user can read, so the key is in no program's arguments. +"src/odmdm_connector/browser.py" = ["TID251"] [tool.ruff.lint.flake8-tidy-imports.banned-api] "subprocess".msg = "The connector starts no process" @@ -62,7 +65,7 @@ extend-select = ["TID251", "S102", "S307"] "asyncio.create_subprocess_shell".msg = "The connector starts no process" "multiprocessing".msg = "The connector starts no process" "pty".msg = "The connector starts no process" -"webbrowser".msg = "Opening a browser starts a process" +"webbrowser".msg = "Opening a browser starts a process: only browser.py opens the browser" "os.system".msg = "The connector starts no process" "os.popen".msg = "The connector starts no process" "os.fork".msg = "The connector starts no process" diff --git a/src/odmdm_connector/browser.py b/src/odmdm_connector/browser.py new file mode 100644 index 0000000..2bc12a0 --- /dev/null +++ b/src/odmdm_connector/browser.py @@ -0,0 +1,75 @@ +"""Opening the page in the operator's default browser: the one place the connector starts a process + +The address holds the page's key, and on Linux and macOS a program's arguments can be read by other +users of the computer. So the address is never handed to the system's opener: a small file in the +connector's own directory, which only the user can read, leads on to it, and the opener is given +that file's path alone. The file holds the key while the connector runs and is removed when it stops. +""" + +import html +import logging +import os +import sys +import webbrowser +from pathlib import Path + +LOGGER = logging.getLogger(__name__) + +#: The file in the connector's directory that leads on to the page's address +NAME = "open-page.html" + + +def _desktop() -> bool: + """Whether there is a desktop to open a browser on; without one, webbrowser starts a text browser in the terminal""" + if sys.platform in ("win32", "darwin"): + return True + return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")) + + +def _page(address: str) -> str: + escaped = html.escape(address, quote=True) + return ( + "\n" + '\n' + '\n' + f'\n' + "odmdm-connector\n" + f'

Open the connector\'s page

\n' + ) + + +def _write(path: Path, address: str) -> None: + """The file anew, readable only by the user: one left from an earlier start is removed first""" + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + path.unlink(missing_ok=True) + handle = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as written: + written.write(_page(address)) + + +def open_page(address: str, directory: Path) -> bool: + """Ask the default browser to open the address, through a file in the directory; whether it was asked + + Raises nothing that writing the file or starting a browser raises: the connector starts whether + or not a browser opens. + """ + if not _desktop(): + return False + path = directory / NAME + try: + _write(path, address) + if webbrowser.open(path.as_uri()): + return True + LOGGER.warning("No browser could be asked to open the page") + except (OSError, ValueError, webbrowser.Error) as exc: + LOGGER.warning("The browser could not be asked to open the page: %s", type(exc).__name__) + remove(directory) + return False + + +def remove(directory: Path) -> None: + """Remove the file, if it is there; never raises""" + try: + (directory / NAME).unlink(missing_ok=True) + except OSError as exc: + LOGGER.warning("The file %s could not be removed: %s", directory / NAME, type(exc).__name__) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 650e65f..1d73ca7 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -19,13 +19,16 @@ from odmdm_connector import __version__ -from . import core, plugins, settings, web +from . import browser, core, plugins, settings, store, web from .app import App from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError from .settings import Settings #: Said when ODMDM_LOG_LEVEL is not a number LOG_LEVEL = "ODMDM_LOG_LEVEL must be a whole number, such as 10 for debug or 20 for info: change it, or unset it." +#: Said before the page's address, when a browser was asked to open it and when not +OPENING = "The connector's page is opening in your browser. If it does not, open this address:" +OPEN = "Open this address in your browser:" #: Said when Ctrl+C stops the page while a job is under way STOPPED_BUSY = "Stopped while the MDM was still being worked with: refresh the phones when the connector runs again." @@ -354,9 +357,11 @@ def mdms(args: argparse.Namespace) -> int: def page(args: argparse.Namespace) -> int: """Serve the connector as a page that only this computer can open, until Ctrl+C - Open the address it prints: it holds a key that the page needs. It opens no browser itself. + The page opens in your default browser; if it does not, open the address it prints: it holds a + key that the page needs. """ started = App.default() + directory = store.directory() try: try: server = web.Page(started, args.port) @@ -371,7 +376,10 @@ def page(args: argparse.Namespace) -> int: raise _Failed( f"The page cannot listen on port {args.port} of this computer: {exc.strerror}. {advice}" ) from exc - print(f"Open this address in your browser: {server.address}") + if args.browser and browser.open_page(server.address, directory): + print(f"{OPENING} {server.address}") + else: + print(f"{OPEN} {server.address}") print("Press Ctrl+C to stop it.", flush=True) with server: try: @@ -380,6 +388,7 @@ def page(args: argparse.Namespace) -> int: if started.busy(): print(STOPPED_BUSY, file=sys.stderr) finally: + browser.remove(directory) started.close() return 0 @@ -474,4 +483,5 @@ def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) sub.add_argument( "--port", type=_between(1, 65535), default=web.PORT, help="The port on 127.0.0.1 (default: %(default)s)" ) + sub.add_argument("--no-browser", dest="browser", action="store_false", help="Only print the address") return parser diff --git a/tests/test_browser.py b/tests/test_browser.py new file mode 100644 index 0000000..daf8569 --- /dev/null +++ b/tests/test_browser.py @@ -0,0 +1,168 @@ +"""Opening the page in the default browser, with the opener replaced so that no test starts anything""" + +import html +import os +import stat +import sys +from pathlib import Path +from urllib.parse import urlparse +from urllib.request import url2pathname + +import pytest + +from odmdm_connector import browser + +KEY = "k3y-of_the.page" +ADDRESS = f"http://127.0.0.1:8737/#key={KEY}&x=<\"'>" + + +class Opener: + """The opener: what it was handed, and its answer or what it raises""" + + def __init__(self, answer: bool = True, raises: Exception | None = None) -> None: + self.answer, self.raises = answer, raises + self.handed: list[str] = [] + + def __call__(self, url: str, new: int = 0, autoraise: bool = True) -> bool: + self.handed.append(url) + if self.raises is not None: + raise self.raises + return self.answer + + +@pytest.fixture +def desktop(monkeypatch: pytest.MonkeyPatch) -> None: + """A Linux computer with a desktop""" + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.setenv("DISPLAY", ":0") + monkeypatch.delenv("WAYLAND_DISPLAY", raising=False) + + +def _opener(monkeypatch: pytest.MonkeyPatch) -> Opener: + made = Opener() + monkeypatch.setattr("webbrowser.open", made) + return made + + +def test_the_opener_gets_a_file_that_leads_on_to_the_address( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + opener = _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path / "config") + + [handed] = opener.handed + assert KEY not in handed, "only the file's path reaches another program's arguments" + assert urlparse(handed).scheme == "file" + path = Path(url2pathname(urlparse(handed).path)) + assert path == tmp_path / "config" / browser.NAME + text = path.read_text(encoding="utf-8") + assert html.escape(ADDRESS, quote=True) in text + assert ADDRESS not in text, "escaped for HTML" + assert 'http-equiv="refresh"' in text + assert " None: + _opener(monkeypatch) + + browser.open_page(ADDRESS, tmp_path) + + assert stat.S_IMODE((tmp_path / browser.NAME).stat().st_mode) == 0o600 + + +def test_a_file_left_from_an_earlier_start_is_replaced( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + left = tmp_path / browser.NAME + left.write_text("the earlier key", encoding="utf-8") + if os.name == "posix": + left.chmod(0o644) + _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path) + + assert "the earlier key" not in left.read_text(encoding="utf-8") + if os.name == "posix": + assert stat.S_IMODE(left.stat().st_mode) == 0o600 + + +@pytest.mark.parametrize("display", ["DISPLAY", "WAYLAND_DISPLAY"]) +def test_either_display_is_a_desktop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None, display: str +) -> None: + monkeypatch.delenv("DISPLAY") + monkeypatch.setenv(display, "wayland-0") + opener = _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path) + assert len(opener.handed) == 1 + + +def test_without_a_desktop_nothing_is_written_or_opened( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + monkeypatch.delenv("DISPLAY") + opener = _opener(monkeypatch) + + assert not browser.open_page(ADDRESS, tmp_path) + assert opener.handed == [] + assert list(tmp_path.iterdir()) == [] + + +@pytest.mark.parametrize("platform", ["win32", "darwin"]) +def test_windows_and_macos_always_have_a_desktop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, platform: str +) -> None: + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.delenv("DISPLAY", raising=False) + monkeypatch.delenv("WAYLAND_DISPLAY", raising=False) + opener = _opener(monkeypatch) + + assert browser.open_page(ADDRESS, tmp_path) + assert len(opener.handed) == 1 + + +@pytest.mark.parametrize( + "opener", + [Opener(answer=False), Opener(raises=OSError(2, "No such file")), Opener(raises=ValueError("embedded null byte"))], + ids=["says no", "cannot start", "refuses the path"], +) +def test_when_no_browser_is_asked_the_file_is_gone_and_the_answer_is_no( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None, opener: Opener +) -> None: + monkeypatch.setattr("webbrowser.open", opener) + + assert not browser.open_page(ADDRESS, tmp_path) + assert len(opener.handed) == 1 + assert not (tmp_path / browser.NAME).exists() + + +def test_a_file_that_cannot_be_written_is_no(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None) -> None: + blocked = tmp_path / "a file, not a directory" + blocked.write_text("", encoding="utf-8") + opener = _opener(monkeypatch) + + assert not browser.open_page(ADDRESS, blocked) + assert opener.handed == [] + + +def test_remove_takes_the_file_away_and_is_quiet_when_it_is_not_there( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, desktop: None +) -> None: + _opener(monkeypatch) + browser.open_page(ADDRESS, tmp_path) + + browser.remove(tmp_path) + browser.remove(tmp_path) + + assert not (tmp_path / browser.NAME).exists() + + +def test_remove_says_in_the_log_when_it_cannot(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: + (tmp_path / browser.NAME).mkdir() + + browser.remove(tmp_path) + + assert f"The file {tmp_path / browser.NAME} could not be removed" in caplog.text diff --git a/tests/test_web.py b/tests/test_web.py index 211c43e..5f1bf83 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -4,6 +4,7 @@ import json import logging import socket +import sys import threading import time from collections.abc import Iterator @@ -13,7 +14,7 @@ import pytest -from odmdm_connector import app, console, web +from odmdm_connector import app, browser, console, store, web from odmdm_connector.mdm import ASK_AGAIN, State, Step from odmdm_connector.settings import Settings from odmdm_connector.testing import FakeMdm @@ -570,8 +571,13 @@ def test_no_answer_and_no_log_line_holds_a_secret(served: Served, caplog: pytest def _web(rig: WebRig, monkeypatch: pytest.MonkeyPatch, busy: bool = False) -> list[web.Page]: - """The web command will serve rig's App until a Ctrl+C, at once, with a job under way or none""" + """The web command will serve rig's App until a Ctrl+C, at once, with a job under way or none + + The connector's directory is rig's, and no browser is asked unless a test says so. + """ monkeypatch.setattr(app.App, "default", lambda: rig.app) + monkeypatch.setattr(store, "directory", lambda: rig.directory) + monkeypatch.setattr(browser, "open_page", lambda address, directory: False) monkeypatch.setattr(rig.app, "busy", lambda job=None: busy) started: list[web.Page] = [] @@ -605,6 +611,65 @@ def test_the_web_command_prints_where_and_how_to_stop( assert not printed.err +#: The real browser.open_page, which _web replaces +OPEN_PAGE = browser.open_page + + +def _opener(rig: WebRig, monkeypatch: pytest.MonkeyPatch, answer: bool = True) -> list[tuple[str, bool]]: + """The web command asks the browser through browser.open_page, on a desktop, of an opener that answers + + What the opener was handed, and whether the file was there then. + """ + handed: list[tuple[str, bool]] = [] + + def opener(url: str, new: int = 0, autoraise: bool = True) -> bool: + handed.append((url, (rig.directory / browser.NAME).is_file())) + return answer + + monkeypatch.setattr(browser, "open_page", OPEN_PAGE) + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr("webbrowser.open", opener) + return handed + + +def test_the_web_command_opens_the_page_in_the_browser_by_default( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + rig = WebRig(tmp_path / "config") + started = _web(rig, monkeypatch) + handed = _opener(rig, monkeypatch) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + + assert handed == [((rig.directory / browser.NAME).as_uri(), True)] + assert started[0].key not in handed[0][0] + assert capsys.readouterr().out.splitlines() == [ + f"{console.OPENING} http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert not (rig.directory / browser.NAME).exists(), "removed when the connector stops" + + +@pytest.mark.parametrize("given", [[], ["--no-browser"]], ids=["the browser says no", "--no-browser"]) +def test_without_a_browser_asked_the_address_is_printed_to_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], given: list[str] +) -> None: + rig = WebRig(tmp_path / "config") + started = _web(rig, monkeypatch) + handed = _opener(rig, monkeypatch, answer=False) + port = _free_port() + + assert console.main(["web", *given, "--port", str(port)]) == 0 + + assert len(handed) == (0 if given else 1) + assert capsys.readouterr().out.splitlines() == [ + f"{console.OPEN} http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert not (rig.directory / browser.NAME).exists() + + def test_ctrl_c_during_a_job_says_what_to_do_next( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: @@ -619,7 +684,9 @@ def test_the_web_command_says_when_the_port_is_taken( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: rig = WebRig(tmp_path / "config") - monkeypatch.setattr(app.App, "default", lambda: rig.app) + _web(rig, monkeypatch) + rig.directory.mkdir(parents=True, exist_ok=True) + (rig.directory / browser.NAME).write_text("left from an earlier start", encoding="utf-8") with socket.socket() as taken: taken.bind(("127.0.0.1", 0)) taken.listen() @@ -631,6 +698,7 @@ def test_the_web_command_says_when_the_port_is_taken( assert code == 1 assert said.startswith(f"The page cannot listen on port {port} of this computer: ") assert said.endswith(". Give another with --port.\n") + assert not (rig.directory / browser.NAME).exists(), "removed when the server could not start too" def test_the_web_command_says_the_connector_may_be_running_when_its_own_port_is_taken( @@ -638,7 +706,7 @@ def test_the_web_command_says_the_connector_may_be_running_when_its_own_port_is_ ) -> None: """Deploy App's button reaches the default port only, so another port is not the first advice""" rig = WebRig(tmp_path / "config") - monkeypatch.setattr(app.App, "default", lambda: rig.app) + _web(rig, monkeypatch) with socket.socket() as taken: taken.bind(("127.0.0.1", 0)) taken.listen() From 23f5c173c648bf9fc025903d33ead8dee45a1967 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 20:56:36 +0200 Subject: [PATCH 071/104] docs: the browser opens the page at start, through a file, and when it does not --- AGENTS.md | 18 ++++++++++++++++-- README.rst | 17 ++++++++++++----- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3dc8c46..f0ece44 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,16 @@ The connector starts no process and runs no code it was given: ruff bans `subpro `conftest.py` at the root makes every way to start a process raise for the whole test run. A missing feature is not a reason to shell out. +The one exception, decided by the owner on 2026-11-21: `web` opens the page in the default browser +through `src/odmdm_connector/browser.py`, the only module ruff lets import `webbrowser` +(`per-file-ignores` in `pyproject.toml`); it starts nothing else. The address holds the page's key, +and on Linux and macOS a program's arguments can be read by other users of the computer, so the +address never goes to the opener: `browser.py` writes `open-page.html` into `store.directory()`, +mode 0600, which leads on to the address, and hands the opener that file's `file:` URI. Without a +desktop (no `DISPLAY` or `WAYLAND_DISPLAY` outside Windows and macOS) it opens nothing, as +`webbrowser` would start a text browser in the terminal. Tests replace the opener with a fake; +`conftest.py` still makes `webbrowser.open` raise in every test. + ## One dependency: keyring, for the token Runtime code under `src/` imports nothing but Python's standard library and the package itself, @@ -116,7 +126,9 @@ giving callsigns, one phone, the settings and removing a Deploy App. Keep these - Known limits: the button in Deploy App talks to whatever listens on port 8737 of this computer, so on a computer shared with other users the settings line is copied by hand instead. Another program on this computer can slow the page down, but cannot read or drive it without the key. -- The connector opens no browser; `web` prints the address. +- `web` opens the page in the default browser through `browser.py` only, and prints the address; + `--no-browser` only prints it. Deploy App's button finds the page only in the browser where the + address was opened. ## Facts measured against a live Fleet @@ -165,4 +177,6 @@ strands every enrolled phone's key. so the MDM. `app.js` takes it out of the address, keeps it in `localStorage` only once `/api/state` accepts it (any web page can send the browser to the address with a wrong one), and sends it only as the `X-ODMDM-Key` header to the page's own `/api/`. Never log it, never put it in - an answer, never in a cookie or a query. + an answer, never in a cookie, a query or another program's arguments. +- **`open-page.html`** in `store.directory()`: it holds the address, key and all, while the + connector runs, so it is written mode 0600 and removed in the `web` command's `finally`. diff --git a/README.rst b/README.rst index 6461ae5..63d8b7e 100644 --- a/README.rst +++ b/README.rst @@ -30,14 +30,18 @@ Manager, the macOS Keychain, or the Secret Service on Linux. The page -------- -The connector's everyday face is a page in your browser, served by this computer. Start it, and -open the address it prints:: +The connector's everyday face is a page in your browser, served by this computer. Start it:: odmdm-connector web -It goes on until Ctrl+C. ``--port N`` serves it on another port than 8737. The connector starts no -browser: open the address yourself. A page opened without it says so, and goes on by itself once the -address has been opened in the same browser. +It opens the page in your default browser and prints its address, and goes on until Ctrl+C. +``--port N`` serves it on another port than 8737. The browser does not open by itself on a computer +without a desktop, with ``--no-browser``, or when the default browser may not read the connector's +own folder, as a browser installed as a snap on Linux cannot: then open the address it prints +yourself. A page opened without that address says so, and goes on by itself once the address has +been opened in the same browser. Deploy App's button finds the page only in the browser where the +address was opened, so use Deploy App in your default browser, or open the address in the browser +you use Deploy App in. The first time, the page sets up one thing at a time, on cards under a bar of three parts: Deploy App, the MDM, Connect. Have at hand Deploy App's MDM page, open as an admin, your MDM's address and @@ -91,6 +95,9 @@ What guards the page: once the connector accepts it, so that a page elsewhere cannot put a wrong one in its place, and sends it with each request in a header of its own, never in a cookie, which a browser would also send to every other program listening on this computer. +- The address never goes to another program: to open the browser, the connector writes a small file + that leads on to it into its own folder, which only you can read, and hands the browser that + file. The file holds the key while the connector runs and is removed when it stops. - The browser keeps exactly one thing, that key, in the page's own storage, so that every tab of the page has it. It is worthless once the connector stops. Nothing else is ever kept there. The browser's history also keeps the address you opened, key and all; that matters only while the From add67ced16073211dbb479de10990e1d45c2f5cb Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 21:08:10 +0200 Subject: [PATCH 072/104] test: browser.py imports nothing but what opening a browser needs, as ruff's ban is off there --- AGENTS.md | 6 ++- pyproject.toml | 2 + tests/test_no_processes.py | 93 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 100 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index f0ece44..ff36c9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,11 @@ feature is not a reason to shell out. The one exception, decided by the owner on 2026-11-21: `web` opens the page in the default browser through `src/odmdm_connector/browser.py`, the only module ruff lets import `webbrowser` -(`per-file-ignores` in `pyproject.toml`); it starts nothing else. The address holds the page's key, +(`per-file-ignores` in `pyproject.toml`); it starts nothing else. Ruff cannot exempt one API, so +that entry lifts every ban in the file: there `tests/test_no_processes.py`, not ruff, holds the rule. +It reads `browser.py` without importing it and fails on any import but `html`, `logging`, `os`, `sys`, +`webbrowser` and `pathlib`, on any `os` function that starts a process, and on anything of +`webbrowser` but `open` and `Error`. The address holds the page's key, and on Linux and macOS a program's arguments can be read by other users of the computer, so the address never goes to the opener: `browser.py` writes `open-page.html` into `store.directory()`, mode 0600, which leads on to the address, and hands the opener that file's `file:` URI. Without a diff --git a/pyproject.toml b/pyproject.toml index b7f20cc..7ce6698 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,6 +57,8 @@ extend-select = ["TID251", "S102", "S307"] "tests/test_no_processes.py" = ["TID251"] # The one exception, decided by the owner: the web command opens the page in the default browser. # The address goes through a file only the user can read, so the key is in no program's arguments. +# Ruff cannot exempt one API, so this lifts every ban here: tests/test_no_processes.py, not ruff, +# holds the rule inside browser.py: six modules, no os process start, of webbrowser open and Error. "src/odmdm_connector/browser.py" = ["TID251"] [tool.ruff.lint.flake8-tidy-imports.banned-api] diff --git a/tests/test_no_processes.py b/tests/test_no_processes.py index 604e150..1d715f2 100644 --- a/tests/test_no_processes.py +++ b/tests/test_no_processes.py @@ -1,9 +1,11 @@ """The connector starts no process, and the test run makes sure of it""" +import ast import os import subprocess import webbrowser from collections.abc import Callable +from pathlib import Path import pytest @@ -20,3 +22,94 @@ def test_a_process_start_fails_the_test(start: Callable[[], object]) -> None: with pytest.raises(RuntimeError, match="started a process"): start() + + +#: browser.py: ruff's ban is off for the whole file, so this test holds the rule there +BROWSER = Path(__file__).parent.parent / "src" / "odmdm_connector" / "browser.py" +#: The modules browser.py may import, and the only things of webbrowser it may use +BROWSER_IMPORTS = frozenset({"html", "logging", "os", "sys", "webbrowser", "pathlib"}) +BROWSER_OPENS = frozenset({"open", "Error"}) + + +def _starts(name: str) -> bool: + """Whether os. starts a process""" + return name in {"system", "popen", "fork", "forkpty", "posix_spawn", "posix_spawnp", "startfile"} or ( + name.startswith(("exec", "spawn")) + ) + + +def _breaches(source: str) -> list[str]: + """What the source does beyond opening a browser, read without importing it""" + tree = ast.parse(source) + found: list[str] = [] + #: The names os and webbrowser are bound to, as imported + bound: dict[str, str] = {} + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + top = alias.name.split(".")[0] + if top not in BROWSER_IMPORTS: + found.append(f"import {alias.name}") + if alias.name in ("os", "webbrowser"): + bound[alias.asname or alias.name] = alias.name + elif isinstance(node, ast.ImportFrom): + module = "." * node.level + (node.module or "") + if module.split(".")[0] not in BROWSER_IMPORTS: + found.append(f"from {module} import") + for alias in node.names: + if (module == "os" and _starts(alias.name)) or ( + module == "webbrowser" and alias.name not in BROWSER_OPENS + ): + found.append(f"from {module} import {alias.name}") + elif isinstance(node, ast.Name) and node.id == "__import__": + found.append("__import__") + used = {id(node.value) for node in ast.walk(tree) if isinstance(node, ast.Attribute)} + for node in ast.walk(tree): + if isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name) and node.value.id in bound: + module = bound[node.value.id] + if (module == "os" and _starts(node.attr)) or (module == "webbrowser" and node.attr not in BROWSER_OPENS): + found.append(f"{module}.{node.attr}") + elif isinstance(node, ast.Name) and node.id in bound and id(node) not in used: + # Handed on whole, as to getattr, the module could reach anything in it + found.append(f"{bound[node.id]} itself") + return found + + +def test_browser_py_only_opens_a_browser() -> None: + assert _breaches(BROWSER.read_text(encoding="utf-8")) == [] + + +@pytest.mark.parametrize( + "source", + [ + "import subprocess", + "import multiprocessing.pool", + "import pty", + "import importlib", + "from . import store", + "from .os import system", + "from asyncio import create_subprocess_exec", + "__import__('subprocess')", + "import os\nos.posix_spawn('x', [], {})", + "import os\nos.fork()", + "import os\nos.execv('x', [])", + "import os\nos.spawnlp(0, 'x')", + "import os as o\no.system('x')", + "import os\ngetattr(os, 'system')('x')", + "from os import popen", + "from os import execvp", + "import webbrowser\nwebbrowser.get('x')", + "import webbrowser\nwebbrowser.open_new_tab('x')", + "from webbrowser import BackgroundBrowser", + ], +) +def test_the_guard_on_browser_py_finds_a_process_start(source: str) -> None: + assert _breaches(source) + + +def test_the_guard_on_browser_py_lets_what_it_needs_through() -> None: + allowed = ( + "import html, logging, os, sys, webbrowser\nfrom pathlib import Path\n" + "os.open('x', os.O_WRONLY)\nos.environ.get('DISPLAY')\nwebbrowser.open('x')\nexcept_ = webbrowser.Error\n" + ) + assert _breaches(allowed) == [] From 906c062d8a4235230cfab507f8d9d712789c7ff4 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 21:09:42 +0200 Subject: [PATCH 073/104] fix: print the address and serve the page while the browser is asked, as some openers wait --- AGENTS.md | 3 +- src/odmdm_connector/browser.py | 4 +- src/odmdm_connector/console.py | 12 +-- tests/test_web.py | 139 +++++++++++++++++++++++++++------ 4 files changed, 124 insertions(+), 34 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ff36c9d..9e1fbcb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,7 +131,8 @@ giving callsigns, one phone, the settings and removing a Deploy App. Keep these so on a computer shared with other users the settings line is copied by hand instead. Another program on this computer can slow the page down, but cannot read or drive it without the key. - `web` opens the page in the default browser through `browser.py` only, and prints the address; - `--no-browser` only prints it. Deploy App's button finds the page only in the browser where the + `--no-browser` only prints it. The address is printed first and the browser asked from a daemon + thread as the page starts to serve, since some openers wait for the browser or never return. Deploy App's button finds the page only in the browser where the address was opened. ## Facts measured against a live Fleet diff --git a/src/odmdm_connector/browser.py b/src/odmdm_connector/browser.py index 2bc12a0..7451ed1 100644 --- a/src/odmdm_connector/browser.py +++ b/src/odmdm_connector/browser.py @@ -19,7 +19,7 @@ NAME = "open-page.html" -def _desktop() -> bool: +def can_open() -> bool: """Whether there is a desktop to open a browser on; without one, webbrowser starts a text browser in the terminal""" if sys.platform in ("win32", "darwin"): return True @@ -53,7 +53,7 @@ def open_page(address: str, directory: Path) -> bool: Raises nothing that writing the file or starting a browser raises: the connector starts whether or not a browser opens. """ - if not _desktop(): + if not can_open(): return False path = directory / NAME try: diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 1d73ca7..118352d 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -13,6 +13,7 @@ import logging import os import sys +import threading from collections.abc import Callable, Mapping, Sequence from pathlib import Path from urllib.parse import urlparse @@ -26,7 +27,7 @@ #: Said when ODMDM_LOG_LEVEL is not a number LOG_LEVEL = "ODMDM_LOG_LEVEL must be a whole number, such as 10 for debug or 20 for info: change it, or unset it." -#: Said before the page's address, when a browser was asked to open it and when not +#: Said before the page's address, when the browser is to be asked to open it and when not OPENING = "The connector's page is opening in your browser. If it does not, open this address:" OPEN = "Open this address in your browser:" #: Said when Ctrl+C stops the page while a job is under way @@ -376,12 +377,13 @@ def page(args: argparse.Namespace) -> int: raise _Failed( f"The page cannot listen on port {args.port} of this computer: {exc.strerror}. {advice}" ) from exc - if args.browser and browser.open_page(server.address, directory): - print(f"{OPENING} {server.address}") - else: - print(f"{OPEN} {server.address}") + asked = args.browser and browser.can_open() + print(f"{OPENING if asked else OPEN} {server.address}") print("Press Ctrl+C to stop it.", flush=True) with server: + if asked: + # Some openers wait for the browser, or never return: the page serves meanwhile + threading.Thread(target=browser.open_page, args=(server.address, directory), daemon=True).start() try: server.serve_forever() except KeyboardInterrupt: diff --git a/tests/test_web.py b/tests/test_web.py index 5f1bf83..170236d 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -570,19 +570,25 @@ def test_no_answer_and_no_log_line_holds_a_secret(served: Served, caplog: pytest assert all(secret.encode() not in body for body in served.bodies) -def _web(rig: WebRig, monkeypatch: pytest.MonkeyPatch, busy: bool = False) -> list[web.Page]: +def _web( + rig: WebRig, monkeypatch: pytest.MonkeyPatch, busy: bool = False, asked: threading.Event | None = None +) -> list[web.Page]: """The web command will serve rig's App until a Ctrl+C, at once, with a job under way or none - The connector's directory is rig's, and no browser is asked unless a test says so. + The connector's directory is rig's. Without asked, there is no desktop and no browser is asked; + with it, the Ctrl+C comes once the browser has been asked. """ monkeypatch.setattr(app.App, "default", lambda: rig.app) monkeypatch.setattr(store, "directory", lambda: rig.directory) - monkeypatch.setattr(browser, "open_page", lambda address, directory: False) + if asked is None: + monkeypatch.setattr(browser, "can_open", lambda: False) monkeypatch.setattr(rig.app, "busy", lambda job=None: busy) started: list[web.Page] = [] def serve(page: web.Page, poll_interval: float = 0.5) -> None: started.append(page) + if asked is not None: + assert asked.wait(5), "the browser was never asked" raise KeyboardInterrupt monkeypatch.setattr(web.Page, "serve_forever", serve) @@ -611,39 +617,44 @@ def test_the_web_command_prints_where_and_how_to_stop( assert not printed.err -#: The real browser.open_page, which _web replaces -OPEN_PAGE = browser.open_page +#: The real browser.can_open, which _web replaces +CAN_OPEN = browser.can_open -def _opener(rig: WebRig, monkeypatch: pytest.MonkeyPatch, answer: bool = True) -> list[tuple[str, bool]]: - """The web command asks the browser through browser.open_page, on a desktop, of an opener that answers +class Opener: + """The opener on a desktop: what it was handed and whether the file was there then, and its answer - What the opener was handed, and whether the file was there then. + Once asked, it sets asked; it answers only once released is set. """ - handed: list[tuple[str, bool]] = [] - def opener(url: str, new: int = 0, autoraise: bool = True) -> bool: - handed.append((url, (rig.directory / browser.NAME).is_file())) - return answer + def __init__(self, rig: WebRig, monkeypatch: pytest.MonkeyPatch, answer: bool = True) -> None: + self.rig, self.answer = rig, answer + self.handed: list[tuple[str, bool]] = [] + self.asked, self.released = threading.Event(), threading.Event() + self.released.set() + monkeypatch.setattr(browser, "can_open", CAN_OPEN) + monkeypatch.setattr(sys, "platform", "darwin") + monkeypatch.setattr("webbrowser.open", self) - monkeypatch.setattr(browser, "open_page", OPEN_PAGE) - monkeypatch.setattr(sys, "platform", "darwin") - monkeypatch.setattr("webbrowser.open", opener) - return handed + def __call__(self, url: str, new: int = 0, autoraise: bool = True) -> bool: + self.handed.append((url, (self.rig.directory / browser.NAME).is_file())) + self.asked.set() + self.released.wait(5) + return self.answer def test_the_web_command_opens_the_page_in_the_browser_by_default( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: rig = WebRig(tmp_path / "config") - started = _web(rig, monkeypatch) - handed = _opener(rig, monkeypatch) + opener = Opener(rig, monkeypatch) + started = _web(rig, monkeypatch, asked=opener.asked) port = _free_port() assert console.main(["web", "--port", str(port)]) == 0 - assert handed == [((rig.directory / browser.NAME).as_uri(), True)] - assert started[0].key not in handed[0][0] + assert opener.handed == [((rig.directory / browser.NAME).as_uri(), True)] + assert started[0].key not in opener.handed[0][0] assert capsys.readouterr().out.splitlines() == [ f"{console.OPENING} http://127.0.0.1:{port}/#key={started[0].key}", "Press Ctrl+C to stop it.", @@ -651,22 +662,98 @@ def test_the_web_command_opens_the_page_in_the_browser_by_default( assert not (rig.directory / browser.NAME).exists(), "removed when the connector stops" -@pytest.mark.parametrize("given", [[], ["--no-browser"]], ids=["the browser says no", "--no-browser"]) -def test_without_a_browser_asked_the_address_is_printed_to_open( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], given: list[str] +def test_an_opener_that_waits_holds_up_neither_the_address_nor_the_page( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """A BROWSER command webbrowser does not know, a text browser or osascript waits for the browser""" + rig = WebRig(tmp_path / "config") + opener = Opener(rig, monkeypatch) + opener.released.clear() + monkeypatch.setattr(app.App, "default", lambda: rig.app) + monkeypatch.setattr(store, "directory", lambda: rig.directory) + pages: list[web.Page] = [] + serving = threading.Event() + serve = web.Page.serve_forever + + def watched(page: web.Page, poll_interval: float = 0.5) -> None: + pages.append(page) + serving.set() + serve(page, 0.01) + + monkeypatch.setattr(web.Page, "serve_forever", watched) + codes: list[int] = [] + command = threading.Thread(target=lambda: codes.append(console.main(["web", "--port", str(_free_port())]))) + command.start() + try: + assert opener.asked.wait(5) and serving.wait(5) + page = pages[0] + assert capsys.readouterr().out.splitlines() == [f"{console.OPENING} {page.address}", "Press Ctrl+C to stop it."] + connection = http.client.HTTPConnection("127.0.0.1", page.port, timeout=5) + try: + connection.request("GET", "/api/state", headers={"Host": f"127.0.0.1:{page.port}", "X-ODMDM-Key": page.key}) + assert connection.getresponse().status == 200 + finally: + connection.close() + assert command.is_alive() and not codes, "still serving while the opener waits" + finally: + opener.released.set() + if serving.wait(5): + pages[0].shutdown() + command.join(5) + assert codes == [0] + + +def test_without_a_desktop_the_address_is_printed_to_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: rig = WebRig(tmp_path / "config") started = _web(rig, monkeypatch) - handed = _opener(rig, monkeypatch, answer=False) + opener = Opener(rig, monkeypatch) + monkeypatch.setattr(sys, "platform", "linux") + monkeypatch.delenv("DISPLAY", raising=False) + monkeypatch.delenv("WAYLAND_DISPLAY", raising=False) port = _free_port() - assert console.main(["web", *given, "--port", str(port)]) == 0 + assert console.main(["web", "--port", str(port)]) == 0 - assert len(handed) == (0 if given else 1) + assert opener.handed == [] assert capsys.readouterr().out.splitlines() == [ f"{console.OPEN} http://127.0.0.1:{port}/#key={started[0].key}", "Press Ctrl+C to stop it.", ] + + +def test_with_no_browser_the_address_is_printed_to_open( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + rig = WebRig(tmp_path / "config") + started = _web(rig, monkeypatch) + opener = Opener(rig, monkeypatch) + port = _free_port() + + assert console.main(["web", "--no-browser", "--port", str(port)]) == 0 + + assert opener.handed == [] + assert capsys.readouterr().out.splitlines() == [ + f"{console.OPEN} http://127.0.0.1:{port}/#key={started[0].key}", + "Press Ctrl+C to stop it.", + ] + assert not (rig.directory / browser.NAME).exists() + + +def test_when_the_browser_says_no_the_file_is_gone( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """The address was printed before the answer, with the sentence that says what to do if it does not open""" + rig = WebRig(tmp_path / "config") + opener = Opener(rig, monkeypatch, answer=False) + started = _web(rig, monkeypatch, asked=opener.asked) + port = _free_port() + + assert console.main(["web", "--port", str(port)]) == 0 + + assert len(opener.handed) == 1 + assert capsys.readouterr().out.splitlines()[0] == f"{console.OPENING} http://127.0.0.1:{port}/#key={started[0].key}" assert not (rig.directory / browser.NAME).exists() From 2c7c4c225ae099662d5e5728354355895e170c78 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 21:10:17 +0200 Subject: [PATCH 074/104] fix: remove the page's file only when this run wrote it, not a running connector's --- AGENTS.md | 4 +++- src/odmdm_connector/console.py | 5 ++++- tests/test_web.py | 25 ++++++++++++++++++++----- 3 files changed, 27 insertions(+), 7 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9e1fbcb..7d3453a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -184,4 +184,6 @@ strands every enrolled phone's key. sends it only as the `X-ODMDM-Key` header to the page's own `/api/`. Never log it, never put it in an answer, never in a cookie, a query or another program's arguments. - **`open-page.html`** in `store.directory()`: it holds the address, key and all, while the - connector runs, so it is written mode 0600 and removed in the `web` command's `finally`. + connector runs, so it is written mode 0600 and removed in the `web` command's `finally`, only by + a run that asked the browser: with `--no-browser`, without a desktop or on a taken port it may be + a running connector's. diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 118352d..ae0cdc0 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -389,8 +389,11 @@ def page(args: argparse.Namespace) -> int: except KeyboardInterrupt: if started.busy(): print(STOPPED_BUSY, file=sys.stderr) + finally: + # Only this run's file: without it, the file may be a connector's that is still running + if asked: + browser.remove(directory) finally: - browser.remove(directory) started.close() return 0 diff --git a/tests/test_web.py b/tests/test_web.py index 170236d..343c70d 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -723,12 +723,25 @@ def test_without_a_desktop_the_address_is_printed_to_open( ] +#: What a connector still running wrote into the file +RUNNING = "written by a connector still running" + + +def _running_connectors_file(rig: WebRig) -> Path: + """The file, as another connector on this computer wrote it and still needs it""" + rig.directory.mkdir(parents=True, exist_ok=True) + path = rig.directory / browser.NAME + path.write_text(RUNNING, encoding="utf-8") + return path + + def test_with_no_browser_the_address_is_printed_to_open( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: rig = WebRig(tmp_path / "config") started = _web(rig, monkeypatch) opener = Opener(rig, monkeypatch) + running = _running_connectors_file(rig) port = _free_port() assert console.main(["web", "--no-browser", "--port", str(port)]) == 0 @@ -738,7 +751,7 @@ def test_with_no_browser_the_address_is_printed_to_open( f"{console.OPEN} http://127.0.0.1:{port}/#key={started[0].key}", "Press Ctrl+C to stop it.", ] - assert not (rig.directory / browser.NAME).exists() + assert running.read_text(encoding="utf-8") == RUNNING, "another connector's, left alone" def test_when_the_browser_says_no_the_file_is_gone( @@ -770,10 +783,11 @@ def test_ctrl_c_during_a_job_says_what_to_do_next( def test_the_web_command_says_when_the_port_is_taken( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] ) -> None: + """On a desktop: a connector may be running on that port, and its file is left alone""" rig = WebRig(tmp_path / "config") - _web(rig, monkeypatch) - rig.directory.mkdir(parents=True, exist_ok=True) - (rig.directory / browser.NAME).write_text("left from an earlier start", encoding="utf-8") + opener = Opener(rig, monkeypatch) + _web(rig, monkeypatch, asked=opener.asked) + running = _running_connectors_file(rig) with socket.socket() as taken: taken.bind(("127.0.0.1", 0)) taken.listen() @@ -785,7 +799,8 @@ def test_the_web_command_says_when_the_port_is_taken( assert code == 1 assert said.startswith(f"The page cannot listen on port {port} of this computer: ") assert said.endswith(". Give another with --port.\n") - assert not (rig.directory / browser.NAME).exists(), "removed when the server could not start too" + assert opener.handed == [] + assert running.read_text(encoding="utf-8") == RUNNING, "another connector's, left alone" def test_the_web_command_says_the_connector_may_be_running_when_its_own_port_is_taken( From 2ebe5e68a684c10610091c835f018c313534582f Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sat, 21 Nov 2026 21:10:55 +0200 Subject: [PATCH 075/104] docs: the address is on no program's command line, and two openers to start without --- README.rst | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/README.rst b/README.rst index 63d8b7e..bc84658 100644 --- a/README.rst +++ b/README.rst @@ -38,8 +38,11 @@ It opens the page in your default browser and prints its address, and goes on un ``--port N`` serves it on another port than 8737. The browser does not open by itself on a computer without a desktop, with ``--no-browser``, or when the default browser may not read the connector's own folder, as a browser installed as a snap on Linux cannot: then open the address it prints -yourself. A page opened without that address says so, and goes on by itself once the address has -been opened in the same browser. Deploy App's button finds the page only in the browser where the +yourself. On a Mac whose ``.html`` files open in another program than the browser, the connector's +file may open there instead; on Linux without a graphical opener, a text browser may take the +terminal. In both cases start it with ``--no-browser`` and open the printed address. A page opened +without that address says so, and goes on by itself once the address has been opened in the same +browser. Deploy App's button finds the page only in the browser where the address was opened, so use Deploy App in your default browser, or open the address in the browser you use Deploy App in. @@ -95,9 +98,10 @@ What guards the page: once the connector accepts it, so that a page elsewhere cannot put a wrong one in its place, and sends it with each request in a header of its own, never in a cookie, which a browser would also send to every other program listening on this computer. -- The address never goes to another program: to open the browser, the connector writes a small file - that leads on to it into its own folder, which only you can read, and hands the browser that - file. The file holds the key while the connector runs and is removed when it stops. +- The address is never on another program's command line, where other users of the computer could + read it: to open the browser, the connector writes a small file that leads on to it into its own + folder, which only you can read, and the browser gets the address through that file. The file + holds the key while the connector runs and is removed when it stops. - The browser keeps exactly one thing, that key, in the page's own storage, so that every tab of the page has it. It is worthless once the connector stops. Nothing else is ever kept there. The browser's history also keeps the address you opened, key and all; that matters only while the From e0b48ee4e01a004b16f7f3c5a9245c9820b271f8 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:58:10 +0200 Subject: [PATCH 076/104] fix: keep a Deploy App's name whole in the page's titles A name with a hyphen broke in the middle of a heading. It now moves to the next line as one, with the punctuation after it, and breaks inside only when it is wider than the line by itself. --- src/odmdm_connector/static/app.css | 7 +++++++ src/odmdm_connector/static/app.js | 11 +++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/odmdm_connector/static/app.css b/src/odmdm_connector/static/app.css index 376e9ce..6372076 100644 --- a/src/odmdm_connector/static/app.css +++ b/src/odmdm_connector/static/app.css @@ -59,6 +59,13 @@ h1 { overflow-wrap: anywhere; } +/* A Deploy App's name in a title: whole on its line, broken only when wider than the line */ +.name { + display: inline-block; + max-width: 100%; + overflow-wrap: anywhere; +} + h2 { font-size: 15px; margin: 8px 0 8px; diff --git a/src/odmdm_connector/static/app.js b/src/odmdm_connector/static/app.js index 911ba30..6d34c90 100644 --- a/src/odmdm_connector/static/app.js +++ b/src/odmdm_connector/static/app.js @@ -39,6 +39,9 @@ function el(tag, props, ...children) { } const h1 = (text) => el("h1", {}, text); +// A Deploy App's name in a title, kept whole with the punctuation after it: it moves to the next line +// as one, and breaks inside only when it is wider than the line by itself +const named = (name, after = "") => el("span", { class: "name" }, name, after); const lead = (text) => (text ? el("p", { class: "lead" }, text) : null); // A button is known by its text, so that it keeps the focus when the view is drawn again const button = (props, text) => { @@ -424,7 +427,7 @@ const CARDS = { step: renew ? null : 0, back: S.connections.length ? { text: "Back", action: flow.back || home } : null, parts: [ - h1(renew ? `New settings for Deploy App ${S.active}` : "Add your Deploy App"), + h1(renew ? ["New settings for Deploy App ", named(S.active)] : "Add your Deploy App"), notice ? el("p", { class: "muted" }, notice) : null, lead("On Deploy App's MDM page, press this button:"), // A picture of Deploy App's button, which the sentence above names: nothing to press here @@ -466,7 +469,7 @@ const CARDS = { return { step: known ? null : 0, parts: [ - h1(known ? `New settings for Deploy App ${host}` : `Add Deploy App ${host}?`), + h1(known ? ["New settings for Deploy App ", named(host)] : ["Add Deploy App ", named(host, "?")]), lead(until), main(known ? "Use the new settings" : `Add ${host}`, take), // Any web page can bring this card up for a Deploy App of its own @@ -1126,7 +1129,7 @@ function settings() { open( "Settings", [ - el("h3", { class: "sect" }, `${answer.title} for ${S.active}`), + el("h3", { class: "sect" }, `${answer.title} for `, named(S.active)), el( "dl", { class: "facts" }, @@ -1157,7 +1160,7 @@ function remove() { ); const button = main("Remove", removing, false, "danger"); const tell = open( - `Remove Deploy App ${host}?`, + ["Remove Deploy App ", named(host, "?")], [ el( "p", From 4465b8796df9a51661dadab33cef8307b4caed2d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:24 +0200 Subject: [PATCH 077/104] feat: open the page when started without a command A downloaded file is started by a double-click, with no arguments: it then does what web does, with web's defaults. An option of web given without the command is still an error. --- src/odmdm_connector/console.py | 11 ++++++-- tests/test_console.py | 46 +++++++++++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index ae0cdc0..75ee111 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -44,7 +44,12 @@ class _Failed(Exception): def main(argv: Sequence[str] | None = None) -> int: """Run the command line and answer its exit code; a usage error exits 2 through argparse""" - args = _parser().parse_args(argv) + parser = _parser() + given = sys.argv[1:] if argv is None else list(argv) + args = parser.parse_args(given) + if not hasattr(args, "run"): + # Started with no command, as a downloaded file is by a double-click: the page, with web's defaults + args = parser.parse_args([*given, "web"]) try: level = int(os.environ.get("ODMDM_LOG_LEVEL", "20")) except ValueError: @@ -446,7 +451,9 @@ def _parser() -> argparse.ArgumentParser: metavar="KEY=VALUE", help="A setting of the MDM, such as mdm_url; never a secret, which is read from the file ODMDM__FILE names", ) - commands = parser.add_subparsers(title="commands", metavar="COMMAND", required=True) + commands = parser.add_subparsers( + title="commands", metavar="COMMAND", description="Without a command: web with its defaults" + ) def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) -> argparse.ArgumentParser: doc = inspect.cleandoc(run.__doc__ or "") diff --git a/tests/test_console.py b/tests/test_console.py index eb8bece..8d9ef01 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -4,6 +4,7 @@ to say why, rather than end in a traceback. """ +import argparse import codecs import datetime import getpass @@ -17,7 +18,7 @@ import pytest -from odmdm_connector import __version__, console, plugins +from odmdm_connector import __version__, console, plugins, web from odmdm_connector import fleet as fleet_module from odmdm_connector.fleet_plugin import FleetPlugin @@ -1066,3 +1067,46 @@ def test_a_log_level_that_is_not_a_number_is_said(run: Run, level: str) -> None: result = run(["mdms"], env={"ODMDM_LOG_LEVEL": level}) assert (result.exit_code, result.stdout, result.stderr) == (1, "", f"{console.LOG_LEVEL}\n") + + +def _pages(monkeypatch: pytest.MonkeyPatch) -> list[argparse.Namespace]: + """What the web command was started with, each time, in place of serving the page""" + started: list[argparse.Namespace] = [] + + def page(args: argparse.Namespace) -> int: + """Serve the page""" + started.append(args) + return 0 + + monkeypatch.setattr(console, "page", page) + return started + + +@pytest.mark.parametrize( + ("arguments", "verbose"), + [([], 0), (["-v"], 1), (["--mdm", "fleet", "--set", "team=Deploy App"], 0)], +) +def test_without_a_command_the_page_starts_with_web_s_defaults( + arguments: list[str], verbose: int, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """A downloaded file is started by a double-click, with no arguments""" + started = _pages(monkeypatch) + + result = run(arguments) + + assert result.exit_code == 0 + assert [(args.port, args.browser, args.verbose) for args in started] == [(web.PORT, True, verbose)] + + +@pytest.mark.parametrize("arguments", [["--help"], ["--version"], ["nope"], ["-v", "nope"]]) +def test_help_version_and_a_wrong_command_start_no_page( + arguments: list[str], monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + started = _pages(monkeypatch) + + result = run(arguments) + + assert not started + assert result.exit_code == (2 if "nope" in arguments else 0) + if "nope" in arguments: + assert "invalid choice: 'nope'" in result.stderr From b5d1622e1b6249ebab01538ffdf97202650228c7 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:24 +0200 Subject: [PATCH 078/104] feat: describe the files a deployment serves, in connector.json The version, the MDMs built in as the package registers them, and each file with its size and SHA-256 in a fixed order. A file that is none of the connector's is an error that names it. --- .pre-commit-config.yaml | 3 +- packaging/manifest.py | 95 +++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 8 ++-- tests/test_manifest.py | 58 +++++++++++++++++++++++++ 4 files changed, 159 insertions(+), 5 deletions(-) create mode 100644 packaging/manifest.py create mode 100644 tests/test_manifest.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index abf2e06..9f688d8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -110,7 +110,7 @@ repos: # >>> END AUTOGENERATED SECTION - config-ci-library # Add any repo-specific hooks below this line - # Repo specific. The generated mypy hook only looks at src, and the tests and the demo plugin are annotated too. + # Repo specific. The generated mypy hook only looks at src, and the tests, the demo plugin and packaging are annotated too. - repo: local hooks: - id: mypy-tests @@ -126,3 +126,4 @@ repos: - "conftest.py" - "examples/odmdm-connector-demo/src" - "examples/odmdm-connector-demo/tests" + - "packaging" diff --git a/packaging/manifest.py b/packaging/manifest.py new file mode 100644 index 0000000..8badf7c --- /dev/null +++ b/packaging/manifest.py @@ -0,0 +1,95 @@ +"""Write DIR/connector.json for the connector's files in DIR: what Deploy App's MDM page offers + + uv run python packaging/manifest.py DIR + +DIR holds what a deployment serves beside its UI as mdm-connector/: the files packaging/build.py +packed, one per system, and the one-file Python build. The manifest says the connector's version, +the MDMs built into it, read from what the package registers, and each file with its size and +SHA-256, in a fixed order. A file in DIR that is none of these is an error that names it. +""" + +import hashlib +import json +import re +import sys +from importlib.metadata import version +from pathlib import Path + +from odmdm_connector import plugins + +NAME = "connector.json" +#: Each system's file, in the manifest's order: the system, its architecture and the file's extension +FILES = ( + ("windows", "x64", ".exe"), + ("windows", "arm64", ".exe"), + ("macos", "x64", ".zip"), + ("macos", "arm64", ".zip"), + ("linux", "x64", ".tar.gz"), + ("linux", "arm64", ".tar.gz"), + ("any", "any", ".pyz"), +) +#: What Deploy App takes as a file's name: a bare name in the manifest's folder +BARE = re.compile(r"[A-Za-z0-9._+-]{1,120}") + + +class ManifestError(Exception): + """A folder that cannot be described as the contract says""" + + +def file_name(release: str, system: str, arch: str) -> str: + """The name of the connector's file for that system and architecture""" + extension = next(extension for named, machine, extension in FILES if (named, machine) == (system, arch)) + if system == "any": + return f"odmdm-connector-{release}{extension}" + return f"odmdm-connector-{release}-{system}-{arch}{extension}" + + +def built_in() -> list[dict[str, str]]: + """The MDMs built into the connector, name and title, as the package registers them""" + return [ + {"name": plugin.name, "title": plugins.load(plugin.name).title} + for plugin in plugins.installed() + if plugin.built_in + ] + + +def manifest(folder: Path, release: str) -> dict[str, object]: + """The manifest for the files in the folder, connector.json aside""" + known = {file_name(release, system, arch): (system, arch) for system, arch, _ in FILES} + found = {path.name: path for path in folder.iterdir() if path.name != NAME} + for name, path in sorted(found.items()): + if name not in known or not BARE.fullmatch(name) or not path.is_file(): + raise ManifestError(f"{path} is not one of the connector's files of version {release}") + if not found: + raise ManifestError(f"{folder} holds none of the connector's files") + files = [ + { + "os": system, + "arch": arch, + "file": name, + "size": found[name].stat().st_size, + "sha256": hashlib.sha256(found[name].read_bytes()).hexdigest(), + } + for name, (system, arch) in known.items() + if name in found + ] + return {"version": release, "mdms": built_in(), "files": files} + + +def main(argv: list[str]) -> int: + """Write the manifest into the folder named, or say why not""" + if len(argv) != 1 or not Path(argv[0]).is_dir(): + print("Give the folder of the connector's files: manifest.py DIR", file=sys.stderr) + return 2 + folder = Path(argv[0]) + try: + written = manifest(folder, version("odmdm-connector")) + except ManifestError as exc: + print(exc, file=sys.stderr) + return 1 + (folder / NAME).write_text(json.dumps(written, indent=2) + "\n", encoding="utf-8") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/pyproject.toml b/pyproject.toml index 7ce6698..733c10d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -95,8 +95,8 @@ extend-select = ["TID251", "S102", "S307"] [tool.mypy] strict=true -# The demo plugin's tests import it from its source, as pytest does -mypy_path="examples/odmdm-connector-demo/src" +# The demo plugin's tests import it from its source, as pytest does, and the manifest's test from packaging +mypy_path="examples/odmdm-connector-demo/src:packaging" [[tool.mypy.overrides]] module="tests.*" @@ -104,8 +104,8 @@ disallow_untyped_decorators=false [tool.pytest.ini_options] junit_family="xunit2" -# The demo plugin, a package of its own, runs its contract tests here from its source -pythonpath=["examples/odmdm-connector-demo/src"] +# The demo plugin, a package of its own, runs its contract tests here from its source; and packaging/manifest.py +pythonpath=["examples/odmdm-connector-demo/src", "packaging"] addopts="--cov=odmdm_connector --cov-fail-under=88 --cov-branch" [tool.coverage.run] diff --git a/tests/test_manifest.py b/tests/test_manifest.py new file mode 100644 index 0000000..4b8cc9a --- /dev/null +++ b/tests/test_manifest.py @@ -0,0 +1,58 @@ +"""packaging/manifest.py: connector.json, the contract with Deploy App's MDM page""" + +import hashlib +import json +import re +from importlib.metadata import version +from pathlib import Path + +import manifest +import pytest + +RELEASE = version("odmdm-connector") + + +def test_the_manifest_names_the_mdms_built_in_and_each_file_in_a_fixed_order(tmp_path: Path) -> None: + for name in (f"odmdm-connector-{RELEASE}.pyz", f"odmdm-connector-{RELEASE}-windows-x64.exe"): + (tmp_path / name).write_bytes(name.encode()) + (tmp_path / manifest.NAME).write_text("the one written before", encoding="utf-8") + + assert manifest.main([str(tmp_path)]) == 0 + + written = json.loads((tmp_path / manifest.NAME).read_text(encoding="utf-8")) + assert written == { + "version": RELEASE, + "mdms": [{"name": "fleet", "title": "Fleet"}], + "files": [ + { + "os": system, + "arch": arch, + "file": name, + "size": len(name), + "sha256": hashlib.sha256(name.encode()).hexdigest(), + } + for system, arch, name in ( + ("windows", "x64", f"odmdm-connector-{RELEASE}-windows-x64.exe"), + ("any", "any", f"odmdm-connector-{RELEASE}.pyz"), + ) + ], + } + assert all(re.fullmatch(r"[A-Za-z0-9._+-]{1,120}", item["file"]) for item in written["files"]) + + +@pytest.mark.parametrize( + "name", ["odmdm-connector-0.0.1+1-windows-x64.exe", "odmdm-connector-macos-arm64.zip", "notes.txt", "a folder"] +) +def test_a_file_that_is_not_the_connector_s_is_named_never_skipped( + name: str, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + (tmp_path / f"odmdm-connector-{RELEASE}.pyz").write_bytes(b"pyz") + if name == "a folder": + (tmp_path / name).mkdir() + else: + (tmp_path / name).write_bytes(b"other") + + assert manifest.main([str(tmp_path)]) == 1 + + assert name in capsys.readouterr().err + assert not (tmp_path / manifest.NAME).exists() From b3104b015ff9007876efda19390f567aa837ec4e Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:25 +0200 Subject: [PATCH 079/104] build: one self-contained file per system, built with PyInstaller A build tool only, in a dependency group of its own: Python, the connector and keyring in one executable, packed so that a browser's download keeps it runnable. Not signed. --- packaging/build.py | 91 +++++++++++++++++++++++++++++++++++++++++++ packaging/launcher.py | 6 +++ pyproject.toml | 8 ++++ uv.lock | 83 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 188 insertions(+) create mode 100644 packaging/build.py create mode 100644 packaging/launcher.py diff --git a/packaging/build.py b/packaging/build.py new file mode 100644 index 0000000..6acf41f --- /dev/null +++ b/packaging/build.py @@ -0,0 +1,91 @@ +"""Build the connector as one self-contained file for this computer's system, and pack it + + uv run --group dist python packaging/build.py [OUT] + +PyInstaller, a build tool only, puts Python, the connector and keyring into one executable, +build/pyinstaller/odmdm-connector (.exe on Windows). It is packed into OUT, default +dist/mdm-connector, under the name connector.json gives it: the .exe as it is, otherwise one +executable named odmdm-connector in a .zip (macOS) or .tar.gz (Linux), with its executable bit, +which a browser's download would lose. README.rst and CI both build with this file. +""" + +import platform +import shutil +import sys +import tarfile +import zipfile +from importlib.metadata import version +from pathlib import Path + +import PyInstaller.__main__ +from manifest import file_name + +ROOT = Path(__file__).resolve().parent.parent +BUILD = ROOT / "build" / "pyinstaller" +#: --copy-metadata: the entry points, through which the connector finds Fleet. +#: --collect-submodules: the modules only an entry point names, Fleet's among them. +ARGUMENTS = ( + "--onefile", + "--name", + "odmdm-connector", + "--collect-data", + "odmdm_connector", + "--copy-metadata", + "odmdm-connector", + "--collect-submodules", + "odmdm_connector", + "--noconfirm", + "--clean", + "--distpath", + str(BUILD), + "--workpath", + str(BUILD / "work"), + "--specpath", + str(BUILD), + str(ROOT / "packaging" / "launcher.py"), +) +SYSTEMS = {"win32": "windows", "darwin": "macos", "linux": "linux"} +ARCHITECTURES = {"x86_64": "x64", "amd64": "x64", "arm64": "arm64", "aarch64": "arm64"} + + +def pack(executable: Path, out: Path, release: str, system: str, arch: str) -> Path: + """The executable in OUT under its name in connector.json, packed for its system""" + out.mkdir(parents=True, exist_ok=True) + packed = out / file_name(release, system, arch) + if system == "windows": + shutil.copyfile(executable, packed) + elif system == "macos": + member = zipfile.ZipInfo.from_file(executable, "odmdm-connector") + member.create_system = 3 # Unix, so that unzipping keeps the mode + member.external_attr = 0o100755 << 16 + with zipfile.ZipFile(packed, "w") as archive: + archive.writestr(member, executable.read_bytes()) + else: + with tarfile.open(packed, "w:gz") as archive: + archive.add(executable, "odmdm-connector", filter=_owned_by_nobody) + return packed + + +def _owned_by_nobody(member: tarfile.TarInfo) -> tarfile.TarInfo: + member.uid = member.gid = 0 + member.uname = member.gname = "" + member.mode = 0o755 + return member + + +def main(argv: list[str]) -> int: + """Build and pack for this computer, and say where the file is""" + out = Path(argv[0]) if argv else ROOT / "dist" / "mdm-connector" + system = SYSTEMS.get(sys.platform, "") + arch = ARCHITECTURES.get(platform.machine().lower(), "") + if not system or not arch: + print(f"No file is made for {sys.platform} on {platform.machine()}", file=sys.stderr) + return 1 + PyInstaller.__main__.run(list(ARGUMENTS)) + executable = BUILD / ("odmdm-connector.exe" if system == "windows" else "odmdm-connector") + print(pack(executable, out, version("odmdm-connector"), system, arch)) + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/packaging/launcher.py b/packaging/launcher.py new file mode 100644 index 0000000..49bc9b8 --- /dev/null +++ b/packaging/launcher.py @@ -0,0 +1,6 @@ +"""What PyInstaller starts: the connector's command line, as the installed odmdm-connector command""" + +from odmdm_connector.console import odmdm_connector_cli + +if __name__ == "__main__": + odmdm_connector_cli() diff --git a/pyproject.toml b/pyproject.toml index 733c10d..085e485 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,6 +34,9 @@ dev = [ "tox-uv>=1.0,<2.0", "ruff>=0.15.12", ] +dist = [ + "pyinstaller>=6.22,<7", +] [build-system] requires = ["hatchling"] @@ -98,6 +101,11 @@ strict=true # The demo plugin's tests import it from its source, as pytest does, and the manifest's test from packaging mypy_path="examples/odmdm-connector-demo/src:packaging" +# A build tool, in the dist group only, and without type hints +[[tool.mypy.overrides]] +module="PyInstaller.*" +ignore_missing_imports=true + [[tool.mypy.overrides]] module="tests.*" disallow_untyped_decorators=false diff --git a/uv.lock b/uv.lock index 00c1d12..aaf146d 100644 --- a/uv.lock +++ b/uv.lock @@ -7,6 +7,15 @@ resolution-markers = [ "(python_full_version < '3.15' and sys_platform != 'emscripten') or (python_full_version < '3.12' and sys_platform == 'emscripten')", ] +[[package]] +name = "altgraph" +version = "0.17.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/f8/97fdf103f38fed6792a1601dbc16cc8aac56e7459a9fff08c812d8ae177a/altgraph-0.17.5.tar.gz", hash = "sha256:c87b395dd12fabde9c99573a9749d67da8d29ef9de0125c7f536699b4a9bc9e7", size = 48428, upload-time = "2025-11-21T20:35:50.583Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/ba/000a1996d4308bc65120167c21241a3b205464a2e0b58deda26ae8ac21d1/altgraph-0.17.5-py2.py3-none-any.whl", hash = "sha256:f3a22400bce1b0c701683820ac4f3b159cd301acab067c51c653e06961600597", size = 21228, upload-time = "2025-11-21T20:35:49.444Z" }, +] + [[package]] name = "annotated-types" version = "0.8.0" @@ -811,6 +820,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/69/7a5d10ac409c4da0355e054a14371871da9b5557fcc42772cd00181c6cce/librt-0.16.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8ceafb70f2a4f0826f11031942e59c0728fd98da112dc346d4352bde1e486866", size = 116391, upload-time = "2026-09-29T00:55:07.484Z" }, ] +[[package]] +name = "macholib" +version = "1.16.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "altgraph", marker = "python_full_version < '3.12' or python_full_version >= '3.15' or sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/10/2f/97589876ea967487978071c9042518d28b958d87b17dceb7cdc1d881f963/macholib-1.16.4.tar.gz", hash = "sha256:f408c93ab2e995cd2c46e34fe328b130404be143469e41bc366c807448979362", size = 59427, upload-time = "2025-11-22T08:28:38.373Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/d1/a9f36f8ecdf0fb7c9b1e78c8d7af12b8c8754e74851ac7b94a8305540fc7/macholib-1.16.4-py2.py3-none-any.whl", hash = "sha256:da1a3fa8266e30f0ce7e97c6a54eefaae8edd1e5f86f3eb8b95457cae90265ea", size = 38117, upload-time = "2025-11-22T08:28:36.939Z" }, +] + [[package]] name = "markdown-it-py" version = "4.2.0" @@ -922,6 +943,9 @@ dev = [ { name = "tox" }, { name = "tox-uv" }, ] +dist = [ + { name = "pyinstaller" }, +] [package.metadata] requires-dist = [{ name = "keyring", specifier = ">=25.6,<26.0" }] @@ -940,6 +964,7 @@ dev = [ { name = "tox", specifier = ">=4.0,<5.0" }, { name = "tox-uv", specifier = ">=1.0,<2.0" }, ] +dist = [{ name = "pyinstaller", specifier = ">=6.22,<7" }] [[package]] name = "packaging" @@ -959,6 +984,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] +[[package]] +name = "pefile" +version = "2024.8.26" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/03/4f/2750f7f6f025a1507cd3b7218691671eecfd0bbebebe8b39aa0fe1d360b8/pefile-2024.8.26.tar.gz", hash = "sha256:3ff6c5d8b43e8c37bb6e6dd5085658d658a7a0bdcd20b6a07b1fcfc1c4e9d632", size = 76008, upload-time = "2024-08-26T20:58:38.155Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/16/12b82f791c7f50ddec566873d5bdd245baa1491bac11d15ffb98aecc8f8b/pefile-2024.8.26-py3-none-any.whl", hash = "sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f", size = 74766, upload-time = "2024-08-26T21:01:02.632Z" }, +] + [[package]] name = "platformdirs" version = "4.14.2" @@ -1191,6 +1225,46 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, ] +[[package]] +name = "pyinstaller" +version = "6.22.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "altgraph" }, + { name = "macholib", marker = "sys_platform == 'darwin'" }, + { name = "packaging" }, + { name = "pefile", marker = "sys_platform == 'win32'" }, + { name = "pyinstaller-hooks-contrib" }, + { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" }, + { name = "setuptools" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/63/41/f90302845945abd4ed647933ff5ee7c6ac93983187be67f897b6cb613331/pyinstaller-6.22.3.tar.gz", hash = "sha256:05eb2f5615503e72939a7224d68b4aff572c6b0438ee4a17d0a4b481f399362d", size = 4437180, upload-time = "2026-09-12T21:54:09.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/af/898f70947e27f8e65d55183c780e77112e023c0b4a6fba6255d4d563a27d/pyinstaller-6.22.3-py3-none-macosx_10_13_universal2.whl", hash = "sha256:052f4a1cd4f81092ccb7a18fe8ebc9ecf832a5917317e39fb3775af4e959b253", size = 1071847, upload-time = "2026-09-12T21:53:01.711Z" }, + { url = "https://files.pythonhosted.org/packages/c4/96/99f5184985141c2b024bfa61335e9142ae444555224f303186e59b7bb438/pyinstaller-6.22.3-py3-none-manylinux2014_aarch64.whl", hash = "sha256:312da84b4b31ab9750066a823734c11b7c68757fdd67c9f038bf19c330a954e4", size = 758172, upload-time = "2026-09-12T21:53:06.171Z" }, + { url = "https://files.pythonhosted.org/packages/69/9f/9ccb12cc1e6617042cb028fe79f0a756f5f03305bd14b584a4e043fe3844/pyinstaller-6.22.3-py3-none-manylinux2014_i686.whl", hash = "sha256:020d4fe0627f5c73dfbcfad1a6578ef354d5fe4bdccd9d8e5a615528f5a45d2b", size = 772135, upload-time = "2026-09-12T21:53:10.291Z" }, + { url = "https://files.pythonhosted.org/packages/c1/43/4b1d5193a88628c052db89f064433681076959a9f41d0d9f660001b49079/pyinstaller-6.22.3-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:9e4f7bd64b2103f14b4a6240fb9155e9fe7bc61391b4043bbddb7d3ebc8ab0fa", size = 770461, upload-time = "2026-09-12T21:53:14.592Z" }, + { url = "https://files.pythonhosted.org/packages/cb/83/f173f8757c618d83e116fa2b8e57c5cd796e5ad09792e664eabd6ac5edae/pyinstaller-6.22.3-py3-none-manylinux2014_s390x.whl", hash = "sha256:f82d0fb89f21c3ed6f482ee16f341bc59e8a31dbabb9bae9ef04e53ade4dc0d9", size = 764997, upload-time = "2026-09-12T21:53:19.079Z" }, + { url = "https://files.pythonhosted.org/packages/7b/b6/dd21d61fc5e25377be24eabf13e99e4e46548a5abe2bf7b15d8b3d9cc74a/pyinstaller-6.22.3-py3-none-manylinux2014_x86_64.whl", hash = "sha256:451a4ae14b719365bf1a2f0a99dae7b3463060061c3a394c70d5264cfb439528", size = 764974, upload-time = "2026-09-12T21:53:23.176Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fd/d9590942972b1fc205519f7ccffb0d5cd8eb1d6fa61edad319c71d25baed/pyinstaller-6.22.3-py3-none-musllinux_1_1_aarch64.whl", hash = "sha256:ea240b5dfa831ff673c97505eee0ec24670bccf71396c83109440348944c83d0", size = 764450, upload-time = "2026-09-12T21:53:27.419Z" }, + { url = "https://files.pythonhosted.org/packages/72/d6/f22c55d1768433b65c460b19a3136dd9769b6c74b786149b829344654c7d/pyinstaller-6.22.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:a2b6fc26601e8c2596c3d54981566934a3382e85d05d0fe91b55b6a8dcc6b282", size = 763863, upload-time = "2026-09-12T21:53:31.609Z" }, + { url = "https://files.pythonhosted.org/packages/c5/87/cf28cfd42ceca889171e6dd5e7f1553d4372db83d047049ffb7cf95fcbd4/pyinstaller-6.22.3-py3-none-win32.whl", hash = "sha256:46a3e30a118341a1ec20667a5a95aa7e0aa8c4fa129893c0151b3eb3f801a722", size = 1390905, upload-time = "2026-09-12T21:53:38.133Z" }, + { url = "https://files.pythonhosted.org/packages/24/83/c5422204772a27aef643280fdc887b7ef55679989096b21dceb1b9625fc4/pyinstaller-6.22.3-py3-none-win_amd64.whl", hash = "sha256:500bd58c7bf7e584a8435adccbd763a0b918d5c12b08d74ff50fd79b2915458b", size = 1454907, upload-time = "2026-09-12T21:53:44.812Z" }, + { url = "https://files.pythonhosted.org/packages/67/2e/ebc93968bf63f81b122e205da116b16036b653b7ce2cc8ad86e3ddd19586/pyinstaller-6.22.3-py3-none-win_arm64.whl", hash = "sha256:31df3cc4261e804a53d358b7897c293ec8b88b167a7cca06c78018085c855f97", size = 1402956, upload-time = "2026-09-12T21:53:51.369Z" }, +] + +[[package]] +name = "pyinstaller-hooks-contrib" +version = "2026.10" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/45/87/9a32062fb1296b43e866ec78313f887e12b09e6bc344c694647856bcd907/pyinstaller_hooks_contrib-2026.10.tar.gz", hash = "sha256:7e906c659522e592a1680f30f709ffb6333277141a695926aa7190592205c5e3", size = 181831, upload-time = "2026-11-10T00:20:01.695Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/10/4a6d13adaa93d0bbcfea082a78965e970cae7a8bfa82ac1557a1dc8f1cba/pyinstaller_hooks_contrib-2026.10-py3-none-any.whl", hash = "sha256:dfc3cde20a7ce6c92e803016e66eed4b7050467e2c5f886a3745d89b258c6d6d", size = 463652, upload-time = "2026-11-10T00:20:00.335Z" }, +] + [[package]] name = "pyproject-api" version = "1.12.2" @@ -1409,6 +1483,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/46/f5af3402b579fd5e11573ce652019a67074317e18c1935cc0b4ba9b35552/secretstorage-3.5.0-py3-none-any.whl", hash = "sha256:0ce65888c0725fcb2c5bc0fdb8e5438eece02c523557ea40ce0703c266248137", size = 15554, upload-time = "2025-11-23T19:02:51.545Z" }, ] +[[package]] +name = "setuptools" +version = "84.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" }, +] + [[package]] name = "stevedore" version = "5.9.1" From de0ffece901fa7e8d70878358c38cae1772f26f3 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:25 +0200 Subject: [PATCH 080/104] ci: build the self-contained files, start each, and gather the folder a deployment serves The Linux file is built in AlmaLinux 8 and started there, the keychain included, and in Debian 11: it needs the glibc it was built on or newer. Both Macs get a file, as a browser cannot tell them apart. --- .github/workflows/pull_request.yml | 133 +++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 667ea0f..72f6960 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -98,6 +98,139 @@ jobs: grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' pyz-plugin.txt grep -Eq '^d1 +- +Pretend Phone 7' pyz-phones.txt + # The connector as one self-contained file per system, which Deploy App's MDM page offers for + # download. PyInstaller is a build tool only; the file is packed as connector.json names it. Not signed. + # Every leg builds with uv's own Python (python-build-standalone), not the runner's. On Linux the + # file needs the glibc it was built on or newer, so that leg builds in AlmaLinux 8 (glibc 2.28). + # macos-15-intel: a browser cannot tell an Intel Mac from an Apple Silicon one, so both get a file. + one-file: + name: Self-contained file (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest, macos-15-intel] + env: + UV_PYTHON_PREFERENCE: only-managed + UV_PYTHON: "3.12" + ALMALINUX_8: almalinux:8@sha256:768bedc30fe0a536adb0a65d2eddb7caad364e514fbddd0ae9e026975f590342 + DEBIAN_11: debian:11@sha256:6f519a81440354a85eb592c5f32109ab80605f6b892455983a6f618bf87fabe9 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - name: Build and pack it, as README.rst says + if: runner.os != 'Linux' + run: uv run --locked --group dist python packaging/build.py + # The same command in AlmaLinux 8 with this runner's uv; the checkout is read-only in it, and copied + - name: Build and pack it on Linux, in AlmaLinux 8 + if: runner.os == 'Linux' + run: | + mkdir -p dist/mdm-connector + docker run --rm -e UV_PYTHON_PREFERENCE -e UV_PYTHON -v "$PWD:/src:ro" -v "$PWD/dist/mdm-connector:/out" \ + -v "$(command -v uv):/usr/local/bin/uv:ro" "$ALMALINUX_8" sh -euc ' + cp -r /src /work && cd /work && rm -rf .venv build dist + uv run --locked --group dist python packaging/build.py /out' + - run: echo "VERSION=$(uv version --short)" >> "$GITHUB_ENV" + # As an operator gets it: unpacked, started with nothing but its own files, writing only into a scratch home + - name: Unpack it and prove it runs, finds Fleet and serves the page + env: + HOME: ${{ runner.temp }}/home + LOCALAPPDATA: ${{ runner.temp }}/home + XDG_CONFIG_HOME: ${{ runner.temp }}/home + run: | + mkdir -p "$HOME" "$RUNNER_TEMP/unpacked" + for packed in dist/mdm-connector/*; do + case "$packed" in + *.zip) unzip -q "$packed" -d "$RUNNER_TEMP/unpacked" ;; + *.tar.gz) tar -xzf "$packed" -C "$RUNNER_TEMP/unpacked" ;; + *.exe) cp "$packed" "$RUNNER_TEMP/unpacked/odmdm-connector.exe" ;; + esac + done + cd "$RUNNER_TEMP/unpacked" + connector=./odmdm-connector + [ -f "$connector" ] || connector=./odmdm-connector.exe + test -x "$connector" + "$connector" --version | tr -d '\r' | tee version.txt + grep -Fqx "odmdm-connector, version $VERSION" version.txt + "$connector" mdms | tr -d '\r' | tr -s ' ' | tee mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' mdms.txt + # Fleet loads, and asks for its address + if "$connector" phones 2> phones.txt; then exit 1; fi + cat phones.txt + grep -Fq 'Fleet address is missing' phones.txt + port=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])') + "$connector" web --no-browser --port "$port" > web.txt 2>&1 & + pid=$! + for _ in $(seq 100); do grep -q 'Press Ctrl+C' web.txt && break; sleep 0.2; done + cat web.txt + curl -fsS --max-time 10 "http://127.0.0.1:$port/" -o page.html + grep -Fq '' page.html + curl -fsS --max-time 10 "http://127.0.0.1:$port/app.js" -o app.js + test -s app.js + kill "$pid" + wait "$pid" || true + # The floor, proven by starting it there. The keychain loads cryptography, which --version and + # mdms never do: with a Secret Service on a session bus the page must find the keychain usable. + - name: Start it on glibc 2.28 (AlmaLinux 8, keychain included) and 2.31 (Debian 11) + if: runner.os == 'Linux' + run: | + for image in "$ALMALINUX_8" "$DEBIAN_11"; do + docker run --rm -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$image" sh -euc ' + ldd --version | sed -n 1p + /c/odmdm-connector --version + /c/odmdm-connector mdms | grep "built in"' + done + docker run --rm --cap-add IPC_LOCK -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$ALMALINUX_8" sh -euc ' + dnf -q -y install gnome-keyring dbus-daemon > /dev/null + dbus-run-session -- sh -euc " + printf x | gnome-keyring-daemon --unlock --components=secrets > /dev/null + /c/odmdm-connector web --no-browser --port 8080 > /tmp/web.txt 2>&1 & + for _ in \$(seq 100); do grep -q Ctrl+C /tmp/web.txt && break; sleep 0.2; done + kill \$!" + cat /tmp/web.txt + grep -q Ctrl+C /tmp/web.txt + if grep -q keychain /tmp/web.txt; then exit 1; fi' + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: connector-${{ runner.os }}-${{ runner.arch }} + path: dist/mdm-connector/ + if-no-files-found: error + + # What a deployment serves beside its UI as mdm-connector/: the four files, the one file for + # Python (README.rst, "Into a network without internet") and connector.json, as ONE artifact + mdm-connector: + name: The mdm-connector folder + needs: one-file + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: connector-* + merge-multiple: true + path: dist/mdm-connector + - name: Add the one file for Python, without the demo plugin, and write connector.json + run: | + uv build --wheel --out-dir dist + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl + python -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o "dist/mdm-connector/odmdm-connector-$(uv version --short).pyz" + uv run --locked python packaging/manifest.py dist/mdm-connector + cat dist/mdm-connector/connector.json + jq -e '(.files | length) == 5 and .mdms == [{"name": "fleet", "title": "Fleet"}]' dist/mdm-connector/connector.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mdm-connector + path: dist/mdm-connector/ + if-no-files-found: error + snyk-test: name: Run Snyk test runs-on: ubuntu-latest From 9180d6e3e7cd466649aea88ea7273426098d0fb2 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:25 +0200 Subject: [PATCH 081/104] docs: the file to download, how it is built, and that it is not signed --- README.rst | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/README.rst b/README.rst index bc84658..ed94960 100644 --- a/README.rst +++ b/README.rst @@ -34,6 +34,7 @@ The connector's everyday face is a page in your browser, served by this computer odmdm-connector web +or ``odmdm-connector`` alone, as a double-click on a downloaded file does (see `A file to download`_). It opens the page in your default browser and prints its address, and goes on until Ctrl+C. ``--port N`` serves it on another port than 8737. The browser does not open by itself on a computer without a desktop, with ``--no-browser``, or when the default browser may not read the connector's @@ -123,6 +124,35 @@ Its limits: nor drive it. A program that runs as you can read the key from your browser's storage, as it can read anything else of yours. +A file to download +------------------ + +For an operator who has no Python, the connector is also one self-contained file per system, which +Deploy App's MDM page offers for download when a deployment serves them: Python, the connector, +Fleet and keyring are inside, so the token can be kept in the keychain. Started without a command, +as by a double-click, it opens the page; every command works as above. Each system has its own +file: ``odmdm-connector--windows-x64.exe`` as it is, and for macOS and Linux one +executable named ``odmdm-connector`` in a ``.zip`` or ``.tar.gz``, which keeps it executable through +a browser's download. Beside them, ``connector.json`` says the version, the MDMs built in, and each +file's system, size and SHA-256; Deploy App's page reads it. + +The files are NOT SIGNED yet, so the system warns at the first start. On macOS it refuses to open +the file: open **System Settings**, **Privacy & Security**, and press **Open Anyway** for +``odmdm-connector``. On Windows, SmartScreen says it protected the PC: press **More info**, then +**Run anyway**. Compare the file's SHA-256 with ``connector.json`` before doing either. + +Build the file for the computer you are on from a checkout, with PyInstaller, a build tool kept in +a dependency group of its own. ``packaging/build.py`` holds the build and is what CI runs:: + + uv run --locked --group dist python packaging/build.py + +It writes the packed file into ``dist/mdm-connector``. CI builds it on Windows, macOS (Apple +Silicon and Intel) and Linux, starts each, adds the one file for Python below, and writes the +manifest into that folder with ``uv run python packaging/manifest.py dist/mdm-connector``: the +artifact ``mdm-connector`` is the folder a deployment serves. The Linux file needs glibc 2.28 or +newer: CI builds it in AlmaLinux 8 (glibc 2.28) and starts it there, the keychain included, and in +Debian 11. + Into a network without internet ------------------------------- From 5d8ab014357d0794c4212c173d97032f85d62c38 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:25 +0200 Subject: [PATCH 082/104] docs: packaging in the layout, and why every leg builds with uv's own Python --- AGENTS.md | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7d3453a..1d57622 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,14 @@ The command line knows an MDM only through one contract; Fleet is the plugin bui The repository runs the checks against the fake, Fleet over the stub, and the demo. - `examples/odmdm-connector-demo/`: a plugin as a package of its own. CI builds it and the connector and installs both as an operator would. +- `packaging/`: the self-contained file per system that Deploy App's MDM page offers. `build.py` + runs PyInstaller, a build tool in the `dist` dependency group only, on `launcher.py` and packs the + result; `manifest.py DIR` writes `DIR/connector.json`, the contract with Deploy App's UI (its + test: `tests/test_manifest.py`). The file names, `os`, `arch` and the order are that contract: + change them only together with Deploy App. Started without a command, the connector does what + `web` does, as a downloaded file is started by a double-click. CI builds every file with uv's own + Python (`UV_PYTHON_PREFERENCE=only-managed`), one known build on every system instead of each + runner's, and the Linux file in AlmaLinux 8, as it needs the glibc it was built on or newer. - `fleet_plugin.py`: Fleet behind the contract, registered in `pyproject.toml` as `fleet`. `fleet.py`: Fleet's HTTP dialect. `template.py` and the shipped `template.json`: what a deployment's phones need. @@ -52,12 +60,17 @@ desktop (no `DISPLAY` or `WAYLAND_DISPLAY` outside Windows and macOS) it opens n `webbrowser` would start a text browser in the terminal. Tests replace the opener with a fake; `conftest.py` still makes `webbrowser.open` raise in every test. +The self-contained file of `packaging/` is PyInstaller's one-file mode: its bootloader, not the +connector's code, unpacks Python and the package into a new temporary folder and runs them as a +child process of itself, which it removes again when the connector stops. Nothing of the +connector's code changes for it, and every rule above holds inside it. + ## One dependency: keyring, for the token Runtime code under `src/` imports nothing but Python's standard library and the package itself, with one exception: `store.py` imports keyring, inside `platform_backend()`, to keep the MDM token in the system's keychain. Nothing else uses keyring, and the connector must run without it: the -one-file build leaves it out, and there `platform_backend()` is None and the token is held until the +one-file Python build (`.pyz`) leaves it out, and there `platform_backend()` is None and the token is held until the connector stops. `tests/test_standard_library.py` fails on any other import, and on keyring anywhere but there; CI runs the one file without it. The owner decided on 2026-11-21 first that the connector goes into a network without internet as one file with no dependencies (README.rst, "Into a network @@ -130,7 +143,7 @@ giving callsigns, one phone, the settings and removing a Deploy App. Keep these - Known limits: the button in Deploy App talks to whatever listens on port 8737 of this computer, so on a computer shared with other users the settings line is copied by hand instead. Another program on this computer can slow the page down, but cannot read or drive it without the key. -- `web` opens the page in the default browser through `browser.py` only, and prints the address; +- `web`, or no command at all, opens the page in the default browser through `browser.py` only, and prints the address; `--no-browser` only prints it. The address is printed first and the browser asked from a daemon thread as the page starts to serve, since some openers wait for the browser or never return. Deploy App's button finds the page only in the browser where the address was opened. @@ -153,6 +166,7 @@ strands every enrolled phone's key. and no phone. - Hooks, before every commit: `uv run prek run --all-files`. Once per clone: `uv run prek install --hook-type pre-commit --hook-type commit-msg` +- Self-contained file for this computer: `uv run --locked --group dist python packaging/build.py` - Version bump, once per pull request, in its own commit: `uv run bump-my-version bump patch|minor|major` ## Crown jewels From 9bb945f1c0658d013ae15445c8a0b9f37c362ad4 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 01:53:25 +0200 Subject: [PATCH 083/104] chore: bump version to 1.3.0+261122 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/odmdm_connector/__init__.py | 2 +- tests/test_odmdm_connector.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index c1c1995..ecb2860 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.2.0+261121" +current_version = "1.3.0+261122" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index 085e485..5b7956b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "1.2.0+261121" +version = "1.3.0+261122" description = "Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index 15a69a7..17b744c 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ """Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" -__version__ = "1.2.0+261121" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.3.0+261122" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index 895773d..0e6e7ae 100644 --- a/tests/test_odmdm_connector.py +++ b/tests/test_odmdm_connector.py @@ -5,4 +5,4 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.2.0+261121" + assert __version__ == "1.3.0+261122" diff --git a/uv.lock b/uv.lock index aaf146d..56417ab 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "1.2.0+261121" +version = "1.3.0+261122" source = { editable = "." } dependencies = [ { name = "keyring" }, From 10b002325800650b12d5713ae74fa8bb6e8ac56b Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 04:22:46 +0200 Subject: [PATCH 084/104] ci: build the connector's files in a workflow of its own, called on every change The same two jobs, moved, so that the release can run exactly what a pull request runs. --- .github/workflows/mdm_connector.yml | 152 ++++++++++++++++++++++++++++ .github/workflows/pull_request.yml | 134 +----------------------- 2 files changed, 155 insertions(+), 131 deletions(-) create mode 100644 .github/workflows/mdm_connector.yml diff --git a/.github/workflows/mdm_connector.yml b/.github/workflows/mdm_connector.yml new file mode 100644 index 0000000..6b5253a --- /dev/null +++ b/.github/workflows/mdm_connector.yml @@ -0,0 +1,152 @@ +# The mdm-connector folder Deploy App's UI serves, built once for every caller: the self-contained +# file per system and the one file for Python, each started, and connector.json, as the artifact +# mdm-connector. pull_request.yml calls it on the change, push_to_main.yml on the commit it has just tagged. +on: + workflow_call: + inputs: + ref: + description: "Commit, branch or tag to build; empty builds the commit that triggered the caller" + type: string + required: false + default: "" + +permissions: + contents: read + +jobs: + # The connector as one self-contained file per system, which Deploy App's MDM page offers for + # download. PyInstaller is a build tool only; the file is packed as connector.json names it. Not signed. + # Every leg builds with uv's own Python (python-build-standalone), not the runner's. On Linux the + # file needs the glibc it was built on or newer, so that leg builds in AlmaLinux 8 (glibc 2.28). + # macos-15-intel: a browser cannot tell an Intel Mac from an Apple Silicon one, so both get a file. + one-file: + name: Self-contained file (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest, macos-15-intel] + env: + UV_PYTHON_PREFERENCE: only-managed + UV_PYTHON: "3.12" + ALMALINUX_8: almalinux:8@sha256:768bedc30fe0a536adb0a65d2eddb7caad364e514fbddd0ae9e026975f590342 + DEBIAN_11: debian:11@sha256:6f519a81440354a85eb592c5f32109ab80605f6b892455983a6f618bf87fabe9 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - name: Build and pack it, as README.rst says + if: runner.os != 'Linux' + run: uv run --locked --group dist python packaging/build.py + # The same command in AlmaLinux 8 with this runner's uv; the checkout is read-only in it, and copied + - name: Build and pack it on Linux, in AlmaLinux 8 + if: runner.os == 'Linux' + run: | + mkdir -p dist/mdm-connector + docker run --rm -e UV_PYTHON_PREFERENCE -e UV_PYTHON -v "$PWD:/src:ro" -v "$PWD/dist/mdm-connector:/out" \ + -v "$(command -v uv):/usr/local/bin/uv:ro" "$ALMALINUX_8" sh -euc ' + cp -r /src /work && cd /work && rm -rf .venv build dist + uv run --locked --group dist python packaging/build.py /out' + - run: echo "VERSION=$(uv version --short)" >> "$GITHUB_ENV" + # As an operator gets it: unpacked, started with nothing but its own files, writing only into a scratch home + - name: Unpack it and prove it runs, finds Fleet and serves the page + env: + HOME: ${{ runner.temp }}/home + LOCALAPPDATA: ${{ runner.temp }}/home + XDG_CONFIG_HOME: ${{ runner.temp }}/home + run: | + mkdir -p "$HOME" "$RUNNER_TEMP/unpacked" + for packed in dist/mdm-connector/*; do + case "$packed" in + *.zip) unzip -q "$packed" -d "$RUNNER_TEMP/unpacked" ;; + *.tar.gz) tar -xzf "$packed" -C "$RUNNER_TEMP/unpacked" ;; + *.exe) cp "$packed" "$RUNNER_TEMP/unpacked/odmdm-connector.exe" ;; + esac + done + cd "$RUNNER_TEMP/unpacked" + connector=./odmdm-connector + [ -f "$connector" ] || connector=./odmdm-connector.exe + test -x "$connector" + "$connector" --version | tr -d '\r' | tee version.txt + grep -Fqx "odmdm-connector, version $VERSION" version.txt + "$connector" mdms | tr -d '\r' | tr -s ' ' | tee mdms.txt + grep -Eqx 'fleet odmdm-connector [^ ]+ built in' mdms.txt + # Fleet loads, and asks for its address + if "$connector" phones 2> phones.txt; then exit 1; fi + cat phones.txt + grep -Fq 'Fleet address is missing' phones.txt + port=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])') + "$connector" web --no-browser --port "$port" > web.txt 2>&1 & + pid=$! + for _ in $(seq 100); do grep -q 'Press Ctrl+C' web.txt && break; sleep 0.2; done + cat web.txt + curl -fsS --max-time 10 "http://127.0.0.1:$port/" -o page.html + grep -Fq '' page.html + curl -fsS --max-time 10 "http://127.0.0.1:$port/app.js" -o app.js + test -s app.js + kill "$pid" + wait "$pid" || true + # The floor, proven by starting it there. The keychain loads cryptography, which --version and + # mdms never do: with a Secret Service on a session bus the page must find the keychain usable. + - name: Start it on glibc 2.28 (AlmaLinux 8, keychain included) and 2.31 (Debian 11) + if: runner.os == 'Linux' + run: | + for image in "$ALMALINUX_8" "$DEBIAN_11"; do + docker run --rm -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$image" sh -euc ' + ldd --version | sed -n 1p + /c/odmdm-connector --version + /c/odmdm-connector mdms | grep "built in"' + done + docker run --rm --cap-add IPC_LOCK -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$ALMALINUX_8" sh -euc ' + dnf -q -y install gnome-keyring dbus-daemon > /dev/null + dbus-run-session -- sh -euc " + printf x | gnome-keyring-daemon --unlock --components=secrets > /dev/null + /c/odmdm-connector web --no-browser --port 8080 > /tmp/web.txt 2>&1 & + for _ in \$(seq 100); do grep -q Ctrl+C /tmp/web.txt && break; sleep 0.2; done + kill \$!" + cat /tmp/web.txt + grep -q Ctrl+C /tmp/web.txt + if grep -q keychain /tmp/web.txt; then exit 1; fi' + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: connector-${{ runner.os }}-${{ runner.arch }} + path: dist/mdm-connector/ + if-no-files-found: error + + # What a deployment serves beside its UI as mdm-connector/: the four files, the one file for + # Python (README.rst, "Into a network without internet") and connector.json, as ONE artifact + mdm-connector: + name: The mdm-connector folder + needs: one-file + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 + with: + python-version: "3.12" + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: connector-* + merge-multiple: true + path: dist/mdm-connector + - name: Add the one file for Python, without the demo plugin, and write connector.json + run: | + uv build --wheel --out-dir dist + uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl + python -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o "dist/mdm-connector/odmdm-connector-$(uv version --short).pyz" + uv run --locked python packaging/manifest.py dist/mdm-connector + cat dist/mdm-connector/connector.json + jq -e '(.files | length) == 5 and .mdms == [{"name": "fleet", "title": "Fleet"}]' dist/mdm-connector/connector.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mdm-connector + path: dist/mdm-connector/ + if-no-files-found: error diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 72f6960..b6989e8 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -98,138 +98,10 @@ jobs: grep -Fq 'a plugin from odmdm-connector-demo 1.0.0' pyz-plugin.txt grep -Eq '^d1 +- +Pretend Phone 7' pyz-phones.txt - # The connector as one self-contained file per system, which Deploy App's MDM page offers for - # download. PyInstaller is a build tool only; the file is packed as connector.json names it. Not signed. - # Every leg builds with uv's own Python (python-build-standalone), not the runner's. On Linux the - # file needs the glibc it was built on or newer, so that leg builds in AlmaLinux 8 (glibc 2.28). - # macos-15-intel: a browser cannot tell an Intel Mac from an Apple Silicon one, so both get a file. - one-file: - name: Self-contained file (${{ matrix.os }}) - runs-on: ${{ matrix.os }} - strategy: - fail-fast: false - matrix: - os: [ubuntu-latest, windows-latest, macos-latest, macos-15-intel] - env: - UV_PYTHON_PREFERENCE: only-managed - UV_PYTHON: "3.12" - ALMALINUX_8: almalinux:8@sha256:768bedc30fe0a536adb0a65d2eddb7caad364e514fbddd0ae9e026975f590342 - DEBIAN_11: debian:11@sha256:6f519a81440354a85eb592c5f32109ab80605f6b892455983a6f618bf87fabe9 - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 - with: - python-version: "3.12" - - name: Build and pack it, as README.rst says - if: runner.os != 'Linux' - run: uv run --locked --group dist python packaging/build.py - # The same command in AlmaLinux 8 with this runner's uv; the checkout is read-only in it, and copied - - name: Build and pack it on Linux, in AlmaLinux 8 - if: runner.os == 'Linux' - run: | - mkdir -p dist/mdm-connector - docker run --rm -e UV_PYTHON_PREFERENCE -e UV_PYTHON -v "$PWD:/src:ro" -v "$PWD/dist/mdm-connector:/out" \ - -v "$(command -v uv):/usr/local/bin/uv:ro" "$ALMALINUX_8" sh -euc ' - cp -r /src /work && cd /work && rm -rf .venv build dist - uv run --locked --group dist python packaging/build.py /out' - - run: echo "VERSION=$(uv version --short)" >> "$GITHUB_ENV" - # As an operator gets it: unpacked, started with nothing but its own files, writing only into a scratch home - - name: Unpack it and prove it runs, finds Fleet and serves the page - env: - HOME: ${{ runner.temp }}/home - LOCALAPPDATA: ${{ runner.temp }}/home - XDG_CONFIG_HOME: ${{ runner.temp }}/home - run: | - mkdir -p "$HOME" "$RUNNER_TEMP/unpacked" - for packed in dist/mdm-connector/*; do - case "$packed" in - *.zip) unzip -q "$packed" -d "$RUNNER_TEMP/unpacked" ;; - *.tar.gz) tar -xzf "$packed" -C "$RUNNER_TEMP/unpacked" ;; - *.exe) cp "$packed" "$RUNNER_TEMP/unpacked/odmdm-connector.exe" ;; - esac - done - cd "$RUNNER_TEMP/unpacked" - connector=./odmdm-connector - [ -f "$connector" ] || connector=./odmdm-connector.exe - test -x "$connector" - "$connector" --version | tr -d '\r' | tee version.txt - grep -Fqx "odmdm-connector, version $VERSION" version.txt - "$connector" mdms | tr -d '\r' | tr -s ' ' | tee mdms.txt - grep -Eqx 'fleet odmdm-connector [^ ]+ built in' mdms.txt - # Fleet loads, and asks for its address - if "$connector" phones 2> phones.txt; then exit 1; fi - cat phones.txt - grep -Fq 'Fleet address is missing' phones.txt - port=$(python -c 'import socket; s = socket.socket(); s.bind(("127.0.0.1", 0)); print(s.getsockname()[1])') - "$connector" web --no-browser --port "$port" > web.txt 2>&1 & - pid=$! - for _ in $(seq 100); do grep -q 'Press Ctrl+C' web.txt && break; sleep 0.2; done - cat web.txt - curl -fsS --max-time 10 "http://127.0.0.1:$port/" -o page.html - grep -Fq '' page.html - curl -fsS --max-time 10 "http://127.0.0.1:$port/app.js" -o app.js - test -s app.js - kill "$pid" - wait "$pid" || true - # The floor, proven by starting it there. The keychain loads cryptography, which --version and - # mdms never do: with a Secret Service on a session bus the page must find the keychain usable. - - name: Start it on glibc 2.28 (AlmaLinux 8, keychain included) and 2.31 (Debian 11) - if: runner.os == 'Linux' - run: | - for image in "$ALMALINUX_8" "$DEBIAN_11"; do - docker run --rm -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$image" sh -euc ' - ldd --version | sed -n 1p - /c/odmdm-connector --version - /c/odmdm-connector mdms | grep "built in"' - done - docker run --rm --cap-add IPC_LOCK -e HOME=/tmp -v "$RUNNER_TEMP/unpacked:/c:ro" "$ALMALINUX_8" sh -euc ' - dnf -q -y install gnome-keyring dbus-daemon > /dev/null - dbus-run-session -- sh -euc " - printf x | gnome-keyring-daemon --unlock --components=secrets > /dev/null - /c/odmdm-connector web --no-browser --port 8080 > /tmp/web.txt 2>&1 & - for _ in \$(seq 100); do grep -q Ctrl+C /tmp/web.txt && break; sleep 0.2; done - kill \$!" - cat /tmp/web.txt - grep -q Ctrl+C /tmp/web.txt - if grep -q keychain /tmp/web.txt; then exit 1; fi' - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: connector-${{ runner.os }}-${{ runner.arch }} - path: dist/mdm-connector/ - if-no-files-found: error - - # What a deployment serves beside its UI as mdm-connector/: the four files, the one file for - # Python (README.rst, "Into a network without internet") and connector.json, as ONE artifact + # The connector's files and the mdm-connector artifact, defined once in mdm_connector.yml mdm-connector: - name: The mdm-connector folder - needs: one-file - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: pvarki/config-ci-library/.github/actions/setup-python@fffb737257f6a08b0bbd03aa8f9e090cc610e7b6 # v0.15.0+261104 - with: - python-version: "3.12" - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - pattern: connector-* - merge-multiple: true - path: dist/mdm-connector - - name: Add the one file for Python, without the demo plugin, and write connector.json - run: | - uv build --wheel --out-dir dist - uv pip install --target build/pyz --no-deps dist/odmdm_connector-*.whl - python -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o "dist/mdm-connector/odmdm-connector-$(uv version --short).pyz" - uv run --locked python packaging/manifest.py dist/mdm-connector - cat dist/mdm-connector/connector.json - jq -e '(.files | length) == 5 and .mdms == [{"name": "fleet", "title": "Fleet"}]' dist/mdm-connector/connector.json - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: mdm-connector - path: dist/mdm-connector/ - if-no-files-found: error + name: Connector files + uses: ./.github/workflows/mdm_connector.yml snyk-test: name: Run Snyk test From b41a1782c8899ed0e8d1c73933fe7d5e6b075e08 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 04:22:46 +0200 Subject: [PATCH 085/104] ci: attach the files to each release: one archive, its SHA-256, and each file's Built for the commit just tagged. The folder is refused when it holds anything Deploy App's UI image would not unpack, and what a release already carries is never replaced. --- .github/workflows/push_to_main.yml | 67 ++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) diff --git a/.github/workflows/push_to_main.yml b/.github/workflows/push_to_main.yml index 5d72964..d0cc352 100644 --- a/.github/workflows/push_to_main.yml +++ b/.github/workflows/push_to_main.yml @@ -29,6 +29,8 @@ jobs: contents: write packages: read pull-requests: read + outputs: + tag: ${{ steps.tag.outputs.tag }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -42,3 +44,68 @@ jobs: release: ${{ steps.tag.outputs.version }} product: odmdm-connector attach-to-release: "true" + + # The release's mdm-connector folder, built from the tagged commit by the same workflow as a change + mdm-connector: + name: Connector files + needs: release + if: needs.release.outputs.tag != '' + uses: ./.github/workflows/mdm_connector.yml + with: + ref: ${{ github.sha }} # the tag's commit (tag-release tags only HEAD); no '+' through a checkout ref + + # The folder as ONE archive and its SHA-256 on the release: what Deploy App's UI image fetches and + # pins; and SHA256SUMS, each file's SHA-256, which the MDM page shows for the file it offers. The + # names carry no version, so that only the tag changes in the address. Assets already on the release + # are kept: a UI image may pin the archive's SHA-256, and a rebuild would not match it. + publish-mdm-connector: + name: Attach the mdm-connector folder to the release + needs: [release, mdm-connector] + runs-on: ubuntu-latest + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ needs.release.outputs.tag }} + defaults: + run: + shell: bash # with pipefail, so that a failing tar fails the pack + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: mdm-connector + path: mdm-connector + # The gate refuses a folder Deploy App's UI image would not unpack: a file connector.json does not + # name, anything but a plain file, a name outside its pattern. A release's assets are never replaced. + - name: Pack it as mdm-connector.tar.gz, with its SHA-256 and each file's beside it + run: | + (cd mdm-connector && jq -r '.files[] | "\(.sha256) \(.file)"' connector.json | sha256sum -c --strict) + diff <({ jq -r '.files[].file' mdm-connector/connector.json; echo connector.json; } | LC_ALL=C sort) \ + <(find mdm-connector -mindepth 1 -maxdepth 1 -printf '%f\n' | LC_ALL=C sort) + test -z "$(find mdm-connector -mindepth 1 ! -type f)" + jq -e '(.files | length > 0) and all(.files[].file; test("^[A-Za-z0-9_+-][A-Za-z0-9._+-]{0,119}$"))' \ + mdm-connector/connector.json > /dev/null + (cd mdm-connector && jq -r '.files[].file' connector.json | LC_ALL=C sort | xargs -r -d '\n' sha256sum --) > SHA256SUMS + (cd mdm-connector && sha256sum -c --strict ../SHA256SUMS) + tar --sort=name --owner=0 --group=0 --numeric-owner --mode=u=rwX,go=rX --mtime=@0 -cf - mdm-connector | gzip -n > mdm-connector.tar.gz + sha256sum mdm-connector.tar.gz | tee mdm-connector.tar.gz.sha256 + sha256sum -c --strict mdm-connector.tar.gz.sha256 + # All three or none: a rebuilt SHA256SUMS would not describe an archive already attached + - name: Attach the three to the release + run: | + assets=(mdm-connector.tar.gz mdm-connector.tar.gz.sha256 SHA256SUMS) + gh release view "$TAG" --json assets --jq '.assets[].name' > attached.txt + present=0 + for asset in "${assets[@]}"; do + if grep -Fqx "$asset" attached.txt; then present=$((present + 1)); fi + done + if [ "$present" -eq "${#assets[@]}" ]; then + echo "::warning::$TAG already has ${assets[*]}, kept as they are" + exit 0 + fi + if [ "$present" -ne 0 ]; then + echo "::error::$TAG has only some of ${assets[*]}: complete or remove them by hand, and never replace an attached archive" + exit 1 + fi + gh release upload "$TAG" "${assets[@]}" From 1eae1484c4a99b34f3407558c53852e776c80154 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 04:22:46 +0200 Subject: [PATCH 086/104] docs: where a release's files and checksums are, and what to compare --- README.rst | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/README.rst b/README.rst index ed94960..5bc67d1 100644 --- a/README.rst +++ b/README.rst @@ -139,7 +139,8 @@ file's system, size and SHA-256; Deploy App's page reads it. The files are NOT SIGNED yet, so the system warns at the first start. On macOS it refuses to open the file: open **System Settings**, **Privacy & Security**, and press **Open Anyway** for ``odmdm-connector``. On Windows, SmartScreen says it protected the PC: press **More info**, then -**Run anyway**. Compare the file's SHA-256 with ``connector.json`` before doing either. +**Run anyway**. Before doing either, compare the file's SHA-256 with its line in the release's +``SHA256SUMS`` (below). Build the file for the computer you are on from a checkout, with PyInstaller, a build tool kept in a dependency group of its own. ``packaging/build.py`` holds the build and is what CI runs:: @@ -153,6 +154,27 @@ artifact ``mdm-connector`` is the folder a deployment serves. The Linux file nee newer: CI builds it in AlmaLinux 8 (glibc 2.28) and starts it there, the keychain included, and in Debian 11. +Each release carries that folder, built from the release's tag, as one archive that unpacks to +``mdm-connector/``, the archive's SHA-256 beside it, and ``SHA256SUMS``, one line per file of the +folder (``connector.json`` aside), all in the form ``sha256sum -c`` reads:: + + https://github.com/pvarki/python-odmdm-fleet/releases/download/v/mdm-connector.tar.gz + https://github.com/pvarki/python-odmdm-fleet/releases/download/v/mdm-connector.tar.gz.sha256 + https://github.com/pvarki/python-odmdm-fleet/releases/download/v/SHA256SUMS + +The ``+`` in the version is written ``%2B`` in the address, as GitHub writes it: the tag of +1.3.0+261122 is ``v1.3.0%2B261122`` there. Check an archive before unpacking it:: + + sha256sum -c mdm-connector.tar.gz.sha256 + tar -xzf mdm-connector.tar.gz + +Deploy App's UI image fetches the archive of one release, pins its SHA-256 and serves the folder +beside the app: an image refuses to build from an archive with any other SHA-256. A release's +assets are never replaced, so the SHA-256 the MDM page shows for a file is the line for that file in +the release's ``SHA256SUMS``. Check a downloaded file in its folder before the first start:: + + sha256sum -c --ignore-missing SHA256SUMS + Into a network without internet ------------------------------- From 284433f7609f0ba5017fc511c9223ef263979d86 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 04:22:46 +0200 Subject: [PATCH 087/104] docs: the called workflow, the release's three files, and which jobs may write --- AGENTS.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 1d57622..9a93e84 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,6 +36,16 @@ The command line knows an MDM only through one contract; Fleet is the plugin bui `web` does, as a downloaded file is started by a double-click. CI builds every file with uv's own Python (`UV_PYTHON_PREFERENCE=only-managed`), one known build on every system instead of each runner's, and the Linux file in AlmaLinux 8, as it needs the glibc it was built on or newer. + The build is defined once, in `.github/workflows/mdm_connector.yml` (`workflow_call`), which + `pull_request.yml` calls on every change and `push_to_main.yml` on the commit it has just tagged + (by `github.sha`, so no `+` goes through a checkout ref). Besides `release`, which tags and creates + the release, only `publish-mdm-connector` there has `contents: write`: it refuses a folder that + Deploy App's UI image would refuse (a file `connector.json` does not name, anything but a plain + file, a name outside its pattern), packs the folder as `mdm-connector.tar.gz` (unpacks to + `mdm-connector/`) and attaches it with `mdm-connector.tar.gz.sha256` and `SHA256SUMS` (each file's + SHA-256 but `connector.json`'s, sorted by name), all three or none. No version in any name, as + GitHub may rename an asset with a `+`: only the tag changes in the address. Deploy App's UI image + pins that archive's SHA-256, so assets already on a release are never replaced. - `fleet_plugin.py`: Fleet behind the contract, registered in `pyproject.toml` as `fleet`. `fleet.py`: Fleet's HTTP dialect. `template.py` and the shipped `template.json`: what a deployment's phones need. From 2fac1f4df2682b042dde59300ff4f64a75a5e9d6 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 088/104] feat: a plugin may send its policy again, and a field's default may name the deployment send_policy is a capability a plugin lists as missing when it cannot. {deployment} in a default is the first label of the Deploy App's host, lower case, and only of a plain DNS name. --- src/odmdm_connector/mdm.py | 31 +++++++++++++++++++++---- src/odmdm_connector/testing/contract.py | 23 +++++++++++++++++- src/odmdm_connector/testing/fake.py | 4 +++- tests/test_mdm.py | 30 +++++++++++++++++++++++- tests/test_testing.py | 15 ++++++++++-- 5 files changed, 94 insertions(+), 9 deletions(-) diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py index c6da97c..1c895e7 100644 --- a/src/odmdm_connector/mdm.py +++ b/src/odmdm_connector/mdm.py @@ -14,7 +14,7 @@ from enum import Enum from typing import ClassVar, Protocol -from .settings import Settings +from .settings import HOST, Settings API_VERSION = 1 @@ -22,7 +22,11 @@ SETUP = "setup" SET_CHALLENGE = "set_challenge" ASK_AGAIN = "ask_again" -CAPABILITIES = (SETUP, SET_CHALLENGE, ASK_AGAIN) +#: setup with force: the policy sent to the phones again even if unchanged +SEND_POLICY = "send_policy" +CAPABILITIES = (SETUP, SET_CHALLENGE, ASK_AGAIN, SEND_POLICY) +#: In a Field's default, the deployment's name: the first label of its Deploy App's host +DEPLOYMENT = "{deployment}" class State(Enum): @@ -61,7 +65,8 @@ class Field: A secret is never taken from an option or a plain environment variable, only from a file. A required one must be given: the window does not connect without it, and the command line - says how to give it. + says how to give it. DEPLOYMENT in the default stands for the deployment's name, so that + "{deployment} DeployApp" is "golden-monkey DeployApp" for golden-monkey.example.fi. """ key: str @@ -73,6 +78,20 @@ class Field: #: Rarely changed: the window shows it only when asked advanced: bool = False + def default_for(self, host: str) -> str: + """The default for the Deploy App on this host; none when it names the deployment and the host is not one + + The host is trimmed and taken in lower case, so the page and the command line give the same + default for the same Deploy App; anything but a plain DNS name, such as an address with its + scheme, gives none. + """ + if DEPLOYMENT not in self.default: + return self.default + host = host.strip().lower() + if not HOST.fullmatch(host): + return "" + return self.default.replace(DEPLOYMENT, host.split(".")[0]) + @dataclass(frozen=True) class Step: @@ -124,7 +143,9 @@ def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> """Set the MDM up for this Deploy App, first time or again Idempotent. Never replaces a certificate template on a group that has phones. dry_run - checks what would be stated and stops before the MDM is changed. + checks what would be stated and stops before the MDM is changed. force sends the policy to + the phones again even if unchanged, for a phone whose policy the MDM overwrote; the phones + keep their certificates and apps. An MDM that cannot lists SEND_POLICY in missing. """ def set_challenge(self, window: Settings) -> None: @@ -152,6 +173,8 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: "API_VERSION", "ASK_AGAIN", "CAPABILITIES", + "DEPLOYMENT", + "SEND_POLICY", "SETUP", "SET_CHALLENGE", "Field", diff --git a/src/odmdm_connector/testing/contract.py b/src/odmdm_connector/testing/contract.py index 9f87f5f..eaa57e8 100644 --- a/src/odmdm_connector/testing/contract.py +++ b/src/odmdm_connector/testing/contract.py @@ -19,7 +19,19 @@ def test_the_contract(check: contract.Check) -> None: from collections.abc import Callable from typing import Protocol -from ..mdm import API_VERSION, ASK_AGAIN, CAPABILITIES, SET_CHALLENGE, SETUP, Mdm, MdmError, Phone, State, Step +from ..mdm import ( + API_VERSION, + ASK_AGAIN, + CAPABILITIES, + SEND_POLICY, + SET_CHALLENGE, + SETUP, + Mdm, + MdmError, + Phone, + State, + Step, +) from ..settings import Settings #: An enrolment window to hand the MDM; the challenge is not a real one @@ -157,6 +169,14 @@ def sets_up(factory: Factory) -> None: _require(steps and all(isinstance(step, Step) for step in steps), "setup must report Steps") +def sends_the_policy_again(factory: Factory) -> None: + mdm = factory() + if SETUP in mdm.missing or _lacking(mdm, SEND_POLICY, lambda: list(mdm.setup(WINDOW, force=True, dry_run=True))): + return + steps = list(mdm.setup(WINDOW, force=True, dry_run=True)) + _require(steps and all(isinstance(step, Step) for step in steps), "setup with force must report Steps") + + CHECKS: tuple[Check, ...] = ( declares_the_contract_version, declares_its_fields, @@ -168,4 +188,5 @@ def sets_up(factory: Factory) -> None: asks_again, sets_the_challenge, sets_up, + sends_the_policy_again, ) diff --git a/src/odmdm_connector/testing/fake.py b/src/odmdm_connector/testing/fake.py index 97855f7..a3d9f18 100644 --- a/src/odmdm_connector/testing/fake.py +++ b/src/odmdm_connector/testing/fake.py @@ -4,7 +4,7 @@ from dataclasses import replace from typing import ClassVar -from ..mdm import API_VERSION, ASK_AGAIN, SET_CHALLENGE, SETUP, Field, MdmError, Phone, State, Step +from ..mdm import API_VERSION, ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, MdmError, Phone, State, Step from ..settings import Settings #: The group's phones when a test gives none: two waiting for a name, one with its certificate @@ -72,6 +72,8 @@ def _waiting(self, phone: str, callsign: str | None = None) -> None: def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: self._able(SETUP) + if force: + self._able(SEND_POLICY) yield Step(f"Group {self.values.get('group', 'Deploy App')} enrols at {window.scep_url}", True) if dry_run: return diff --git a/tests/test_mdm.py b/tests/test_mdm.py index 550192d..4b54ead 100644 --- a/tests/test_mdm.py +++ b/tests/test_mdm.py @@ -1,5 +1,7 @@ """The MDM contract""" +import pytest + from odmdm_connector import mdm @@ -18,7 +20,7 @@ def test_an_error_carries_the_phones_named_before_it() -> None: def test_every_state_is_a_sentence_and_every_capability_is_named() -> None: """The state's value is what the operator reads""" assert all(state.value and state.value == state.value.strip() for state in mdm.State) - assert set(mdm.CAPABILITIES) == {"setup", "set_challenge", "ask_again"} + assert set(mdm.CAPABILITIES) == {"setup", "set_challenge", "ask_again", "send_policy"} assert mdm.API_VERSION == 1 @@ -26,3 +28,29 @@ def test_a_field_is_shown_unless_marked_advanced() -> None: """The window hides a field marked advanced until asked; the command line takes it as any other""" assert not mdm.Field("team", "Team").advanced assert mdm.Field("key_alias", "Key alias", advanced=True).advanced + + +def test_a_default_may_name_the_deployment() -> None: + """The first label of the Deploy App's host; without a host such a default is none, and any other is itself""" + team = mdm.Field("team", "Team", default="{deployment} DeployApp") + + assert team.default_for("golden-monkey.example.fi") == "golden-monkey DeployApp" + assert team.default_for("") == "" + assert mdm.Field("key_alias", "Key alias", default="rmscep").default_for("") == "rmscep" + assert mdm.Field("plain", "Plain", default="{x} {deployment}").default_for("a.example.fi") == "{x} a" + + +@pytest.mark.parametrize( + ("host", "default"), + [ + ("Golden-Monkey.Example.fi", "golden-monkey DeployApp"), + (" golden-monkey.example.fi\n", "golden-monkey DeployApp"), + ("https://golden-monkey.example.fi", ""), + ("golden-monkey.example.fi/scep", ""), + ("golden monkey.example.fi", ""), + ("localhost", ""), + ], +) +def test_a_deployment_default_takes_only_a_plain_host_in_lower_case(host: str, default: str) -> None: + """The page and the command line give one team for one Deploy App; a host the settings would refuse gives none""" + assert mdm.Field("team", "Team", default="{deployment} DeployApp").default_for(host) == default diff --git a/tests/test_testing.py b/tests/test_testing.py index c62bcc2..4a688f0 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -1,12 +1,13 @@ """The plugin authors' test kit, run against the fake and against Fleet over the stub""" -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence from typing import ClassVar import pytest from odmdm_connector.fleet_plugin import FleetPlugin -from odmdm_connector.mdm import CAPABILITIES, Mdm, MdmError, Phone, State +from odmdm_connector.mdm import CAPABILITIES, Mdm, MdmError, Phone, State, Step +from odmdm_connector.settings import Settings from odmdm_connector.testing import FakeMdm, contract from .test_fleet import Request, Response, _Fleet, _host, _mdm @@ -85,6 +86,15 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: return [""] +class _Forcing(FakeMdm): + """Says it cannot send the policy again, then sets up with force anyway""" + + missing: ClassVar[Mapping[str, str]] = {"send_policy": "Not here"} + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + return super().setup(window, dry_run=dry_run) + + class _Lying(FakeMdm): """Says it lacks asking again, then does it anyway""" @@ -106,6 +116,7 @@ def set_challenge(self, window: object) -> None: (_Careless, contract.asks_again, "lines must be non-empty"), (_Lying, contract.asks_again, "listed as missing but did not raise"), (_Lying, contract.sets_the_challenge, "must raise MdmError with its sentence"), + (_Forcing, contract.sends_the_policy_again, "send_policy is listed as missing but did not raise"), ], ) def test_a_plugin_breaking_the_contract_fails_its_check( From cfb16d7f7d5f502dddcceb5cb74e61a6c597b571 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 089/104] feat(fleet): the team named after the deployment, and a repair that makes no team Sending the policy again refuses a team Fleet lacks before anything is changed. The step names the team, and no sentence names a command. --- src/odmdm_connector/fleet.py | 22 +++++++++---- src/odmdm_connector/fleet_plugin.py | 35 +++++++++++++++----- tests/test_fleet_plugin.py | 50 ++++++++++++++++++++++++++--- 3 files changed, 89 insertions(+), 18 deletions(-) diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index ee79bc4..924bb6e 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -42,6 +42,10 @@ class Unauthorized(FleetError): """Fleet answered 401: it does not accept the token""" +class NoTeam(FleetError): + """Fleet has no team of the name given, and none was to be created""" + + #: The proxy the environment names, and HTTPS with certificates checked: nothing else. Without a #: redirect handler a redirect comes back as an answer and is never followed, so the token goes #: nowhere but the MDM URL; without the error handlers an answer of any status comes back as it is. @@ -93,7 +97,7 @@ def _multipart( #: Said when Fleet answers 401. A token copied from a signed-in account is that sign-in's own, and Fleet ends it -#: after some days or at sign-out; an API-only user's token does not end. +#: with that sign-in, after 5 days by default or at sign-out; an API-only user's token does not end. UNAUTHORIZED = ( "the API token is not accepted. A token copied from a signed-in account ends with that sign-in: " "give a new one, or an API-only user's, which does not end" @@ -198,7 +202,7 @@ def team_id(self, name: str, create: bool = False) -> int: if team.get("name") == name: return int(team["id"]) if not create: - raise FleetError(f"no team named {name}: check the team's name") + raise NoTeam(f"no team named {name}: check the team's name") created = self._call("POST", "/api/latest/fleet/teams", {"name": name}) team = created.get("team", created) LOGGER.info("Created team %s", name) @@ -292,8 +296,8 @@ def ensure_policy(self, team: int, fragment: dict[str, Any], name: str = POLICY_ # A token refused meanwhile is still a token refused, which the operator is asked for again. kind = Unauthorized if isinstance(exc, Unauthorized) else FleetError raise kind( - f"policy {name} was being replaced in team {team} and may now be missing ({exc}). " - "Run apply to put it back" + f"policy {name} was being replaced in team {team} and may now be missing ({exc}): " + "sending the policy again puts it back" ) from exc LOGGER.info("Uploaded policy %s to team %s", name, team) @@ -592,6 +596,7 @@ def apply( force_policy: bool = False, scep_url: str = "", challenge: str = "", + create_team: bool = True, ) -> dict[str, Any]: """State everything the template says, in the order that actually works @@ -603,11 +608,16 @@ def apply( Given scep_url, the certificate authority is created too, so a fresh deployment needs nothing typed into Fleet by hand. Without it the authority must already be there, which is the case for an MDM we cannot create one in. + + Without create_team, a team Fleet lacks is NoTeam before anything is changed. """ - # The authority first: refusing it must leave Fleet as it was, a new team included + # Without create_team the team is looked up first, so a team missing leaves Fleet as it was + team = None if create_team else self.team_id(team_name) + # The authority before a team is made: refusing it must leave Fleet as it was, a new team included if template.certificate and scep_url: self.ensure_authority(template.certificate.authority, scep_url, challenge) - team = self.team_id(team_name, create=True) + if team is None: + team = self.team_id(team_name, create=True) if template.certificate: self.ensure_certificate( team, diff --git a/src/odmdm_connector/fleet_plugin.py b/src/odmdm_connector/fleet_plugin.py index 555514e..a60ffed 100644 --- a/src/odmdm_connector/fleet_plugin.py +++ b/src/odmdm_connector/fleet_plugin.py @@ -11,7 +11,7 @@ from urllib.parse import urlparse from . import template -from .fleet import FleetError, FleetMdm, Unauthorized +from .fleet import FleetError, FleetMdm, NoTeam, Unauthorized from .fleet import Phone as FleetPhone from .mdm import API_VERSION, Field, MdmError, Phone, State, Step from .settings import Settings @@ -69,12 +69,18 @@ class FleetPlugin: "API token", secret=True, help=( - "A global admin's API token: in Fleet, My account, Get API token. That one ends after some days; " - "an API-only user's does not." + "A global admin's API token: in Fleet, My account, Get API token. That one ends with that sign-in, " + "after 5 days by default; an API-only user's does not." ), required=True, ), - Field("team", "Team", default="Deploy App", help="The team phones enrol into and get the certificate in"), + Field( + "team", + "Team", + default="{deployment} DeployApp", + help="The team phones enrol into and get the certificate in", + required=True, + ), Field( "template", "Template", @@ -92,7 +98,7 @@ class FleetPlugin: missing: ClassVar[Mapping[str, str]] = {} def __init__(self, values: Mapping[str, str]) -> None: - given = {item.key: values.get(item.key) or item.default for item in self.fields} + given = {item.key: values.get(item.key) or item.default_for("") for item in self.fields} self._url = given["mdm_url"] self._token = given["token"] self.team = given["team"] @@ -113,6 +119,8 @@ def _fleet(self) -> FleetMdm: ) if not self._token: raise MdmError("The Fleet API token is missing") + if not self.team: + raise MdmError("The Fleet team is missing") self._api = FleetMdm(self._url, self._token) return self._api @@ -129,7 +137,8 @@ def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> """State what the template says, in the order FleetMdm.apply knows works force sends the policy again even if Fleet's copy is unchanged, to reach a phone that just - joined. + joined. It is a repair, so it makes no team: a team Fleet lacks is refused before anything + is changed. """ wanted = self._template(window) lines = [f" {app.package}{' (at enrolment)' if app.preinstall else ' (on demand)'}" for app in wanted.apps] @@ -141,11 +150,21 @@ def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> return try: result = self._fleet().apply( - self.team, wanted, force_policy=force, scep_url=window.scep_url, challenge=window.challenge + self.team, + wanted, + force_policy=force, + scep_url=window.scep_url, + challenge=window.challenge, + create_team=not force, ) + except NoTeam as exc: + raise MdmError( + f"Fleet has no team named {self.team}, so nothing was changed: sending the policy again makes no " + "team. Check the team's name." + ) from exc except FleetError as exc: raise _refused(exc) from exc - yield Step(f"Applied to team {result['team_id']}: {len(result['assigned'])} apps assigned", True) + yield Step(f"Applied to team {self.team} ({result['team_id']}): {len(result['assigned'])} apps assigned", True) def set_challenge(self, window: Settings) -> None: """Give the template's certificate authority the window's challenge, and change nothing else""" diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py index 235bfe7..d3dc866 100644 --- a/tests/test_fleet_plugin.py +++ b/tests/test_fleet_plugin.py @@ -8,7 +8,7 @@ from odmdm_connector.mdm import Mdm, MdmError, State from odmdm_connector.settings import Settings -from .test_fleet import Request, Response, _Fleet, _host, _mdm +from .test_fleet import Request, Response, _Fleet, _host, _mdm, _policy_uploads NO_NAME = "Could not replace certificate variables: host 6f1c does not have an IDP user for variable FLEET_VAR_X" REFUSED = "SCEP enrollment failed: Enrollment failed with SCEP failInfo: badMessageCheck" @@ -155,6 +155,7 @@ def refusing(request: Request) -> Response: ({"mdm_url": ""}, "The Fleet address is missing"), ({"mdm_url": "http://mdm.test"}, "must start with https://"), ({"token": ""}, "The Fleet API token is missing"), + ({"team": ""}, "The Fleet team is missing"), ], ) def test_fleet_is_reached_only_when_configured(fleet: _Fleet, values: dict[str, str], says: str) -> None: @@ -183,10 +184,51 @@ def test_the_template_and_key_alias_are_advanced() -> None: def test_the_token_help_says_which_token_lasts() -> None: - """The token My account gives ends after some days, and the refusal then says so""" + """The token My account gives ends with that sign-in, as the refusal then says""" [token] = [each for each in FleetPlugin.fields if each.key == "token"] assert token.help == ( - "A global admin's API token: in Fleet, My account, Get API token. That one ends after some days; " - "an API-only user's does not." + "A global admin's API token: in Fleet, My account, Get API token. That one ends with that sign-in, " + "after 5 days by default; an API-only user's does not." ) + + +def test_the_team_is_named_after_the_deployment_by_default() -> None: + """golden-monkey.example.fi's team is golden-monkey DeployApp; it must be given, and the connector suggests it""" + [team] = [each for each in FleetPlugin.fields if each.key == "team"] + + assert team.required + assert team.default_for("golden-monkey.example.fi") == "golden-monkey DeployApp" + + +def test_sending_the_policy_again_makes_no_team(fleet: _Fleet) -> None: + """A repair creates nothing: a team Fleet lacks is refused before the authority or anything else is changed""" + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] + + with pytest.raises(MdmError) as raised: + list(_plugin(team="golden-monkey DeployApp").setup(WINDOW, force=True)) + + assert str(raised.value) == ( + "Fleet has no team named golden-monkey DeployApp, so nothing was changed: sending the policy again makes " + "no team. Check the team's name." + ) + assert not raised.value.unauthorized + assert not [call for call in fleet.calls if call[0] != "GET"] + assert fleet.authorities[0]["challenge"] == "old" + + +def test_setup_with_force_sends_the_unchanged_policy_again_and_no_challenge(fleet: _Fleet) -> None: + """apply --force-policy, and Send the policy again on the page: for a phone whose policy Fleet overwrote""" + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] + bare = Settings("https://example.fi/scep", "") + list(_plugin().setup(bare)) + before = _policy_uploads(fleet) + + list(_plugin().setup(bare)) + unforced = _policy_uploads(fleet) + steps = list(_plugin().setup(bare, force=True)) + + assert unforced == before, "unchanged, so not sent" + assert _policy_uploads(fleet) == before + 1 + assert steps[-1].label.startswith("Applied to team rmscep (7): ") + assert fleet.authorities[0]["challenge"] == "old" From 30714e3411cad100fa4ae7f628201e7d9fa2331d Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 090/104] feat: send the policy again through the core, one job at a time --- src/odmdm_connector/app.py | 75 +++++++++++++++++---- tests/test_app.py | 131 ++++++++++++++++++++++++++++++++++++- 2 files changed, 193 insertions(+), 13 deletions(-) diff --git a/src/odmdm_connector/app.py b/src/odmdm_connector/app.py index f454c46..de8d66d 100644 --- a/src/odmdm_connector/app.py +++ b/src/odmdm_connector/app.py @@ -26,7 +26,7 @@ from urllib.parse import urlsplit from . import core, plugins, settings, store -from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step +from .mdm import ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step from .settings import Settings LOGGER = logging.getLogger(__name__) @@ -181,6 +181,8 @@ class Job(Enum): PHONES = "phones" NAME = "name" ASK_AGAIN = "ask again" + #: Setup again with the policy sent even if unchanged + POLICY = "policy" @dataclass(frozen=True) @@ -350,17 +352,21 @@ def _run(job: Job, work: Callable[[], Result], log_path: Path) -> Result: return Result(job, error=f"The MDM plugin failed; the log says more: {log_path}") -def _setup(mdm: Mdm, window: Settings, seen: Callable[[tuple[Step, ...]], None]) -> Result: - """The MDM's setup, each step shown as it is done, with the steps done before it stopped if it did""" +def _setup(mdm: Mdm, window: Settings, seen: Callable[[tuple[Step, ...]], None], force: bool = False) -> Result: + """The MDM's setup, each step shown as it is done, with the steps done before it stopped if it did + + force: the policy is sent again even if unchanged, as a POLICY job. + """ + job = Job.POLICY if force else Job.SETUP steps: list[Step] = [] try: - for step in mdm.setup(window): + for step in mdm.setup(window, force=force): steps.append(step) seen(tuple(steps)) except MdmError as exc: - LOGGER.warning("Setup failed: %s", exc) - return Result(Job.SETUP, error=str(exc), steps=tuple(steps), unauthorized=exc.unauthorized) - return Result(Job.SETUP, steps=tuple(steps)) + LOGGER.warning("%s failed: %s", job.value, exc) + return Result(job, error=str(exc), steps=tuple(steps), unauthorized=exc.unauthorized) + return Result(job, steps=tuple(steps)) def _name(mdm: Mdm, wanted: list[tuple[str, str]]) -> Result: @@ -562,10 +568,18 @@ def _forget(self, host: str, name: str) -> bool: left = [account for account in accounts if not self.keychain.forget(account)] return not left + def _default(self, item: Field) -> str: + """The field's default for the active Deploy App, the deployment's name filled in""" + return item.default_for(self.saved.active) + def form(self, name: str) -> Form: - """The MDM's fields with their values: saved ones if it is the active connection's MDM, else the defaults""" + """The MDM's fields with their values: saved ones if it is the active connection's MDM, else the defaults + + Each field's default is the active Deploy App's. + """ chosen = self._class(name) saved = self.conn.values if self.conn.mdm == name else {} + fields = [replace(item, default=self._default(item)) for item in chosen.fields] return Form( name, chosen.title, @@ -573,7 +587,7 @@ def form(self, name: str) -> Form: FieldValue(item, self._secret(name, item), self._remembered(name, item)) if item.secret else FieldValue(item, saved.get(item.key, item.default)) - for item in chosen.fields + for item in fields ), ) @@ -587,7 +601,9 @@ def _make(self, name: str, chosen: type[Mdm]) -> Mdm: """The MDM, made from the saved values and the secrets, and held""" values = {} for item in chosen.fields: - values[item.key] = self._secret(name, item) if item.secret else self.conn.values.get(item.key, item.default) + values[item.key] = ( + self._secret(name, item) if item.secret else self.conn.values.get(item.key, self._default(item)) + ) if item.secret: self.redact.add(values[item.key]) try: @@ -635,8 +651,10 @@ def connect(self, name: str, values: Mapping[str, str], remember: bool = True) - f"To set {chosen.title} up, open enrolment on the MDM page of Deploy App {self.saved.active}, " "then press Open in the MDM connector there." ) - plain = {item.key: values.get(item.key, item.default) for item in chosen.fields if not item.secret} - saved = {item.key: self.conn.values.get(item.key, item.default) for item in chosen.fields if not item.secret} + plain = {item.key: values.get(item.key, self._default(item)) for item in chosen.fields if not item.secret} + saved = { + item.key: self.conn.values.get(item.key, self._default(item)) for item in chosen.fields if not item.secret + } same = self.conn.mdm == name and plain == saved given = dict(plain) for item in chosen.fields: @@ -675,6 +693,37 @@ def connect(self, name: str, values: Mapping[str, str], remember: bool = True) - def connected(self) -> bool: return self.mdm is not None + def policy_note(self) -> str: + """What sending the policy again does, while the MDM connected can; empty when it cannot""" + if self.mdm is None or SETUP in self.mdm.missing or SEND_POLICY in self.mdm.missing: + return "" + return ( + "For a phone whose browser refuses its certificate: the MDM sends the policy to every phone again. " + "Phones keep their certificates. Not while phones are still installing apps: it stops their installs." + ) + + def send_policy(self) -> str: + """Set the MDM up again with its policy sent even if unchanged, on the worker, as apply --force-policy does + + For a phone whose policy the MDM overwrote. No challenge goes with it, so a window pasted + earlier never takes the place of a newer one, and enrolment need not be open. One at a + time: asked again while it or a setup waits or runs, nothing more is sent, as every send + rewrites the policy and a policy rewritten again and again stops the phones' installs. + """ + if self.mdm is None: + raise AppError("Connect to the MDM first.") + for capability in (SETUP, SEND_POLICY): + if capability in self.mdm.missing: + raise AppError(self.mdm.missing[capability]) + said = f"Sending the policy again for Deploy App {self.saved.active}." + if self._pending[Job.POLICY] or self._pending[Job.SETUP]: + return self._say(said) + mdm = self.mdm + window = Settings(self.window.scep_url if self.window else f"https://{self.saved.active}/scep", "") + self._progress = () + self._submit(Job.POLICY, lambda: _setup(mdm, window, self._show, force=True)) + return self._say(said) + # The Deploy Apps def connections(self, now: datetime.datetime) -> list[DeployApp]: @@ -1039,6 +1088,8 @@ def _take(self, result: Result) -> None: self._say(f"Do the steps by hand to finish setting {title} up for Deploy App {result.host}.") elif result.job is Job.SETUP: self._say(f"{title} is set up for Deploy App {result.host}.") + elif result.job is Job.POLICY: + self._say(f"{title} has sent the policy again to the phones of Deploy App {result.host}.") elif result.job is Job.CHALLENGE: self._say(f"{title} has the new challenge.") elif result.job is Job.NAME: diff --git a/tests/test_app.py b/tests/test_app.py index ab7fb2b..b433301 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -16,7 +16,7 @@ from odmdm_connector import app, plugins, store from odmdm_connector.fleet_plugin import FleetPlugin -from odmdm_connector.mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step +from odmdm_connector.mdm import ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, Phone, State, Step from odmdm_connector.settings import Settings from odmdm_connector.testing import FakeMdm from odmdm_connector.testing.fake import PHONES @@ -1378,3 +1378,132 @@ def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> assert rig.app.progress in ((), (Step("Group found", True, "with [secret]"),)), "the last setup's steps are gone" go.set() rig.settle() + + +class Forced(FakeMdm): + """Records the window and force of every setup""" + + setups: ClassVar[list[tuple[Settings, bool]]] = [] + + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + Forced.setups.append((window, force)) + return super().setup(window, force, dry_run) + + +def test_the_policy_is_sent_again_as_apply_force_policy_with_its_steps(keyed: Rig) -> None: + """A setup with force and no challenge, so a window pasted earlier never replaces a newer one""" + keyed.classes["fake"] = Forced + keyed.connected() + Forced.setups.clear() + + note = keyed.app.policy_note() + said = keyed.app.send_policy() + [result] = keyed.settle() + + assert note == ( + "For a phone whose browser refuses its certificate: the MDM sends the policy to every phone again. " + "Phones keep their certificates. Not while phones are still installing apps: it stops their installs." + ) + assert said == "Sending the policy again for Deploy App unit.example.fi." + assert Forced.setups == [(Settings("https://unit.example.fi/scep", ""), True)] + assert (result.job, result.error) == (app.Job.POLICY, "") + assert result.steps[-1] == Step("Certificate template stated", True, "forced") + assert keyed.app.status == "Fake MDM has sent the policy again to the phones of Deploy App unit.example.fi." + + # After a restart, with enrolment closed and no window pasted: the command line needs none either + keyed.app.close() + keyed.app = keyed.start() + keyed.app.send_policy() + keyed.settle() + assert Forced.setups[-1] == (Settings("https://unit.example.fi/scep", ""), True) + + +def test_the_policy_is_sent_again_one_job_at_a_time(keyed: Rig) -> None: + """Every send rewrites the policy: asked again while one waits or runs, or a setup does, nothing more is sent""" + keyed.classes["fake"] = Forced + keyed.connected() + Forced.setups.clear() + + first = keyed.app.send_policy() + second = keyed.app.send_policy() + keyed.settle() + + assert first == second == "Sending the policy again for Deploy App unit.example.fi." + assert Forced.setups == [(Settings("https://unit.example.fi/scep", ""), True)] + + keyed.app.paste_settings(LINE, NOW) + keyed.app.connect("fake", VALUES) + during_setup = keyed.app.send_policy() + keyed.settle() + + assert during_setup == "Sending the policy again for Deploy App unit.example.fi." + assert [force for _, force in Forced.setups] == [True, False], "the setup only, nothing forced beside it" + + +class PolicyRefused(FakeMdm): + def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> Iterator[Step]: + yield Step("Group found", True) + if force: + raise MdmError("Fleet refused: the policy cannot be uploaded") + + +def test_a_policy_the_mdm_refuses_is_its_reason(rig: Rig) -> None: + rig.classes["fake"] = PolicyRefused + rig.connected() + + rig.app.send_policy() + [result] = rig.settle() + + assert (result.job, result.steps) == (app.Job.POLICY, (Step("Group found", True),)) + assert result.error == rig.app.status == "Fleet refused: the policy cannot be uploaded" + + +@pytest.mark.parametrize( + ("lacking", "says"), [(SEND_POLICY, "The fake MDM cannot send_policy"), (SETUP, "The fake MDM cannot setup")] +) +def test_the_policy_is_not_offered_by_an_mdm_that_cannot_send_it(rig: Rig, lacking: str, says: str) -> None: + with pytest.raises(app.AppError, match="^Connect to the MDM first.$"): + rig.app.send_policy() + assert rig.app.policy_note() == "" + rig.classes["fake"] = FakeMdm.lacking(lacking) + rig.app.paste_settings(LINE, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + assert rig.app.policy_note() == "" + with pytest.raises(app.AppError, match=f"^{says}$"): + rig.app.send_policy() + assert not rig.app.busy() + + +#: The Fleet plugin's fields on the fake MDM: whatever reads them gets the team's default +FleetFields = type("FleetFields", (FakeMdm,), {"fields": FleetPlugin.fields}) +GOLDEN = LINE.replace("unit.example.fi", "golden-monkey.example.fi") + + +def test_the_team_suggested_is_named_after_the_deployment(rig: Rig) -> None: + rig.classes["fake"] = FleetFields + rig.app.paste_settings(GOLDEN, NOW) + + form = {each.field.key: each for each in rig.app.form("fake").fields} + rig.app.connect("fake", {"mdm_url": "https://mdm.example.fi", "token": "t0ken"}) # pragma: allowlist secret + rig.settle() + + assert (form["team"].value, form["team"].field.default) == ("golden-monkey DeployApp", "golden-monkey DeployApp") + assert form["key_alias"].value == "rmscep" + assert rig.app.saved.connections["golden-monkey.example.fi"].values["team"] == "golden-monkey DeployApp" + assert isinstance(rig.app.mdm, FakeMdm) and rig.app.mdm.values["team"] == "golden-monkey DeployApp" + + +def test_a_team_saved_or_typed_stays_as_it_is(rig: Rig) -> None: + rig.classes["fake"] = FleetFields + rig.app.paste_settings(GOLDEN, NOW) + rig.app.connect("fake", {"mdm_url": "https://mdm.example.fi", "token": "t0ken", "team": "Deploy App"}) + rig.settle() + + [team] = [each for each in rig.app.form("fake").fields if each.field.key == "team"] + + assert team.value == "Deploy App" + assert rig.app.saved.connections["golden-monkey.example.fi"].values["team"] == "Deploy App" + with pytest.raises(app.AppError, match="^Fill in Team.$"): + rig.app.connect("fake", {"mdm_url": "https://mdm.example.fi", "token": "t0ken", "team": " "}) From 17f83491eccec4732d31658a2797f138263f37ee Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 091/104] feat: Send the policy again in the page's Settings The repair the command line has as apply --force-policy, with its steps shown as a setup's. --- src/odmdm_connector/static/app.js | 60 ++++++++++--- src/odmdm_connector/web.py | 13 ++- tests/test_web.py | 136 +++++++++++++++++++++++++++++- 3 files changed, 195 insertions(+), 14 deletions(-) diff --git a/src/odmdm_connector/static/app.js b/src/odmdm_connector/static/app.js index 6d34c90..024a1e1 100644 --- a/src/odmdm_connector/static/app.js +++ b/src/odmdm_connector/static/app.js @@ -307,7 +307,7 @@ function begin() { // Where a Deploy App's work goes on: its phones, else what its MDM still needs, and why. The last // answer's sentence stays, for a card to say. function home() { - flow.renew = flow.change = flow.again = false; + flow.renew = flow.change = flow.again = flow.policy = false; flow.back = null; if (!S.active) show(S.connections.length ? "choose" : "add"); else if (S.connected) show("app"); @@ -367,9 +367,10 @@ function chooseMdm(name, why = "", only = false) { } // After Connect: the setup's steps while it runs or leaves something to say, else the phones. With -// the token typed again, a setup that ends with nothing to say goes straight on to the phones. +// the token typed again, a setup that ends with nothing to say goes straight on to the phones. After +// Send the policy again (flow.policy), the same card shows that job's steps and stays to say how it ended. function checklist() { - const busy = S.busy.includes("setup"); + const busy = S.busy.includes(flow.policy ? "policy" : "setup"); const said = S.setup_error || S.challenge || S.steps.some((step) => !step.done) || (S.steps.length && !flow.again); if (!busy && (!S.connected || !said)) home(); else if (screen === "connecting") draw(false); @@ -560,6 +561,7 @@ const CARDS = { () => { flow.values = {}; flow.again = flow.only; + flow.policy = false; checklist(); }, // A kept secret left empty after the settings changed is asked for again on its own card @@ -621,15 +623,31 @@ const CARDS = { connecting() { const title = flow.form.title; - const busy = S.busy.includes("setup"); + const policy = flow.policy; + const busy = S.busy.includes(policy ? "policy" : "setup"); const done = S.steps.filter((step) => step.done); const todo = S.steps.filter((step) => !step.done); const item = (cls, step) => el("li", { class: cls }, step.label, step.message ? el("span", {}, step.message) : null); // Steps left to the operator are what the card is about once the setup has run - const hand = !busy && !S.setup_error && (todo.length || S.challenge); - const heading = busy ? `Connecting ${title}` : S.setup_error ? `${title} is not set up` : hand ? "Do these by hand" : `${title} is connected`; + const given = S.challenge && !policy; + const hand = !busy && !S.setup_error && (todo.length || given); + const heading = policy + ? busy + ? "Sending the policy again" + : S.setup_error + ? "The policy was not sent" + : hand + ? "Do these by hand" + : "The policy is sent again" + : busy + ? `Connecting ${title}` + : S.setup_error + ? `${title} is not set up` + : hand + ? "Do these by hand" + : `${title} is connected`; return { - step: flow.again ? null : 2, + step: flow.again || policy ? null : 2, host: true, parts: [ h1(heading), @@ -641,7 +659,7 @@ const CARDS = { "ul", { class: "run" }, todo.map((step) => item("hand", step)), - S.challenge ? el("li", { class: "hand" }, S.challenge_note, challenge()) : null, + given ? el("li", { class: "hand" }, S.challenge_note, challenge()) : null, ) : null, el( @@ -651,7 +669,7 @@ const CARDS = { busy ? el("li", { class: "now" }, "…") : null, ), S.setup_error ? el("p", { class: "error" }, S.setup_error) : null, - S.setup_error + S.setup_error && !policy ? main("Change the settings", () => { flow.change = false; chooseMdm(S.mdm); @@ -1111,6 +1129,27 @@ function giveCallsigns(ids) { function settings() { act("/api/form", { mdm: S.mdm }, (answer) => { + // Its steps on the card a setup shows them on; a refusal before it starts is said here. The button + // is disabled as it is pressed, so a second press sends nothing + const resend = (event) => { + const pressed = event.currentTarget; + pressed.disabled = true; + act( + "/api/policy", + {}, + () => { + dialog.close(); + flow.form = answer; + flow.again = false; + flow.policy = true; + checklist(); + }, + (text) => { + pressed.disabled = false; + tell(text); + }, + ); + }; const said = (each) => each.secret ? each.remembered @@ -1126,7 +1165,7 @@ function settings() { }; submit = null; const close = main("Close", () => dialog.close(), false, "plain"); - open( + const tell = open( "Settings", [ el("h3", { class: "sect" }, `${answer.title} for `, named(S.active)), @@ -1136,6 +1175,7 @@ function settings() { answer.fields.filter((each) => said(each)).map((each) => [el("dt", {}, each.label), el("dd", {}, said(each))]), ), second(`Change the ${answer.title} settings`, change), + S.policy ? [el("h3", { class: "sect" }, "Policy"), el("p", { class: "muted" }, S.policy), second("Send the policy again", resend, S.busy.includes("policy") || S.busy.includes("setup"))] : null, el("h3", { class: "sect" }, "Log"), el("div", { class: "copyrow" }, copyable(S.log, "Log"), tool("Copy", () => copy(S.log))), el("p", { class: "muted" }, `odmdm-connector ${S.version}`), diff --git a/src/odmdm_connector/web.py b/src/odmdm_connector/web.py index 4981be8..6350bcf 100644 --- a/src/odmdm_connector/web.py +++ b/src/odmdm_connector/web.py @@ -105,7 +105,7 @@ def __init__( self.lock = threading.Lock() self.hosts = {f"127.0.0.1:{self.port}", f"localhost:{self.port}"} self.origins = {f"http://{host}" for host in self.hosts} - #: The steps of the last setup, as its result brought them, and its error, empty when it passed + #: The steps of the last setup or sending of the policy, as its result brought them, and its error self.steps: list[dict[str, Any]] = [] self.setup_error = "" #: When the phones were last asked for, by clock; None before the first time @@ -131,7 +131,7 @@ def handle_error(self, request: Any, client_address: Any) -> None: def _take(self, results: list[Result], now: datetime.datetime) -> None: for result in results: - if result.job is Job.SETUP: + if result.job in (Job.SETUP, Job.POLICY): self.steps, self.setup_error = [asdict(step) for step in result.steps], result.error elif result.job is Job.PHONES and result.phones is not None: self.updated = (result.host, now.strftime("%H:%M")) @@ -174,6 +174,8 @@ def state(self) -> Body: {"name": each.name, "package": each.package, "version": each.version, "built_in": each.built_in} for each in app.mdms() ], + # What sending the policy again does, empty when the MDM cannot + "policy": app.policy_note(), # While a setup runs, the steps it has done so far; after it, the steps its result brought "steps": self.steps or [asdict(step) for step in app.progress], "setup_error": self.setup_error, @@ -254,6 +256,12 @@ def refresh(self, body: Body) -> Body: self._list() return {} + def policy(self, body: Body) -> Body: + """Send the policy again, its steps shown as a setup's""" + said = self.app.send_policy() + self.steps, self.setup_error = [], "" + return {"said": said} + def preview(self, body: Body) -> Body: """What naming the phones chosen would do, and the first number a numbered batch starts from""" app = self.app @@ -304,6 +312,7 @@ def detail(self, body: Body) -> Body: "/api/approve": Page.approve, "/api/connect": Page.connect, "/api/refresh": Page.refresh, + "/api/policy": Page.policy, "/api/preview": Page.preview, "/api/name": Page.name, "/api/again": Page.again, diff --git a/tests/test_web.py b/tests/test_web.py index 343c70d..d181076 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -15,11 +15,23 @@ import pytest from odmdm_connector import app, browser, console, store, web -from odmdm_connector.mdm import ASK_AGAIN, State, Step +from odmdm_connector.mdm import ASK_AGAIN, SEND_POLICY, State, Step from odmdm_connector.settings import Settings from odmdm_connector.testing import FakeMdm -from .test_app import CHALLENGE, KEPT, LINE, NOW, TOKEN_VALUES, VALUES, Addressed, HalfSetUp, Rig +from .test_app import ( + CHALLENGE, + GOLDEN, + KEPT, + LINE, + NOW, + TOKEN_VALUES, + VALUES, + Addressed, + FleetFields, + HalfSetUp, + Rig, +) from .test_store import MemoryBackend Answer = tuple[int, http.client.HTTPMessage, bytes] @@ -918,3 +930,123 @@ def test_the_phones_say_which_have_their_certificates_and_which_asking_again_can rows = [(row["id"], row["ready"], row["askable"]) for row in served.state()["rows"]] assert rows == [("a1", False, askable), ("a2", False, False), ("a3", True, False)] + + +def test_the_policy_is_sent_again_from_the_page_its_steps_shown_as_a_setups(served: Served) -> None: + """Offered while the MDM connected can send it; its steps and its refusal take the setup's place""" + assert served.state()["policy"] == "" + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + offered = served.state()["policy"] + served.rig.classes["fake"] = HalfSetUp + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + assert served.state()["setup_error"] == "The fake MDM refused the template" + served.rig.classes["fake"] = FakeMdm + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + + said = served.post("/api/policy") + state = served.state() + + assert offered.startswith("For a phone whose browser refuses its certificate:") + assert said == {"said": "Sending the policy again for Deploy App unit.example.fi."} + assert [(step["label"], step["message"]) for step in state["steps"]] == [ + ("Group Deploy App enrols at https://unit.example.fi/scep", ""), + ("Certificate template stated", "forced"), + ] + assert (state["setup_error"], state["status"], "policy" in state["busy"]) == ( + "", + "Fake MDM has sent the policy again to the phones of Deploy App unit.example.fi.", + False, + ) + served.rig.classes["fake"] = HalfSetUp + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + served.state() + served.post("/api/policy") + refused = served.state() + assert ([step["label"] for step in refused["steps"]], refused["setup_error"]) == ( + ["Group found"], + "The fake MDM refused the template", + ) + + +def test_the_policy_is_refused_for_an_mdm_that_cannot_send_it(served: Served) -> None: + served.rig.classes["fake"] = FakeMdm.lacking(SEND_POLICY) + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + + assert served.state()["policy"] == "" + assert served.post("/api/policy", status=400) == {"error": "The fake MDM cannot send_policy"} + + +class Terminal: + """A terminal's stdin or stdout, or a pipe's, as isatty says""" + + def __init__(self, tty: bool) -> None: + self.tty = tty + self.written: list[str] = [] + + def isatty(self) -> bool: + return self.tty + + def write(self, text: str) -> int: + self.written.append(text) + return len(text) + + def flush(self) -> None: + pass + + +@pytest.mark.parametrize( + ("command", "stdin", "stdout", "waits"), + [ + ([], True, True, True), + ([], False, True, False), + ([], True, False, False), + (["web"], True, True, False), + (["web", "--no-browser"], True, True, False), + ], +) +def test_a_second_start_by_a_double_click_waits_for_enter_on_a_terminal( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + command: list[str], + stdin: bool, + stdout: bool, + waits: bool, +) -> None: + """Its window on Windows would close before the sentence is read; with a command, a script must never hang""" + _web(WebRig(tmp_path / "config"), monkeypatch) + asked: list[str] = [] + + def enter(prompt: str = "") -> str: + asked.append(prompt) + raise EOFError + + monkeypatch.setattr("builtins.input", enter) + monkeypatch.setattr(sys, "stdin", Terminal(stdin)) + monkeypatch.setattr(sys, "stdout", Terminal(stdout)) + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + taken.listen() + monkeypatch.setattr(web, "PORT", taken.getsockname()[1]) + + code = console.main(command) + + assert code == 1 + assert "The connector may be running already: use its page." in capsys.readouterr().err + assert asked == ([console.PRESS_ENTER] if waits else []) + + +def test_the_team_card_suggests_the_deployments_team(served: Served) -> None: + served.rig.classes["fake"] = FleetFields + served.post("/api/add", {"line": GOLDEN}) + + [team] = [each for each in served.post("/api/form", {"mdm": "fake"})["fields"] if each["key"] == "team"] + + assert (team["value"], team["default"], team["required"]) == ( + "golden-monkey DeployApp", + "golden-monkey DeployApp", + True, + ) From dc1e13443e074203cbb2bf1965929d1166380761 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 092/104] feat: the command line's team default follows the deployment, and a second start waits for Enter Only a start with no command on a terminal waits, so that a double-clicked window can be read. --- src/odmdm_connector/console.py | 44 +++++++++++++++-------- tests/test_console.py | 66 +++++++++++++++++++++++++++++++--- 2 files changed, 92 insertions(+), 18 deletions(-) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 75ee111..cc7b577 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -22,7 +22,7 @@ from . import browser, core, plugins, settings, store, web from .app import App -from .mdm import ASK_AGAIN, SET_CHALLENGE, SETUP, Field, Mdm, MdmError +from .mdm import ASK_AGAIN, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError from .settings import Settings #: Said when ODMDM_LOG_LEVEL is not a number @@ -32,6 +32,8 @@ OPEN = "Open this address in your browser:" #: Said when Ctrl+C stops the page while a job is under way STOPPED_BUSY = "Stopped while the MDM was still being worked with: refresh the phones when the connector runs again." +#: Asked after the page's port was found taken on a start without a command, so its window does not close unread +PRESS_ENTER = "Press Enter to close." class _Usage(Exception): @@ -50,6 +52,7 @@ def main(argv: Sequence[str] | None = None) -> int: if not hasattr(args, "run"): # Started with no command, as a downloaded file is by a double-click: the page, with web's defaults args = parser.parse_args([*given, "web"]) + args.alone = True try: level = int(os.environ.get("ODMDM_LOG_LEVEL", "20")) except ValueError: @@ -98,8 +101,8 @@ def _chosen(name: str) -> type[Mdm]: raise _Failed(str(exc)) from exc -def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str]) -> dict[str, str]: - """The fields' values: from --set, else ODMDM_, else the default +def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str], host: str) -> dict[str, str]: + """The fields' values: from --set, else ODMDM_, else the default for the deployment on host A secret only ever from the file ODMDM__FILE names, so it stays out of shell history and process environments. No value is ever in a message. @@ -121,7 +124,7 @@ def _values(name: str, fields: tuple[Field, ...], given: Mapping[str, str]) -> d f"The {item.label} holds a line break or another character that cannot be part of it: copy it again." ) else: - values[item.key] = given[item.key] if item.key in given else os.environ.get(env, item.default) + values[item.key] = given[item.key] if item.key in given else os.environ.get(env, item.default_for(host)) return values @@ -150,20 +153,23 @@ def _missing(fields: tuple[Field, ...], values: Mapping[str, str]) -> str: return "" -def _mdm(args: argparse.Namespace, capability: str = "", complete: bool = True) -> Mdm: - """The chosen MDM, configured; or the MDM's sentence for lacking the capability +def _mdm(args: argparse.Namespace, *capabilities: str, complete: bool = True) -> Mdm: + """The chosen MDM, configured; or the MDM's sentence for lacking one of the capabilities - The command's own options such as --team are each the same as --set team=... + The command's own options such as --team are each the same as --set team=... A default that + names the deployment takes it from --domain, else ODMDM_DOMAIN. complete: every required setting must be given, which a dry run does not need. """ given = {key: setting for key, _, setting in (value.partition("=") for value in args.given)} chosen = _chosen(args.chosen) - if capability in chosen.missing: - raise _Failed(chosen.missing[capability]) + for capability in capabilities: + if capability in chosen.missing: + raise _Failed(chosen.missing[capability]) for key in ("mdm_url", "team", "template"): if getattr(args, key, None) is not None: given[key] = getattr(args, key) - values = _values(args.chosen, chosen.fields, given) + host = getattr(args, "domain", None) or os.environ.get("ODMDM_DOMAIN", "") + values = _values(args.chosen, chosen.fields, given, host) missing = _missing(chosen.fields, values) if complete else "" if missing: raise _Failed(missing) @@ -218,7 +224,8 @@ def apply(args: argparse.Namespace) -> int: window = Settings(f"https://{the_domain}/scep", "") else: window = _window(os.environ.get("ODMDM_CHALLENGE", ""), the_domain) - mdm = _mdm(args, SETUP, complete=not args.dry_run) + capabilities = (SETUP, SEND_POLICY) if args.force_policy else (SETUP,) + mdm = _mdm(args, *capabilities, complete=not args.dry_run) try: for step in mdm.setup(window, force=args.force_policy, dry_run=args.dry_run): print(step.label if step.done else f"{step.label} (not done)") @@ -379,9 +386,17 @@ def page(args: argparse.Namespace) -> int: if args.port == web.PORT else "Give another with --port." ) - raise _Failed( - f"The page cannot listen on port {args.port} of this computer: {exc.strerror}. {advice}" - ) from exc + print( + f"The page cannot listen on port {args.port} of this computer: {exc.strerror}. {advice}", + file=sys.stderr, + ) + # Started without a command, as by a double-click, the window would close before it is read + if args.alone and sys.stdin.isatty() and sys.stdout.isatty(): + try: + input(PRESS_ENTER) + except (EOFError, KeyboardInterrupt): + pass + return 1 asked = args.browser and browser.can_open() print(f"{OPENING if asked else OPEN} {server.address}") print("Press Ctrl+C to stop it.", flush=True) @@ -492,6 +507,7 @@ def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) sub.add_argument("ids", nargs="*", metavar="ID") command("mdms", mdms) sub = command("web", page) + sub.set_defaults(alone=False) sub.add_argument( "--port", type=_between(1, 65535), default=web.PORT, help="The port on 127.0.0.1 (default: %(default)s)" ) diff --git a/tests/test_console.py b/tests/test_console.py index 8d9ef01..b14a538 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -130,7 +130,7 @@ def test_apply_states_the_template(fleet: _Fleet, tmp_path: Path, monkeypatch: p result = run(["apply"]) assert result.exit_code == 0, result.output - assert "Applied to team 7" in result.output + assert "Applied to team rmscep (7): 1 apps assigned" in result.output assert fleet.authorities[0]["challenge"] == "new-window" assert fleet.authorities[0]["url"] == "https://example.fi/scep" @@ -621,10 +621,28 @@ def refusing(request: Request) -> Response: assert result.exit_code == 1 assert result.output.splitlines()[0] == "Phone 31 is OTTER4" assert "may now be missing" in result.stderr - assert "Run apply to put it back" in result.stderr + assert "sending the policy again puts it back" in result.stderr + assert "apply" not in result.stderr, "Fleet's sentence names no command" assert not fleet.profiles +def test_apply_force_policy_makes_no_team( + fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: Run +) -> None: + """Sending the policy again is a repair: a team Fleet lacks is refused before anything is changed""" + _template(tmp_path, monkeypatch) + monkeypatch.setenv("ODMDM_CHALLENGE", "new-window") + + result = run(["apply", "--force-policy", "--team", "Typo"]) + + assert result.exit_code == 1 + assert result.stderr == ( + "Fleet has no team named Typo, so nothing was changed: sending the policy again makes no team. " + "Check the team's name.\n" + ) + assert not _changes(fleet) + + @pytest.mark.parametrize("command", [["phones"], ["name", "31=OTTER4"], ["resend"]]) def test_an_unknown_team_is_named_not_created(fleet: _Fleet, command: list[str], run: Run) -> None: """A typo must not leave an empty team behind for the next phone to enrol into""" @@ -910,7 +928,7 @@ def test_a_token_file_is_read_in_the_encodings_editors_write( token.write_bytes(written) monkeypatch.setenv("ODMDM_TOKEN_FILE", str(token)) - assert console._values("fleet", FleetPlugin.fields, {})["token"] == "TOPSECRET" + assert console._values("fleet", FleetPlugin.fields, {}, "")["token"] == "TOPSECRET" @pytest.mark.parametrize("unreadable", ["not text", "not readable"]) @@ -937,7 +955,12 @@ def refuse(self: Path) -> bytes: @pytest.mark.parametrize( ("command", "capability"), - [(["challenge"], "set_challenge"), (["apply"], "setup"), (["resend"], "ask_again")], + [ + (["challenge"], "set_challenge"), + (["apply"], "setup"), + (["resend"], "ask_again"), + (["apply", "--force-policy"], "send_policy"), + ], ) def test_a_capability_the_mdm_lacks_is_its_sentence( fleet: _Fleet, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, command: list[str], capability: str, run: Run @@ -1110,3 +1133,38 @@ def test_help_version_and_a_wrong_command_start_no_page( assert result.exit_code == (2 if "nope" in arguments else 0) if "nope" in arguments: assert "invalid choice: 'nope'" in result.stderr + + +def test_the_team_is_named_after_the_deployment_unless_given(monkeypatch: pytest.MonkeyPatch) -> None: + """From --domain, else ODMDM_DOMAIN; a team given with --team, --set or ODMDM_TEAM wins""" + monkeypatch.delenv("ODMDM_TEAM", raising=False) + host = "golden-monkey.example.fi" + + assert console._values("fleet", FleetPlugin.fields, {}, host)["team"] == "golden-monkey DeployApp" + assert console._values("fleet", FleetPlugin.fields, {"team": "Deploy App"}, host)["team"] == "Deploy App" + monkeypatch.setenv("ODMDM_TEAM", "rmscep") + assert console._values("fleet", FleetPlugin.fields, {}, host)["team"] == "rmscep" + + +def test_the_team_default_is_the_pages_for_any_spelling_of_the_domain(monkeypatch: pytest.MonkeyPatch) -> None: + """A domain in mixed case gives the page's lower-case team, and an address with its scheme gives none""" + monkeypatch.delenv("ODMDM_TEAM", raising=False) + + assert ( + console._values("fleet", FleetPlugin.fields, {}, "Golden-Monkey.Example.fi")["team"] + == "golden-monkey DeployApp" + ) + assert console._values("fleet", FleetPlugin.fields, {}, "https://golden-monkey.example.fi")["team"] == "" + + +def test_the_default_team_reaches_fleet(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + monkeypatch.delenv("ODMDM_TEAM") + fleet.hosts = [_host(31)] + + named = run(["phones"], env={"ODMDM_DOMAIN": "golden-monkey.example.fi"}) + monkeypatch.delenv("ODMDM_DOMAIN") + unnamed = run(["phones"]) + + assert ("teams" in str(fleet.calls), named.exit_code) == (True, 1) + assert "golden-monkey DeployApp" in named.stderr, "the team asked for, which the stub does not hold" + assert (unnamed.exit_code, unnamed.stderr) == (1, "Team is missing: give --set team=... or set ODMDM_TEAM\n") From 4b1eb0ef6f04dab6ee6c655f9d9c718efb3472cd Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 093/104] docs(demo): the demo plugin's group named after the deployment --- .../src/odmdm_connector_demo/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py index c7f39d9..a2f3a2a 100644 --- a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py +++ b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py @@ -23,7 +23,8 @@ class DemoMdm: API_VERSION: ClassVar[int] = 1 title: ClassVar[str] = "Demo MDM" fields: ClassVar[tuple[Field, ...]] = ( - Field("group", "Group", default="Deploy App", help="The group phones enrol into"), + # Named after the deployment: the connector fills {deployment} in, golden-monkey for golden-monkey.example.fi + Field("group", "Group", default="{deployment} DeployApp", help="The group phones enrol into"), ) missing: ClassVar[Mapping[str, str]] = { SET_CHALLENGE: ( @@ -33,7 +34,7 @@ class DemoMdm: def __init__(self, values: Mapping[str, str], refuse_after: int | None = None) -> None: """refuse_after: for tests, the pretend MDM refuses to name more phones than that""" - self.group = values.get("group") or "Deploy App" + self.group = values.get("group", "") self.refuse_after = refuse_after self.found = [ Phone("d1", "", "Pretend Phone 7", "2026-11-01T09:00:00+00:00", State.NEEDS_NAME), From 842669fa43e79c005b75a3fb896f3f3458fe8a86 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:32 +0200 Subject: [PATCH 094/104] docs: sending the policy again, the team's default, and the five things an MDM must do --- README.rst | 44 +++++++++++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/README.rst b/README.rst index 5bc67d1..b568131 100644 --- a/README.rst +++ b/README.rst @@ -52,7 +52,8 @@ App, the MDM, Connect. Have at hand Deploy App's MDM page, open as an admin, you an API token for it. Add the Deploy App: on its MDM page press **Open in the MDM connector**, or copy its settings line and paste it into the page, and confirm it. Choose the MDM when more than one is installed, then fill in what it asks, one field to a card: for Fleet its address, an API token -and the team, with the rarely changed ones under **More settings**. **Connect** sets the MDM up and +and the team, which it suggests naming after the deployment (``golden-monkey DeployApp`` for +golden-monkey.example.fi), with the rarely changed ones under **More settings**. **Connect** sets the MDM up and ticks off its steps; it says what is left to do by hand, if anything, or why it failed, and **Show the phones** goes on. @@ -63,7 +64,9 @@ callsign, model, when it joined and where its certificate is. Click a row to sel double-click it, or select one and press **Details**, to see that phone alone. The line at the bottom says what was done last and, at its right end, when the phones were last listed: every minute while the page is open, or at once with **Refresh**. **Settings** shows the MDM's -settings, whether its token is kept on this computer, and where the log is. The Deploy App's name +settings, whether its token is kept on this computer, and where the log is, and offers **Send the +policy again** for a phone whose browser refuses its certificate (see `The order that works`_): it +ticks off its steps as **Connect** does, and the phones keep their certificates and apps. The Deploy App's name at the top right lists the Deploy Apps added, opens another, adds one or removes the one open. Each Deploy App needs a Fleet of its own: the shipped template names one certificate authority for every Deploy App, and the connector refuses to point an authority that serves one @@ -130,7 +133,9 @@ A file to download For an operator who has no Python, the connector is also one self-contained file per system, which Deploy App's MDM page offers for download when a deployment serves them: Python, the connector, Fleet and keyring are inside, so the token can be kept in the keychain. Started without a command, -as by a double-click, it opens the page; every command works as above. Each system has its own +as by a double-click, it opens the page; every command works as above. Started so again while the +page runs, it says the connector may be running already and, in a terminal window, waits for Enter +before the window closes. Each system has its own file: ``odmdm-connector--windows-x64.exe`` as it is, and for macOS and Linux one executable named ``odmdm-connector`` in a ``.zip`` or ``.tar.gz``, which keeps it executable through a browser's download. Beside them, ``connector.json`` says the version, the MDMs built in, and each @@ -219,8 +224,8 @@ them, and each gets its certificate once it has a name. odmdm-connector challenge -3. Enrol phones into the ``Deploy App`` team, as many as you like, in any order. Name them once - every phone in the team has its apps: naming can send the policy to all of them again. +3. Enrol phones into the team, `` DeployApp`` by default, as many as you like, in + any order. Name them once every phone in the team has its apps: naming can send the policy to all of them again. 4. Name them, all at once or a few at a time:: @@ -285,7 +290,10 @@ from the file its ``_FILE`` variable names: enrolled phone. The tool reads it and never prints, logs or writes it. ``ODMDM_TEAM`` - The team phones enrol into and get the certificate in. Default ``Deploy App``. + The team phones enrol into and get the certificate in. Default `` DeployApp``, the + deployment being the first label of ``--domain`` or ``ODMDM_DOMAIN``: ``golden-monkey DeployApp`` + for golden-monkey.example.fi. Without either, give the team. A deployment set up with the + earlier default keeps its team only when it is given: ``--team "Deploy App"``. ``ODMDM_TEMPLATE`` The document saying what to install, see below. Default: the one shipped with the connector. @@ -391,8 +399,9 @@ it wrong. the policy as verified on that phone and never sends it again, so the phone has its certificate but Chrome may not use it, and Deploy App says "Certificate Authentication Failed". ``name`` and ``resend`` send the policy again, to every phone in the team, when a phone enrolled after it - was last sent. By hand it is ``apply --force-policy``, or deleting the policy in Fleet and - uploading it again. + was last sent. By hand it is **Send the policy again** in the page's **Settings**, + ``apply --force-policy``, or deleting the policy in Fleet and uploading it again. Sending it + again is a repair and makes no team: a team Fleet lacks is refused before anything is changed. 3. **A policy rewritten while apps are installing stops them installing.** Leave the phones alone until the apps have arrived. @@ -428,9 +437,15 @@ What Fleet does that you would not guess Write a plugin -------------- -An MDM fits if it can do three things: take a static SCEP challenge for its certificate -authority, put a per-device value that its API can set into the certificate subject (the -callsign, as the common name), and ask a device for its certificate again. +An MDM fits if it can do five things: + +1. Keep one Deploy App's phones in a group of its own, with its own enrolment. +2. Send each phone's certificate request to Deploy App's SCEP URL with one static challenge, the + same for every phone. +3. Put a value that its API can set for each phone into the certificate subject: the callsign, as + the common name. +4. Take a new challenge for each enrolment window, by API or by hand. +5. Ask one phone for its certificate again and leave the others alone. A plugin is one class that satisfies ``Mdm`` in ``src/odmdm_connector/mdm.py``, which is standard library only: @@ -438,9 +453,12 @@ library only: - ``API_VERSION = 1``, a ``title``, the ``fields`` it needs (each a ``Field``; mark a token ``secret``, one that must be given ``required``, and one rarely changed ``advanced``, which the window shows only when asked) and ``missing``: for each of ``setup``, - ``set_challenge`` and ``ask_again`` it cannot do, the sentence the operator reads instead. + ``set_challenge``, ``ask_again`` and ``send_policy`` it cannot do, the sentence the operator reads + instead. A default may hold ``{deployment}``, which the connector fills in with the deployment's + name, the first label of the Deploy App's host: ``{deployment} DeployApp`` is Fleet's team. - ``__init__(values)`` takes the fields' values by key. -- ``setup(window, force, dry_run)`` yields ``Step`` objects; ``set_challenge(window)``; ``phones()`` +- ``setup(window, force, dry_run)`` yields ``Step`` objects, ``force`` sending the policy again + even if unchanged, unless ``send_policy`` is missing; ``set_challenge(window)``; ``phones()`` answers ``Phone`` objects, oldest first, each with a ``State``; ``name(names)`` and ``ask_again(ids)`` answer the lines to show. - It raises only ``MdmError``. One that stops half-way through ``name`` says in ``named`` which From 490680d1d664df96c61f0381e9d8a8a28a2c1438 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Sun, 22 Nov 2026 18:06:34 +0200 Subject: [PATCH 095/104] chore: bump version to 1.4.0+261122 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/odmdm_connector/__init__.py | 2 +- tests/test_odmdm_connector.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index ecb2860..3ceaea3 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.3.0+261122" +current_version = "1.4.0+261122" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index 5b7956b..a4d4ed5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "1.3.0+261122" +version = "1.4.0+261122" description = "Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index 17b744c..2a8190a 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ """Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" -__version__ = "1.3.0+261122" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.4.0+261122" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index 0e6e7ae..e84d3e1 100644 --- a/tests/test_odmdm_connector.py +++ b/tests/test_odmdm_connector.py @@ -5,4 +5,4 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.3.0+261122" + assert __version__ == "1.4.0+261122" diff --git a/uv.lock b/uv.lock index 56417ab..5fb7628 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "1.3.0+261122" +version = "1.4.0+261122" source = { editable = "." } dependencies = [ { name = "keyring" }, From cf75f6438b8c42c867449222a348ad0249ef1528 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 00:15:19 +0200 Subject: [PATCH 096/104] feat(fleet): an authority per Deploy App, found by the address it serves A new one is named ODMDM_ and the first part of the Deploy App's host name. One made as RMSCEP, or by hand, is found by its address and kept. A challenge goes only to the authority the team's certificate template is bound to, and a team bound to another address is refused before anything is changed. --- src/odmdm_connector/fleet.py | 193 ++++++++++++++++++++-------- src/odmdm_connector/fleet_plugin.py | 12 +- tests/test_fleet.py | 190 +++++++++++++++++++++++++-- tests/test_fleet_plugin.py | 42 ++++++ 4 files changed, 369 insertions(+), 68 deletions(-) diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index 924bb6e..f92be4e 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -9,6 +9,7 @@ import http.client import json import logging +import re import secrets import ssl import time @@ -114,6 +115,22 @@ def _multipart( #: name, so a new name would sit next to the old profile on every team instead of replacing it. POLICY_NAME = "rmscep-policy" +#: What an authority made here is called: this and the Deploy App's own name, so that one Fleet +#: can serve several Deploy Apps +AUTHORITY_PREFIX = "ODMDM_" +#: The one name the shipped template gave every Deploy App's authority before each had its own. +#: An authority is found by the address it serves, so one of this name is still its Deploy App's. +LEGACY_AUTHORITY = "RMSCEP" + + +def authority_name(scep_url: str) -> str: + """What a Deploy App's authority is called when it is made here: ODMDM_ and the host's first label + + In capitals, with an underscore for anything else: Fleet takes letters, digits and underscores only. + """ + label = (urlparse(scep_url).hostname or "").split(".")[0] + return AUTHORITY_PREFIX + re.sub(r"[^A-Z0-9]", "_", label.upper()) + @dataclasses.dataclass(frozen=True) class Phone: @@ -424,54 +441,109 @@ def _link_app_in_team(self, team: int, title: str) -> str: return str(package) return "" - def ensure_authority(self, name: str, scep_url: str, challenge: str) -> int: - """The SCEP CA this deployment is, created if the MDM does not have it yet + def _authorities(self) -> list[dict[str, Any]]: + """Every certificate authority Fleet has: its id, name and type, not what it serves""" + listed: list[dict[str, Any]] = self._call("GET", "/api/latest/fleet/certificate_authorities").get( + "certificate_authorities", [] + ) + return listed + + def _authority(self, authority_id: int) -> dict[str, Any]: + """One authority in full. The listing does not carry the url, only this does.""" + return self._call("GET", f"/api/latest/fleet/certificate_authorities/{authority_id}") + + def authority_id(self, name: str) -> int: + """An authority that must already be there, by the name a template gives it""" + if not name: + raise FleetError("the template names no certificate authority, and there is no SCEP address to find one by") + authorities = self._authorities() + match = [a for a in authorities if a.get("name") == name] + if not match: + known = ", ".join(sorted(str(a.get("name")) for a in authorities)) or "none" + raise FleetError(f"no certificate authority named {name!r}; the MDM has: {known}") + return int(match[0]["id"]) + + def bound_authority(self, team: int, certificate: str) -> int | None: + """The authority the team's certificate template of that name is bound to; None while the team has none""" + for template in self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []): + if template.get("name") == certificate: + return int(template.get("certificate_authority_id", 0)) + return None + + def _give_challenge(self, authority_id: int, name: object, scep_url: str, challenge: str) -> None: + """Hand an authority that serves scep_url the window's challenge; without one, leave it as it is""" + if not challenge: + return + # The challenge is never logged. No name in the body: Fleet reads a name on a PATCH as + # a rename and then refuses it as a conflict with the authority's own existing name, + # so sending it turns every update into a 409. + LOGGER.info("Giving certificate authority %s at %s the new challenge", name, scep_url) + self._call( + "PATCH", + f"/api/latest/fleet/certificate_authorities/{authority_id}", + {"custom_scep_proxy": {"url": scep_url, "challenge": challenge}}, + ) + + def ensure_authority(self, scep_url: str, challenge: str, name: str = "", bound: int | None = None) -> int: + """The SCEP CA this Deploy App is, created if the MDM does not have it yet Pointing the MDM at a SCEP server is MDM configuration, not protocol, so there is no standard for it and every MDM words it differently. Fleet happens to expose it, so here it is one less thing for an operator to get wrong by hand. - One authority of a name serves one Deploy App. An existing one with another URL is refused, - never repointed: the shipped template names the same authority for every Deploy App, so a - second Deploy App on the same Fleet would otherwise send the first one's phones to itself. - One with this URL gets the challenge whenever there is one: RASENMAEHER makes a new one for - every enrolment window, and Fleet never hands the old one back to compare against. + An authority is known by the address it serves, whatever it is called. So every Deploy App + on one Fleet has its own, and one made under the name all of them once shared, or by hand, + is still found. It gets the challenge whenever there is one: RASENMAEHER makes a new one + for every enrolment window, and Fleet never hands the old one back to compare against. + + Only a new one needs a name: the template's, or else authority_name(). A name that serves + another address is refused, never repointed: that would send its phones to this Deploy App. + + bound is the authority the team's certificate template is already bound to: its phones ask + that one and no other, so it gets the challenge or nothing does. If it serves another address, + by a different host or only by a slash, that is refused before anything is changed: a new + authority beside it would take the challenge and leave the team's phones to be refused. """ - authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) - match = [a for a in authorities if a.get("name") == name] - if match: - authority_id = int(match[0]["id"]) - # The listing does not carry the url, only the detail does, so compare against the detail - serves = self._call("GET", f"/api/latest/fleet/certificate_authorities/{authority_id}").get("url") - if _same_case(serves or "") != _same_case(scep_url): + if bound is not None: + held = self._authority(bound) + serves = str(held.get("url") or "") + if _same_case(serves) != _same_case(scep_url): raise FleetError( - f"certificate authority {name} already serves {serves or 'another address'}: connect this " - "Deploy App to a Fleet of its own, give it a template that names another authority, or delete " - "that authority in Fleet if the Deploy App moved" + f"the team takes its certificates from authority {held.get('name')}, which serves " + f"{serves or 'another address'}, not {scep_url}, so nothing was changed. If that authority is " + "this Deploy App's, correct its address in Fleet; if not, choose another team." ) - if not challenge: - return authority_id - # The challenge is never logged. No name in the body: Fleet reads a name on a PATCH as - # a rename and then refuses it as a conflict with the authority's own existing name, - # so sending it turns every update into a 409. - LOGGER.info("Giving certificate authority %s at %s the new challenge", name, scep_url) - self._call( - "PATCH", - f"/api/latest/fleet/certificate_authorities/{authority_id}", - {"custom_scep_proxy": {"url": scep_url, "challenge": challenge}}, - ) + self._give_challenge(bound, held.get("name"), scep_url, challenge) + return bound + wanted = name or authority_name(scep_url) + # Only a custom SCEP proxy has an address to compare. The likely names are asked first. + proxies = [a for a in self._authorities() if a.get("type", "custom_scep_proxy") == "custom_scep_proxy"] + taken = "" + for listed in sorted(proxies, key=lambda a: a.get("name") not in (wanted, LEGACY_AUTHORITY)): + authority_id = int(listed["id"]) + serves = str(self._authority(authority_id).get("url") or "") + if _same_case(serves) != _same_case(scep_url): + if listed.get("name") == wanted: + taken = serves or "another address" + continue + self._give_challenge(authority_id, listed.get("name"), scep_url, challenge) return authority_id + if taken: + raise FleetError( + f"certificate authority {wanted} already serves {taken}: give this Deploy App a template that " + "names another authority, or delete that authority in Fleet if the Deploy App moved" + ) - LOGGER.info("Creating certificate authority %s -> %s", name, scep_url) + LOGGER.info("Creating certificate authority %s -> %s", wanted, scep_url) created = self._call( "POST", "/api/latest/fleet/certificate_authorities", - {"custom_scep_proxy": {"name": name, "url": scep_url, "challenge": challenge}}, + {"custom_scep_proxy": {"name": wanted, "url": scep_url, "challenge": challenge}}, ) body = created.get("certificate_authority") or created return int(body["id"]) - def ensure_certificate(self, team: int, name: str, subject: str, authority: str) -> int: + def ensure_certificate(self, team: int, name: str, subject: str, authority: int) -> int: """The template the MDM fills in per device, and asks us to sign There is no update in place, so a changed subject is delete then create. The name is kept @@ -481,29 +553,33 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str) Refused while the team has devices. Replacing the template makes each of them delete the certificate it has and ask again, and the deployment refuses a name that is already taken, so all of them would lose access (measured on Fleet 4.90). - """ - authorities = self._call("GET", "/api/latest/fleet/certificate_authorities").get("certificate_authorities", []) - match = [a for a in authorities if a.get("name") == authority] - if not match: - known = ", ".join(sorted(str(a.get("name")) for a in authorities)) or "none" - raise FleetError(f"no certificate authority named {authority!r}; the MDM has: {known}") - authority_id = int(match[0]["id"]) + Refused, devices or none, when the team's template is bound to another authority: a team + takes its certificates from one Deploy App, and replacing the template would enrol that + Deploy App's phones into this one. Fleet keeps an authority while a template is bound to it. + apply() finds that out before it changes anything, through ensure_authority's bound; this + is the same refusal for a caller that names an authority instead. + """ existing = self._call("GET", f"/api/latest/fleet/certificates?team_id={team}").get("certificates", []) for template in existing: if template.get("name") != name: continue - if ( - template.get("subject_name") == subject - and int(template.get("certificate_authority_id", 0)) == authority_id - ): + bound = int(template.get("certificate_authority_id", 0)) + if bound != authority: + other = self._authority(bound) + raise FleetError( + f"team {team} takes its certificates from authority {other.get('name')}, which serves " + f"{other.get('url') or 'another address'}: a team belongs to one Deploy App. Choose another " + "team for this Deploy App." + ) + if template.get("subject_name") == subject: return int(template["id"]) devices = len(self._hosts(team)) if devices: raise FleetError( f"replacing certificate template {name} would delete the certificate of {devices} devices in " - f"team {team}, and their names would be refused when they ask again, so nothing was changed. " - "Use a new team, or empty this one first." + f"team {team}, and their names would be refused when they ask again, so the template was left " + "as it is. Use a new team, or empty this one first." ) self._call("DELETE", f"/api/latest/fleet/certificates/{template['id']}?team_id={team}") LOGGER.info("Replacing certificate template %s", name) @@ -511,7 +587,7 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: str) created = self._call( "POST", "/api/latest/fleet/certificates", - {"name": name, "team_id": team, "certificate_authority_id": authority_id, "subject_name": subject}, + {"name": name, "team_id": team, "certificate_authority_id": authority, "subject_name": subject}, ) LOGGER.info("Certificate template %s asks for %s", name, subject) return int(created["id"]) @@ -605,26 +681,31 @@ def apply( certificate visible to anything at all. Both have to be true before a device joins, because that is the only moment apps install. - Given scep_url, the certificate authority is created too, so a fresh deployment needs - nothing typed into Fleet by hand. Without it the authority must already be there, which - is the case for an MDM we cannot create one in. + Given scep_url, the certificate authority is found by it, or created, so a fresh deployment + needs nothing typed into Fleet by hand. Without it the template must name an authority that + is already there, which is the case for an MDM we cannot create one in. Without create_team, a team Fleet lacks is NoTeam before anything is changed. """ # Without create_team the team is looked up first, so a team missing leaves Fleet as it was team = None if create_team else self.team_id(team_name) - # The authority before a team is made: refusing it must leave Fleet as it was, a new team included + # The authority before a team is made: refusing it must leave Fleet as it was, a new team included. + # A team that is there may have its template bound to an authority already: that one is the team's. + authority = 0 if template.certificate and scep_url: - self.ensure_authority(template.certificate.authority, scep_url, challenge) + if team is None: + try: + team = self.team_id(team_name) + except NoTeam: + team = None + bound = self.bound_authority(team, template.certificate.name) if team is not None else None + authority = self.ensure_authority(scep_url, challenge, template.certificate.authority, bound) + elif template.certificate: + authority = self.authority_id(template.certificate.authority) if team is None: team = self.team_id(team_name, create=True) if template.certificate: - self.ensure_certificate( - team, - template.certificate.name, - template.certificate.subject, - template.certificate.authority, - ) + self.ensure_certificate(team, template.certificate.name, template.certificate.subject, authority) self.ensure_policy(team, template.policy, force=force_policy) packages = [app.package for app in template.apps] diff --git a/src/odmdm_connector/fleet_plugin.py b/src/odmdm_connector/fleet_plugin.py index a60ffed..d6c60c6 100644 --- a/src/odmdm_connector/fleet_plugin.py +++ b/src/odmdm_connector/fleet_plugin.py @@ -58,7 +58,7 @@ def _refused(exc: FleetError, named: Mapping[str, str] | None = None, lines: Seq class FleetPlugin: - """FleetDM, one team per Deploy App""" + """FleetDM: a team and a certificate authority per Deploy App, any number of them on one Fleet""" API_VERSION: ClassVar[int] = API_VERSION title: ClassVar[str] = "Fleet" @@ -167,12 +167,18 @@ def setup(self, window: Settings, force: bool = False, dry_run: bool = False) -> yield Step(f"Applied to team {self.team} ({result['team_id']}): {len(result['assigned'])} apps assigned", True) def set_challenge(self, window: Settings) -> None: - """Give the template's certificate authority the window's challenge, and change nothing else""" + """Give this Deploy App's certificate authority the window's challenge, and change nothing else""" wanted = self._template(window) if not wanted.certificate: raise MdmError("The template states no certificate, so there is no authority to give it to") + api = self._fleet() try: - self._fleet().ensure_authority(wanted.certificate.authority, window.scep_url, window.challenge) + # The team's phones ask the authority its certificate template is bound to: that one gets the challenge + try: + bound = api.bound_authority(api.team_id(self.team), wanted.certificate.name) + except NoTeam: + bound = None + api.ensure_authority(window.scep_url, window.challenge, wanted.certificate.authority, bound) except FleetError as exc: raise _refused(exc) from exc diff --git a/tests/test_fleet.py b/tests/test_fleet.py index f03903c..fbf6555 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -20,7 +20,7 @@ from odmdm_connector import __version__ from odmdm_connector import fleet as fleet_module -from odmdm_connector.fleet import FleetError, FleetMdm +from odmdm_connector.fleet import FleetError, FleetMdm, authority_name from odmdm_connector.icon import launcher_icon from odmdm_connector.template import App, Certificate, LinkApp, MdmTemplate @@ -83,6 +83,7 @@ def __init__(self) -> None: self.hosts: list[dict[str, Any]] = [] self.web_apps: list[dict[str, Any]] = [] self.authorities: list[dict[str, Any]] = [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + self.teams: list[dict[str, Any]] = [{"id": 7, "name": "rmscep"}] self._next_id = 100 def handler(self, request: Request) -> Response: @@ -139,7 +140,8 @@ def handler(self, request: Request) -> Response: return Response(200, json=matching[0] if matching else {}) if path.endswith("/certificate_authorities") and request.method == "POST": body = json.loads(request.content)["custom_scep_proxy"] - made = {"id": 55, "name": body["name"], "url": body["url"]} + self._next_id += 1 + made = {"id": self._next_id, "name": body["name"], "url": body["url"], "challenge": body["challenge"]} self.authorities.append(made) return Response(200, json={"certificate_authority": made}) if "/certificate_authorities/" in path and request.method == "PATCH": @@ -154,12 +156,18 @@ def handler(self, request: Request) -> Response: authority.update(body) return Response(200, json={}) if path.endswith("/certificates") and request.method == "GET": - return Response(200, json={"certificates": self.certificates}) + # A team's own templates; one a test put there without a team is every team's + team = int(request.url.params.get("team_id", "0")) + return Response( + 200, json={"certificates": [c for c in self.certificates if c.get("team_id", team) == team]} + ) if path.endswith("/certificates") and request.method == "POST": body = json.loads(request.content) + self._next_id += 1 made = { - "id": 27, + "id": self._next_id, "name": body["name"], + "team_id": body["team_id"], "subject_name": body["subject_name"], "certificate_authority_id": body["certificate_authority_id"], } @@ -170,7 +178,12 @@ def handler(self, request: Request) -> Response: self.certificates = [c for c in self.certificates if c["id"] != gone] return Response(200, json={}) if path == "/api/latest/fleet/teams" and request.method == "GET": - return Response(200, json={"teams": [{"id": 7, "name": "rmscep"}]}) + return Response(200, json={"teams": self.teams}) + if path == "/api/latest/fleet/teams" and request.method == "POST": + self._next_id += 1 + made = {"id": self._next_id, "name": json.loads(request.content)["name"]} + self.teams.append(made) + return Response(200, json={"team": made}) if path.endswith("/software/titles"): # Fleet scopes the listing to one team. A stub that ignored team_id would let a # lookup find another team's app and call that a pass. @@ -547,8 +560,160 @@ def test_a_new_windows_challenge_reaches_an_authority_already_pointing_at_us( assert fleet.authorities[0]["url"] == "https://deployment.test/scep" +def test_an_authority_is_named_after_its_deploy_app() -> None: + """Fleet takes letters, digits and underscores only""" + assert authority_name("https://golden-monkey.example.fi/scep") == "ODMDM_GOLDEN_MONKEY" + assert authority_name("https://North.example.fi/scep") == "ODMDM_NORTH" + + +def test_a_second_deploy_app_gets_an_authority_and_a_team_of_its_own(monkeypatch: pytest.MonkeyPatch) -> None: + """One Fleet serves several Deploy Apps, and the first one's authority, team and template stay as they are""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="first") + first = [dict(c) for c in fleet.certificates] + + mdm.apply("second DeployApp", _with_cert(""), scep_url="https://second.test/scep", challenge="second") + + assert [(a["name"], a["url"], a["challenge"]) for a in fleet.authorities] == [ + ("RMSCEP", "https://deployment.test/scep", "first"), + ("ODMDM_SECOND", "https://second.test/scep", "second"), + ] + assert [team["name"] for team in fleet.teams] == ["rmscep", "second DeployApp"] + assert fleet.certificates[: len(first)] == first + [made] = fleet.certificates[len(first) :] + assert (made["team_id"], made["certificate_authority_id"]) == (fleet.teams[1]["id"], fleet.authorities[1]["id"]) + + +def test_an_authority_under_the_old_shared_name_is_found_by_its_address(monkeypatch: pytest.MonkeyPatch) -> None: + """Every Deploy App's authority was once RMSCEP: a template that names none must not make a second one + + A second one would get the team's template replaced, and every phone asked again under a taken name. + """ + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c9") + + assert [(a["id"], a["name"], a["challenge"]) for a in fleet.authorities] == [(3, "RMSCEP", "c9")] + assert [c["certificate_authority_id"] for c in fleet.certificates] == [3] + + +def test_an_authority_made_by_hand_is_found_by_its_address(monkeypatch: pytest.MonkeyPatch) -> None: + """Whatever it was called in Fleet's console; another Deploy App's is asked and left alone""" + fleet = _Fleet() + fleet.authorities = [ + {"id": 4, "name": "OTHER_UNIT", "url": "https://other.test/scep"}, + {"id": 9, "name": "Typed_by_hand", "url": "https://deployment.test/scep"}, + ] + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c9") + + assert [a.get("challenge") for a in fleet.authorities] == [None, "c9"] + assert [c["certificate_authority_id"] for c in fleet.certificates] == [9] + + +def test_the_likely_names_are_asked_for_their_address_first(monkeypatch: pytest.MonkeyPatch) -> None: + """The listing has no address, so each one costs a request: another Deploy App's is not asked""" + fleet = _Fleet() + fleet.authorities.insert(0, {"id": 4, "name": "OTHER_UNIT", "url": "https://other.test/scep"}) + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep") + + assert ("GET", "/api/latest/fleet/certificate_authorities/3") in fleet.calls + assert ("GET", "/api/latest/fleet/certificate_authorities/4") not in fleet.calls + + +def test_an_authority_of_another_kind_has_no_address_to_ask_for(monkeypatch: pytest.MonkeyPatch) -> None: + fleet = _Fleet() + fleet.authorities = [{"id": 2, "name": "DIGI", "type": "digicert"}] + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c") + + assert ("GET", "/api/latest/fleet/certificate_authorities/2") not in fleet.calls + assert [a["name"] for a in fleet.authorities] == ["DIGI", "ODMDM_DEPLOYMENT"] + + +def test_a_template_may_name_a_new_authority(monkeypatch: pytest.MonkeyPatch) -> None: + """For two Deploy Apps whose hosts begin alike""" + fleet = _Fleet() + _mdm(fleet, monkeypatch).apply("north", _with_cert("NORTH_2"), scep_url="https://north.other.test/scep") + + assert [(a["name"], a["url"]) for a in fleet.authorities[1:]] == [("NORTH_2", "https://north.other.test/scep")] + + +def test_a_name_that_serves_another_address_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """Two Deploy Apps whose hosts begin alike would share a name, and it is never repointed""" + fleet = _Fleet() + fleet.authorities = [{"id": 4, "name": "ODMDM_NORTH", "url": "https://north.example.fi/scep"}] + with pytest.raises(FleetError) as raised: + _mdm(fleet, monkeypatch).apply("north", _with_cert(""), scep_url="https://north.other.test/scep", challenge="c") + + assert str(raised.value) == ( + "certificate authority ODMDM_NORTH already serves https://north.example.fi/scep: give this Deploy App a " + "template that names another authority, or delete that authority in Fleet if the Deploy App moved" + ) + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_a_team_of_another_deploy_app_is_refused_even_when_empty(monkeypatch: pytest.MonkeyPatch) -> None: + """Replacing its template would enrol that Deploy App's phones into this one""" + fleet = _Fleet() + mdm = _mdm(fleet, monkeypatch) + mdm.apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep") + before = [dict(c) for c in fleet.certificates] + fleet.calls.clear() + + with pytest.raises(FleetError) as raised: + mdm.apply("rmscep", _with_cert(""), scep_url="https://second.test/scep", challenge="c2") + + assert str(raised.value) == ( + "the team takes its certificates from authority RMSCEP, which serves https://deployment.test/scep, not " + "https://second.test/scep, so nothing was changed. If that authority is this Deploy App's, correct its " + "address in Fleet; if not, choose another team." + ) + assert fleet.certificates == before + assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet, no authority made beside it" + + +@pytest.mark.parametrize( + "held", ["https://deployment.test/scep/", "https://deployment.test:443/scep", "https://deployment.test/SCEP"] +) +def test_an_address_that_differs_by_little_is_refused_aloud(monkeypatch: pytest.MonkeyPatch, held: str) -> None: + """An authority typed by hand with a slash too many is not this address + + Making a new one beside it would give that one the challenge, and the team's phones, which ask + the one their template is bound to, would be refused with nothing to show why. + """ + fleet = _Fleet() + fleet.authorities = [{"id": 3, "name": "Typed_by_hand", "url": held}] + fleet.certificates = [ + {"id": 81, "name": "rmscep", "subject_name": "CN=$VAR,OU=$OTHER", "certificate_authority_id": 3} + ] + + with pytest.raises(FleetError, match="which serves " + re.escape(held) + ", not https://deployment.test/scep"): + _mdm(fleet, monkeypatch).apply( + "rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c2" + ) + + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + +def test_the_challenge_goes_to_the_authority_the_team_is_bound_to(monkeypatch: pytest.MonkeyPatch) -> None: + """Two authorities typed for one address: the team's phones ask only the one its template names""" + fleet = _Fleet() + fleet.authorities = [ + {"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}, + {"id": 9, "name": "Second_of_the_same", "url": "https://deployment.test/scep"}, + ] + fleet.certificates = [ + {"id": 81, "name": "rmscep", "subject_name": "CN=$VAR,OU=$OTHER", "certificate_authority_id": 9} + ] + + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(""), scep_url="https://deployment.test/scep", challenge="c2") + + assert [a.get("challenge") for a in fleet.authorities] == [None, "c2"] + assert [c["certificate_authority_id"] for c in fleet.certificates] == [9], "the template was left as it is" + + def test_an_authority_that_serves_another_deploy_app_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: - """The shipped template names the same authority for every Deploy App + """A template that names an authority gets that one or none Repointing it would send the phones of the Deploy App it serves to the one connected now. """ @@ -557,9 +722,8 @@ def test_an_authority_that_serves_another_deploy_app_is_refused(monkeypatch: pyt _mdm(fleet, monkeypatch).apply("rmscep", _with_cert(), scep_url="https://moved.test/scep", challenge="rotated") assert str(raised.value) == ( - "certificate authority RMSCEP already serves https://deployment.test/scep: connect this Deploy App to a " - "Fleet of its own, give it a template that names another authority, or delete that authority in Fleet if " - "the Deploy App moved" + "certificate authority RMSCEP already serves https://deployment.test/scep: give this Deploy App a " + "template that names another authority, or delete that authority in Fleet if the Deploy App moved" ) assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://deployment.test/scep"}] assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" @@ -589,6 +753,14 @@ def test_without_a_scep_url_the_authority_must_already_exist(monkeypatch: pytest fleet.authorities = [] with pytest.raises(FleetError, match="RMSCEP"): _mdm(fleet, monkeypatch).apply("rmscep", _with_cert()) + assert not [c for c in fleet.calls if c[0] != "GET"], "no team was made for it" + + +def test_without_a_scep_url_a_template_must_name_its_authority(monkeypatch: pytest.MonkeyPatch) -> None: + fleet = _Fleet() + with pytest.raises(FleetError, match="names no certificate authority"): + _mdm(fleet, monkeypatch).apply("rmscep", _with_cert("")) + assert not fleet.calls def test_applying_twice_publishes_one_web_app(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py index d3dc866..b90f174 100644 --- a/tests/test_fleet_plugin.py +++ b/tests/test_fleet_plugin.py @@ -201,6 +201,48 @@ def test_the_team_is_named_after_the_deployment_by_default() -> None: assert team.default_for("golden-monkey.example.fi") == "golden-monkey DeployApp" +def test_a_new_window_reaches_only_this_deploy_apps_authority(fleet: _Fleet) -> None: + """On a Fleet that serves several Deploy Apps, each with a challenge of its own + + The names say nothing: the team's template is bound to authority 3, which serves this Deploy App. + """ + fleet.authorities = [ + {"id": 4, "name": "UNIT_B", "url": "https://north.example.fi/scep", "challenge": "norths"}, + {"id": 3, "name": "UNIT_A", "url": "https://example.fi/scep", "challenge": "old"}, + ] + + _plugin().set_challenge(WINDOW) + + assert [authority["challenge"] for authority in fleet.authorities] == ["norths", "new-window"] + assert [call for call in fleet.calls if call[0] != "GET"] == [ + ("PATCH", "/api/latest/fleet/certificate_authorities/3") + ] + + +def test_a_new_window_is_refused_when_the_team_asks_another_address(fleet: _Fleet) -> None: + """A Deploy App that moved, or the wrong team: said aloud, and the challenge goes nowhere""" + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://old.example.fi/scep", "challenge": "old"}] + + with pytest.raises(MdmError) as raised: + _plugin().set_challenge(WINDOW) + + assert str(raised.value) == ( + "Fleet refused: the team takes its certificates from authority RMSCEP, which serves " + "https://old.example.fi/scep, not https://example.fi/scep, so nothing was changed. If that authority is this " + "Deploy App's, correct its address in Fleet; if not, choose another team." + ) + assert fleet.authorities == [{"id": 3, "name": "RMSCEP", "url": "https://old.example.fi/scep", "challenge": "old"}] + assert not [call for call in fleet.calls if call[0] != "GET"] + + +def test_a_new_window_before_the_team_is_made_finds_the_authority_by_its_address(fleet: _Fleet) -> None: + fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] + + _plugin(team="golden-monkey DeployApp").set_challenge(WINDOW) + + assert fleet.authorities[0]["challenge"] == "new-window" + + def test_sending_the_policy_again_makes_no_team(fleet: _Fleet) -> None: """A repair creates nothing: a team Fleet lacks is refused before the authority or anything else is changed""" fleet.authorities = [{"id": 3, "name": "RMSCEP", "url": "https://example.fi/scep", "challenge": "old"}] From 3c7583a0673bbce8a410836019200249cae295c0 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 00:15:19 +0200 Subject: [PATCH 097/104] feat: the shipped template names no authority, so one Fleet serves several Deploy Apps --- src/odmdm_connector/template.json | 7 +++++-- src/odmdm_connector/template.py | 10 ++++++---- tests/test_template.py | 13 +++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/odmdm_connector/template.json b/src/odmdm_connector/template.json index 5faff5f..10ce4b2 100644 --- a/src/odmdm_connector/template.json +++ b/src/odmdm_connector/template.json @@ -44,9 +44,12 @@ "number, would make a leaked enrolment link enough for an identity. Fleet's id for the phone", "follows it as OU, so the deployment can tell later which device a callsign was issued to;", "leave the OU out only for a team that already has phones under a subject without it.", - "The name becomes the Android keystore alias, so it is per deployment." + "The name becomes the Android keystore alias, so it is per deployment.", + "No certificate authority is named: the connector finds this Deploy App's in the MDM by the", + "address it serves, and makes one when there is none, called ODMDM_ and the first part of the", + "Deploy App's host name.", + "So one MDM can serve several Deploy Apps. \"authority\": \"NAME\" here gives a new one that name." ], - "authority": "RMSCEP", "name": "{key_alias}", "subject": "CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID" }, diff --git a/src/odmdm_connector/template.py b/src/odmdm_connector/template.py index d45ce15..a2151f1 100644 --- a/src/odmdm_connector/template.py +++ b/src/odmdm_connector/template.py @@ -91,7 +91,9 @@ class Certificate: name: str subject: str - authority: str + #: The MDM's certificate authority by name. Without one the MDM plugin finds the Deploy App's + #: own by the address it serves, and makes it when there is none. + authority: str = "" @dataclass(frozen=True) @@ -190,11 +192,11 @@ def load(path: Traversable, domain: str, key_alias: str) -> MdmTemplate: certificate = None if raw.get("certificate"): entry = raw["certificate"] - missing = [key for key in ("name", "subject", "authority") if not entry.get(key)] + missing = [key for key in ("name", "subject") if not entry.get(key)] if not isinstance(entry, dict) or missing: - raise TemplateError(f"certificate needs name, subject and authority; missing {missing}") + raise TemplateError(f"certificate needs name and subject; missing {missing}") certificate = Certificate( - name=str(entry["name"]), subject=str(entry["subject"]), authority=str(entry["authority"]) + name=str(entry["name"]), subject=str(entry["subject"]), authority=str(entry.get("authority") or "") ) unsafe = _unsafe(policy, raw.get("certificate") or None) diff --git a/tests/test_template.py b/tests/test_template.py index e45009a..db22e0e 100644 --- a/tests/test_template.py +++ b/tests/test_template.py @@ -181,6 +181,19 @@ def test_the_example_is_a_template_we_accept() -> None: assert [r["packageNames"] for r in rules] == [["com.android.chrome", "com.atakmap.app.civ", "im.vector.app"]] +def test_the_shipped_template_names_no_authority() -> None: + """The connector finds a Deploy App's authority by its address, so one MDM can serve several""" + template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None and template.certificate.authority == "" + + +def test_a_template_may_name_its_authority(tmp_path: Path) -> None: + template = load(_write(tmp_path, _with()), domain="example.fi", key_alias="rmscep") + + assert template.certificate is not None and template.certificate.authority == "RMSCEP" + + def test_the_shipped_subject_carries_the_device_id() -> None: """A subject cannot change once a team has phones, so the id is there from the first template""" template = load(EXAMPLE, domain="example.fi", key_alias="rmscep") From ad836a1ecee7269d00c3cf56110eeb89f6b3d7d6 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 00:15:19 +0200 Subject: [PATCH 098/104] docs: several Deploy Apps on one Fleet, and who can change what there --- AGENTS.md | 6 ++++++ README.rst | 19 ++++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9a93e84..4eecf67 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,6 +169,12 @@ Names already in use on live Fleets are identities, not cosmetics: the policy pr certificate template name (the Android keystore alias). Changing either duplicates the profile or strands every enrolled phone's key. +A certificate authority is the exception: it is known by the address it serves, never by its name +(`FleetMdm.ensure_authority`), so one Fleet serves several Deploy Apps and an authority named +`RMSCEP` or typed by hand keeps working. Never look one up by a fixed name, and never repoint one: +its teams' phones would enrol into another Deploy App. Fleet keeps an authority while a certificate +template is bound to it (a foreign key without ON DELETE in Fleet 4.90.1's schema). + ## Commands - Setup: `uv sync` diff --git a/README.rst b/README.rst index b568131..313d1b7 100644 --- a/README.rst +++ b/README.rst @@ -68,9 +68,12 @@ settings, whether its token is kept on this computer, and where the log is, and policy again** for a phone whose browser refuses its certificate (see `The order that works`_): it ticks off its steps as **Connect** does, and the phones keep their certificates and apps. The Deploy App's name at the top right lists the Deploy Apps added, opens another, adds one or removes the one open. -Each Deploy App needs a Fleet of its own: the shipped template names one certificate -authority for every Deploy App, and the connector refuses to point an authority that serves one -Deploy App at another. +One Fleet can serve several Deploy Apps. Each has a certificate authority of its own in Fleet and +a team of its own; the connector never points an authority that serves one Deploy App at another, +and refuses a team whose certificate template takes its certificates from another address (see +`The template`_). A challenge goes only to the authority the team's template is bound to. +The API token is a global admin's, so whoever runs the connector for one Deploy App can change +every team in that Fleet: share a Fleet only among people who trust each other with it. For every batch: open enrolment in Deploy App and press **Open in the MDM connector** again, or **New settings** and paste the line, so the MDM gets the new challenge. Let the phones enrol, then @@ -356,6 +359,16 @@ in a template of its own. A name the phone supplies, such as its serial number, would make a leaked enrolment link enough for an identity. +The shipped template names no certificate authority. The connector finds a Deploy App's authority +in Fleet by the address it serves, whatever it is called, and makes one when there is none: +``ODMDM_`` and the first part of the Deploy App's host name, in capitals, as +``ODMDM_GOLDEN_MONKEY`` for ``golden-monkey.example.fi``. Two Deploy Apps whose host names begin +alike would get the same name; the second is refused until its template names another: +``"authority": "NAME"`` beside the certificate's ``name`` and ``subject``, in letters, digits and +underscores. An authority made earlier as ``RMSCEP``, or by hand, is found by its address and kept: +the address has to be the Deploy App's exactly, ``https:///scep`` with no slash after it. One +that differs is refused once a team's certificate template is bound to it, with both addresses said. + The tool also refuses a policy that lets an app use the key without being named in ``packageNames``, lets the user pick a key for any app (``privateKeySelectionEnabled``), or allows installs from unknown sources (``untrustedAppsPolicy`` other than ``DISALLOW_INSTALL``). From c95671921a1edc2c547adb0bb25090a1d6adb085 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 01:59:30 +0200 Subject: [PATCH 099/104] feat: challenge takes --team, as the team's template says which authority gets the challenge --- src/odmdm_connector/console.py | 2 +- tests/test_console.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index cc7b577..55bcb49 100644 --- a/src/odmdm_connector/console.py +++ b/src/odmdm_connector/console.py @@ -490,7 +490,7 @@ def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) help="Re-upload the policy even if unchanged, to reach a host that just joined", ) sub.add_argument("--dry-run", action="store_true", help="Read and validate the template, then stop") - command("challenge", challenge, "--template", "--mdm-url", "--domain") + command("challenge", challenge, "--template", "--mdm-url", "--team", "--domain") command("phones", phones, "--mdm-url", "--team") sub = command("name", name, "--mdm-url", "--team") sub.add_argument("pairs", nargs="*", metavar="ID=CALLSIGN") diff --git a/tests/test_console.py b/tests/test_console.py index b14a538..f0322d2 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -799,6 +799,21 @@ def test_challenge_takes_the_settings_line( assert SECRET not in caplog.text +def test_challenge_takes_the_team(window: _Fleet, run: Run) -> None: + """The team's certificate template says which authority gets the challenge, so the team is given as elsewhere""" + window.teams.append({"id": 8, "name": "North"}) + window.authorities.append({"id": 4, "name": "ODMDM_NORTH", "url": "https://north.example.fi/scep"}) + window.certificates = [ + {"id": 82, "name": "rmscep", "team_id": 8, "subject_name": NAMED, "certificate_authority_id": 4} + ] + + result = run(["challenge", "--team", "North"], env={"ODMDM_CHALLENGE": LINE}) + + assert result.exit_code == 1 + assert "the team takes its certificates from authority ODMDM_NORTH" in result.stderr + assert not _changes(window) + + def test_challenge_is_never_an_argument(window: _Fleet, run: Run) -> None: """An argument is in the process list and the shell history""" result = run(["challenge", "--challenge", LINE]) From a0f675a657a0f42c0be3419f2e848e5fdcc32c46 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 01:59:30 +0200 Subject: [PATCH 100/104] docs: any MDM and the page, where comments still said Fleet and the window --- AGENTS.md | 10 ++++++---- src/odmdm_connector/__init__.py | 2 +- src/odmdm_connector/mdm.py | 6 +++--- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4eecf67..07d86cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,16 +1,18 @@ # Agent guidance -Connects FleetDM to an OpenDefence deployment's SCEP enrolment. Read `README.rst` first. +Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment. Read +`README.rst` first. ## The boundary -The deployment speaks standard SCEP and knows no MDM; this repository is the only place that knows +The deployment speaks standard SCEP and knows no MDM; this repository and the plugins beside it are +the only place that knows one, and `fleet.py` and `fleet_plugin.py` the only place here that knows Fleet. Keep it that way in both directions: - Nothing here calls the deployment's API. What crosses over is a SCEP URL, the challenge an operator copies from Deploy App, and the callsign in the certificate subject. -- Nothing Fleet-specific goes back into the deployment's repositories. A Fleet behaviour that - needs handling is handled here. +- Nothing that knows an MDM goes back into the deployment's repositories. An MDM's behaviour that + needs handling is handled in that MDM's plugin: Fleet's here. - No product knowledge in code. What a deployment installs arrives in the template. ## Layout diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index 2a8190a..2eb4e4a 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ -"""Connects FleetDM to an OpenDefence deployment's SCEP enrolment""" +"""Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment""" __version__ = "1.4.0+261122" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py index 1c895e7..3d1a02d 100644 --- a/src/odmdm_connector/mdm.py +++ b/src/odmdm_connector/mdm.py @@ -5,7 +5,7 @@ the class's API_VERSION before it uses it. Every sentence a plugin hands back, a Step's message, a line from name or ask_again, an MdmError, -is shown to the operator as it is, by the command line and the window alike, so it names no +is shown to the operator as it is, by the command line and the page alike, so it names no command, option or button. The SCEP challenge is never in one. """ @@ -64,7 +64,7 @@ class Field: """A setup value a plugin needs, such as its MDM's address A secret is never taken from an option or a plain environment variable, only from a file. - A required one must be given: the window does not connect without it, and the command line + A required one must be given: the page does not connect without it, and the command line says how to give it. DEPLOYMENT in the default stands for the deployment's name, so that "{deployment} DeployApp" is "golden-monkey DeployApp" for golden-monkey.example.fi. """ @@ -75,7 +75,7 @@ class Field: default: str = "" help: str = "" required: bool = False - #: Rarely changed: the window shows it only when asked + #: Rarely changed: the page shows it only when asked advanced: bool = False def default_for(self, host: str) -> str: From 9725722dab939fe9a42f5f64c9fef64b586da90b Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 01:59:31 +0200 Subject: [PATCH 101/104] fix(demo): the demo plugin needs connector 1.4, which brought what it uses --- examples/odmdm-connector-demo/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/odmdm-connector-demo/pyproject.toml b/examples/odmdm-connector-demo/pyproject.toml index b9a9c73..3bd83b1 100644 --- a/examples/odmdm-connector-demo/pyproject.toml +++ b/examples/odmdm-connector-demo/pyproject.toml @@ -6,7 +6,7 @@ license = "MIT" readme = "README.rst" requires-python = ">=3.11,<4.0" dependencies = [ - "odmdm-connector>=1.1,<2", + "odmdm-connector>=1.4,<2", ] [project.entry-points."odmdm_connector.mdm"] From 48042bef28eaf53b5c46df9f7c27b733c8f70108 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 01:59:31 +0200 Subject: [PATCH 102/104] docs: what an MDM needs, the shortest way, and Fleet in a chapter of its own --- README.rst | 300 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 224 insertions(+), 76 deletions(-) diff --git a/README.rst b/README.rst index 313d1b7..7617bb5 100644 --- a/README.rst +++ b/README.rst @@ -2,18 +2,70 @@ odmdm-connector =============== -Connects an MDM, FleetDM built in, to an OpenDefence deployment's device enrolment. +Connects your MDM, the mobile device management system that sets up your unit's Android phones, +to a Deploy App deployment (OpenDefence), so that the phones join Deploy App by themselves, each +under its own callsign, the name Deploy App knows a device by. Fleet (FleetDM) is built in. Any +other MDM that can do what `What an MDM needs`_ lists needs a plugin, a small Python package: +install one that exists, or write one (`Write a plugin`_). + +It is for the admin who runs a unit's MDM and is an admin in its Deploy App. It runs on that +admin's own computer, as a page in the browser or from the command line, and keeps one secret: the +MDM's API token. It: + +- sets the MDM up for one Deploy App, as far as the MDM's API allows: where phones ask for their + certificates and, with Fleet, also what they install and the policy that lets the apps use the + certificate; +- hands the MDM the challenge of each enrolment window: the secret phones must show while an + admin has enrolment open in Deploy App, which the connector holds in memory only; +- lists the phones that enrolled, and where each one's certificate is; +- gives phones their callsigns, any number at once, and asks again for the ones that failed. The deployment knows no MDM. It answers standard SCEP (RFC 8894) at ``https:///scep``, asks for a challenge that is new every time an admin opens enrolment in Deploy App, and makes the -certificate's common name the device's callsign. Everything that knows Fleet lives here: the -certificate authority, the certificate template, the apps, the device policy, the launcher icon, -and naming the phones. +certificate's common name the device's callsign. Everything that knows an MDM lives here, behind +one contract, and each MDM in a plugin of its own: Fleet's is built in (`Fleet`_), another MDM's +is a package beside the connector (`Plugins`_). -Run it from an operator's machine, never inside the deployment: it holds a Fleet API token, and +Run it from an operator's machine, never inside the deployment: it holds the MDM's API token, and something that can reach every device a unit owns has no business running next to an internet facing service. +What an MDM needs +----------------- + +An MDM fits, for managed Android phones, if an operator can do five things in it: + +1. Keep one Deploy App's phones in a group of its own, with its own enrolment. +2. Send each phone's certificate request to Deploy App's SCEP URL with one challenge, the same + for every phone of an enrolment window. +3. Put a value that can be set for each phone into the certificate subject: the callsign, as the + common name. +4. Take a new challenge for each enrolment window. +5. Ask one phone for its certificate again and leave the others alone. + +A plugin does through the MDM's API what the MDM lets it do, and at least lists the phones and +names them. For what it cannot do, the connector says what to do in the MDM by hand, and changes +nothing. Fleet can do all five by API. + +The shortest way +---------------- + +1. Get the connector. In Deploy App, as an admin, open **User Management**, then **MDM**, and + press **Install the ODMDM connector**: download the file for your computer and start it (`A + file to download`_). Or install it with uv (`Install`_) and type ``odmdm-connector``: for an + MDM other than Fleet that is the way, as the downloaded files take no plugin (`Plugins`_). +2. Its page opens in your browser. On Deploy App's MDM page press **Open for 2 hours**, then + **Open in the MDM connector**, and confirm your Deploy App on the connector's page. +3. Give what your MDM asks for, with Fleet its address, an API token and a team (`Fleet`_), and + press **Connect**. +4. Enrol the phones in your MDM, then press **Give callsigns**: with Fleet, only once every phone + has its apps (`The order that works`_). +5. Each phone gets its certificate when it next asks its MDM, with Fleet within about 15 minutes. + Close enrolment in Deploy App once the page shows every phone with its certificate: a request + that arrives after it closes is refused. + +`The page`_ says more of each step, and `Enrolling phones`_ does the same by command. + Install ------- @@ -313,6 +365,31 @@ from the file its ``_FILE`` variable names: what the first deployments were set up with. Never change it for a deployment: a second key will not install over an existing alias. +The settings line +----------------- + +Deploy App's MDM page copies one line for the connector. It is the same for every MDM, and it +carries no list of names: phones are named in the MDM. Version 1 is exactly four fields +separated by whitespace:: + + ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z + +1. The mark ``ODMDM1``. +2. The SCEP URL, ``https:///`` and nothing else: no user name, password, port, query, + fragment or backslash. Deploy App writes ``https:///scep``. +3. The challenge: 32 lowercase hex characters. It is a secret, and the tool never prints or logs it. +4. When the enrolment window closes, in UTC, as ``YYYY-MM-DDTHH:MM:SSZ``. + +Whitespace and line breaks before and after the line are ignored. A line with another mark or +another number of fields, a URL that is not just https, a host and a path, a malformed challenge or +time, or a window that has already closed is refused. A line that a page hands to the connector is +taken only from that Deploy App's own pages, ``https://`` or ``https://mtls.``; one +typed or pasted by hand names no page. A value with whitespace inside it is read as a line, never +as a bare challenge, so a damaged paste is refused instead of being sent to Fleet. ``challenge`` +takes the line from ``ODMDM_CHALLENGE``, else at its hidden prompt, never as an argument; it refuses +one whose SCEP URL is not on ``ODMDM_DOMAIN``, and says until when the window is open, in this +computer's time. The line above is the shared test vector, in ``tests/data/settings-line-v1.txt``. + Plugins ------- @@ -335,101 +412,162 @@ Its settings are given as for Fleet: ``--set KEY=VALUE``, or ``ODMDM_``, an from the file ``ODMDM__FILE`` names. A plugin's MDM may lack something Fleet can do, such as taking the challenge by API; the command then says what to do instead and changes nothing. +Fleet +----- + +Fleet (FleetDM) works as it comes: the connector does in it by API everything `What an MDM +needs`_ lists. Fleet's behaviour as told here was measured on Fleet 4.90, and the menu names are +that version's. + +Fleet needs three things: + +- **Android MDM turned on**: Fleet's **Settings**, **Integrations**, **MDM**. Whoever runs Fleet + connects Android Enterprise there once, for all teams. +- **Fleet Premium**: teams and certificate authorities are part of it. +- **A global admin's API token.** Fleet keeps certificate authorities outside teams, so giving + one a new challenge takes a global admin. **My account**, **Get API token** gives the token of + your own sign-in, which Fleet ends after five days by default, or when you sign out; the + connector then says the token is not accepted. For a connector that stays set up, whoever runs + Fleet makes an API-only user with the role Admin for all of Fleet (**Settings**, **Users**, + **Add user**, **API-only user**), whose token does not end. + +Fleet's settings +~~~~~~~~~~~~~~~~ + +On the page these are its cards; for the commands, each is ``ODMDM_`` or ``--set``. +``--mdm-url``, ``--team`` and ``--template`` after a command that takes them say the same as +``--set mdm_url``, ``team`` and ``template``. + +``ODMDM_MDM_URL`` + The address you open Fleet at, such as ``https://fleet.example.fi``, without an API path. Only + https: the token goes with every request. + +``ODMDM_TOKEN_FILE`` + A file holding the API token. + +``ODMDM_TEAM`` + The team phones enrol into and get the certificate in. Default `` DeployApp``: + ``golden-monkey DeployApp`` for golden-monkey.example.fi. Without ``ODMDM_DOMAIN``, give the + team. A deployment set up with the earlier default keeps its team only when it is given: + ``--set team="Deploy App"``. + +``ODMDM_TEMPLATE`` + The document saying what to install, see `The template`_. Default: the one shipped with the + connector. + +``ODMDM_KEY_ALIAS`` + The certificate template's name, which becomes the Android keystore alias. Default ``rmscep``, + what the first deployments were set up with. Never change it for a deployment: a second key + will not install over an existing alias. + +A Fleet whose certificate comes from a private authority is trusted by pointing the +``SSL_CERT_FILE`` environment variable at that authority's certificate file, in PEM form, before +the connector starts. + +What Connect sets up +~~~~~~~~~~~~~~~~~~~~ + +**Connect**, or ``apply``, changes Fleet: it makes the team if it is not there, Deploy App as a +certificate authority, the team's certificate template, its policy, its apps and the **Deploy +App** launcher icon. The launcher is a web app that Google publishes for good (`What Fleet does +that you would not guess`_). Sending the policy again is a repair and makes no team. + +Each phone gets its certificate at its next check-in with Fleet, within about 15 minutes of being +named. One that Fleet has made no certificate request for yet only gets its name, which Fleet +fills in when it makes the request. Name the phones once every phone in the team has its apps: +naming can send the policy to all of them again (`The order that works`_). A phone that already +has its certificate under the name it is given is left alone, and renaming one that has its +certificate says which old callsign to revoke: remove it in Deploy App. + +Several Deploy Apps on one Fleet +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +One Fleet can serve several Deploy Apps. Each has a certificate authority of its own in Fleet and +a team of its own. The connector finds a Deploy App's authority by the address it serves, whatever +it is called, and makes one when there is none: ``ODMDM_`` and the first part of the Deploy App's +host name, in capitals, as ``ODMDM_GOLDEN_MONKEY`` for ``golden-monkey.example.fi``. Two Deploy +Apps whose host names have the same first part, such as ``unit.example.fi`` and +``unit.example.org``, would get the same authority name, the same default team and the same +launcher title, and the second is refused. Give it a team of its own and a template of its own +(`The template`_) that names another authority, ``"authority": "NAME"`` beside the certificate's +``name`` and ``subject``, in letters, digits and underscores, and another ``title`` in its +``link_app``. + +The connector never points an authority that serves one Deploy App at another. An authority made +earlier as ``RMSCEP``, or by hand, is found by its address and kept: the address has to be the +Deploy App's exactly, ``https:///scep`` with no slash after it. Once a team has its +certificate template, a challenge goes only to the authority that template is bound to, and a +team whose template is bound to an authority that serves another address is refused before +anything is changed, with both addresses said. + +The API token is a global admin's, so whoever runs the connector for one Deploy App can change +every team in that Fleet: share a Fleet only among people who trust each other with it. + The template ------------- +~~~~~~~~~~~~ -What to install is a property of the deployment, so it is a document rather than code: the apps, -their managed configuration, the Android Management API device policy, a launcher link, and the -certificate template. ``{domain}``, ``{mtls_url}`` and ``{key_alias}`` are filled in. Keys -beginning with ``_`` are comments and never reach Fleet. ``src/odmdm_connector/template.json``, shipped -in the package, is a working one for Deploy App, with its reasoning in the comments. +With Fleet, what to install is a property of the deployment, so it is a document rather than +code: the apps, their managed configuration, the Android Management API device policy, a launcher +link, and the certificate template. ``{domain}``, ``{mtls_url}`` and ``{key_alias}`` are filled +in. Keys beginning with ``_`` are comments and never reach Fleet. +The one shipped in the package, ``src/odmdm_connector/template.json`` in the repository, is a +working one for Deploy App, with its reasoning in the comments: copy it from there to change what +a deployment installs, and give your copy as the template. The certificate subject is the contract with the deployment. Its common name becomes the callsign: 3 to 32 letters, digits or hyphens, no hyphen at either end. It is the name ``name`` gives the -phone, followed by Fleet's id for the host, and the tool refuses any other:: +phone, optionally followed by Fleet's id for the host:: CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART, OU=$FLEET_VAR_HOST_UUID CN=$FLEET_VAR_HOST_END_USER_IDP_USERNAME_LOCAL_PART -The shipped template uses the first: the id lets the deployment tell later which device a callsign -was issued to. A subject cannot change on a team that has phones, since replacing the certificate -template removes every phone's certificate, so a team set up without the id keeps the second form -in a template of its own. +The tool refuses any other subject; it takes ``$FLEET_VAR_HOST_END_USER_IDP_USERNAME`` in place of +the ``_LOCAL_PART`` form, which is the same text for a callsign. The shipped template uses the +first: the id travels in the certificate request, so the deployment can tell later which device a +callsign was issued to. A subject cannot change on a team that has phones, since replacing the +certificate template removes every phone's certificate, so a team set up without the id keeps the +second form in a template of its own. A name the phone supplies, such as its serial number, would make a leaked enrolment link enough for an identity. -The shipped template names no certificate authority. The connector finds a Deploy App's authority -in Fleet by the address it serves, whatever it is called, and makes one when there is none: -``ODMDM_`` and the first part of the Deploy App's host name, in capitals, as -``ODMDM_GOLDEN_MONKEY`` for ``golden-monkey.example.fi``. Two Deploy Apps whose host names begin -alike would get the same name; the second is refused until its template names another: -``"authority": "NAME"`` beside the certificate's ``name`` and ``subject``, in letters, digits and -underscores. An authority made earlier as ``RMSCEP``, or by hand, is found by its address and kept: -the address has to be the Deploy App's exactly, ``https:///scep`` with no slash after it. One -that differs is refused once a team's certificate template is bound to it, with both addresses said. - The tool also refuses a policy that lets an app use the key without being named in ``packageNames``, lets the user pick a key for any app (``privateKeySelectionEnabled``), or -allows installs from unknown sources (``untrustedAppsPolicy`` other than ``DISALLOW_INSTALL``). - -The settings line ------------------ - -Deploy App's MDM page copies one line for the connector. It is the same for every MDM, and it -carries no list of names: phones are named in the MDM. Version 1 is exactly four fields -separated by whitespace:: - - ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z - -1. The mark ``ODMDM1``. -2. The SCEP URL, ``https:///`` and nothing else: no user name, password, port, query, - fragment or backslash. Deploy App writes ``https:///scep``. -3. The challenge: 32 lowercase hex characters. It is a secret, and the tool never prints or logs it. -4. When the enrolment window closes, in UTC, as ``YYYY-MM-DDTHH:MM:SSZ``. - -Whitespace and line breaks before and after the line are ignored. A line with another mark or -another number of fields, a URL that is not just https, a host and a path, a malformed challenge or -time, or a window that has already closed is refused. A line that a page hands to the connector is -taken only from that Deploy App's own pages, ``https://`` or ``https://mtls.``; one -typed or pasted by hand names no page. A value with whitespace inside it is read as a line, never -as a bare challenge, so a damaged paste is refused instead of being sent to Fleet. ``challenge`` -takes the line from ``ODMDM_CHALLENGE``, else at its hidden prompt, never as an argument; it refuses -one whose SCEP URL is not on ``ODMDM_DOMAIN``, and says until when the window is open, in this -computer's time. The line above is the shared test vector, in ``tests/data/settings-line-v1.txt``. +allows installs from unknown sources (an ``untrustedAppsPolicy`` that begins ``ALLOW_``, or +``installUnknownSourcesAllowed``). The order that works --------------------- +~~~~~~~~~~~~~~~~~~~~ Three facts about managed Android and Fleet pull against each other. Each was learned by getting it wrong. 1. **Apps install at enrolment and at no other time.** The team must carry them before a phone - joins. A phone transferred in from a team with another launcher package loses that launcher - and never gets this one. + joins. A phone moved in from a team that has another launcher loses that launcher and never + gets this one. 2. **Fleet can overwrite a new phone's policy moments after sending it.** It sends a phone that enrols the team's policy, and seconds later can write a bare one over it. It goes on showing the policy as verified on that phone and never sends it again, so the phone has its certificate - but Chrome may not use it, and Deploy App says "Certificate Authentication Failed". ``name`` and - ``resend`` send the policy again, to every phone in the team, when a phone enrolled after it - was last sent. By hand it is **Send the policy again** in the page's **Settings**, - ``apply --force-policy``, or deleting the policy in Fleet and uploading it again. Sending it - again is a repair and makes no team: a team Fleet lacks is refused before anything is changed. + but Chrome may not use it, and Deploy App says "Certificate Authentication Failed". ``name`` + and ``resend`` send the policy again, to every phone in the team, when a phone enrolled after + it was last sent. A phone that enrols again onto its old host keeps its old enrolment time and + is not seen: send the policy again by hand for it. By hand it is **Send the policy again** in + the page's **Settings**, ``apply --force-policy``, or deleting the policy in Fleet and + uploading it again. Sending it again is a repair and makes no team: a team Fleet lacks is + refused before anything is changed. 3. **A policy rewritten while apps are installing stops them installing.** Leave the phones alone until the apps have arrived. What Fleet does that you would not guess ----------------------------------------- - -- **A launcher web app's URL can never change.** Google publishes it permanently and Fleet cannot - delete it. The title carries the deployment's name, so a moved deployment publishes its own - launcher and leaves the old one orphaned. Google refuses a title of 30 characters or more. -- **A web app's display name is unique within a team** (409). A title in a team's setup experience - has to be removed there before it can be removed from the team. -- **A token copied from a signed-in account ends with that sign-in.** **My account → Get API token** - gives the token of your own session, which Fleet ends after five days by default, or when you - sign out. The connector then says the token is not accepted. For a connector that stays set up, - give the token of an API-only user (``fleetctl user create --api-only``), which does not end. +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +- **A launcher web app's URL can never change, and its title is taken for good.** Google publishes + it permanently and Fleet cannot delete it. The title carries the first part of the deployment's + host name, so a deployment moved to a host with another first part publishes its own launcher + and leaves the old one orphaned. One moved to a host with the same first part keeps the old + launcher, which still opens the old host: give the template's ``link_app`` another ``title``. + Fleet refuses a title already published, in any team and even in one since deleted. Google + refuses a title of 30 characters or more. - **A phone enrols before it has a name**, so its first certificate request fails (``does not have an IDP user``) until it is named, and naming it does not send the request again. ``name`` resends. A resend is one more attempt, which the phone acts on at its next check-in, every 15 @@ -437,15 +575,25 @@ What Fleet does that you would not guess - **A returning phone keeps its old team and its old name.** Transfer it into this team if it was in another, and give it a new name with ``name``, or it asks for a name that is already taken. It can also come back as a new device with no name. -- **Renaming a phone that has its certificate gives it a second callsign.** Revoke the old one in - Deploy App. - **Replacing a team's certificate template locks its phones out.** Every phone deletes the certificate it has and asks again, and the deployment refuses a name that is already taken. So this repository never replaces one to retry a phone: ``resend`` asks for that phone alone. - **A refusal shows only as** ``SCEP enrollment failed ... failInfo: badMessageCheck`` on the - phone's certificate. Usually a bad or taken name, or Fleet still has the previous window's - challenge. A taken name is never freed, not even by revoking it, so give the phone another with - ``name``. For the challenge, ``challenge`` and then ``resend``. + phone's certificate. For the causes see `Enrolling phones`_; for an old challenge, ``challenge`` + and then ``resend``. + +By hand in Fleet +~~~~~~~~~~~~~~~~ + +Without the connector, in Fleet's console: open the phone, **Edit user** to give it its callsign, +then under **OS settings** pick the certificate and **Resend**. Naming alone does not send the +request again. Once the phones have enrolled and their apps have arrived, delete the policy in +Fleet and upload it again: Fleet can overwrite a new phone's policy, see `The order that works`_. + +Phones already enrolled in another Fleet team: transfer them into this team in Fleet, then name +them like the rest. Apps install only at enrolment, so a transferred phone gets its certificate but +not this team's apps or launcher. For those, remove its work profile after the transfer and enrol +it again into this team. Write a plugin -------------- From 2621c44e9c09a15c68c81f6f7d71217d3b36792c Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 01:59:31 +0200 Subject: [PATCH 103/104] docs: the page, the files, the commands and the plugin contract as the code has them --- README.rst | 470 +++++++++++++++++++++++++++++------------------------ 1 file changed, 259 insertions(+), 211 deletions(-) diff --git a/README.rst b/README.rst index 7617bb5..32f8999 100644 --- a/README.rst +++ b/README.rst @@ -75,9 +75,11 @@ installed too:: uv tool install git+https://github.com/pvarki/python-odmdm-fleet odmdm-connector --help -From a checkout, ``uv tool install .`` does the same. Installed this way it brings its one -dependency, keyring, which keeps the MDM token in this computer's keychain: Windows Credential -Manager, the macOS Keychain, or the Secret Service on Linux. +The repository is named after Fleet, the first MDM the connector served. From a checkout, +``uv tool install .`` does the same. Installed this way it brings its one dependency, keyring, +which keeps the MDM token in this computer's keychain: Windows Credential Manager, the macOS +Keychain, or the Secret Service on Linux. Fleet is built in; for another MDM add its plugin in the +same line (`Plugins`_). The page -------- @@ -86,68 +88,80 @@ The connector's everyday face is a page in your browser, served by this computer odmdm-connector web -or ``odmdm-connector`` alone, as a double-click on a downloaded file does (see `A file to download`_). -It opens the page in your default browser and prints its address, and goes on until Ctrl+C. -``--port N`` serves it on another port than 8737. The browser does not open by itself on a computer -without a desktop, with ``--no-browser``, or when the default browser may not read the connector's -own folder, as a browser installed as a snap on Linux cannot: then open the address it prints -yourself. On a Mac whose ``.html`` files open in another program than the browser, the connector's -file may open there instead; on Linux without a graphical opener, a text browser may take the -terminal. In both cases start it with ``--no-browser`` and open the printed address. A page opened -without that address says so, and goes on by itself once the address has been opened in the same -browser. Deploy App's button finds the page only in the browser where the -address was opened, so use Deploy App in your default browser, or open the address in the browser -you use Deploy App in. +or ``odmdm-connector`` alone, as a double-click on a downloaded file does (see `A file to +download`_). It asks your default browser to open the page, prints its address, and goes on until +Ctrl+C. ``odmdm-connector web --port N`` serves it on another port than 8737. Deploy App's **Open +in the MDM connector** reaches port 8737 only, so on another port paste the settings line (`The +settings line`_) into the page instead. + +On a computer without a desktop, or with ``odmdm-connector web --no-browser``, the connector only +prints the address. If the page does not appear, or another program opens, open the printed +address yourself. That can happen with a browser installed as a snap on Linux, which may not read +the connector's own folder, on a Mac whose ``.html`` files open in another program than the +browser, and on Linux without a graphical browser, where a text browser may take the terminal: use +``--no-browser`` there. A page opened without that address says so, and goes on by itself once the +address has been opened in the same browser. Deploy App's button finds the page only in the +browser where the address was opened, so use Deploy App in your default browser, or open the +address in the browser you use Deploy App in. The first time, the page sets up one thing at a time, on cards under a bar of three parts: Deploy -App, the MDM, Connect. Have at hand Deploy App's MDM page, open as an admin, your MDM's address and -an API token for it. Add the Deploy App: on its MDM page press **Open in the MDM connector**, or -copy its settings line and paste it into the page, and confirm it. Choose the MDM when more than one -is installed, then fill in what it asks, one field to a card: for Fleet its address, an API token -and the team, which it suggests naming after the deployment (``golden-monkey DeployApp`` for -golden-monkey.example.fi), with the rarely changed ones under **More settings**. **Connect** sets the MDM up and -ticks off its steps; it says what is left to do by hand, if anything, or why it failed, and **Show -the phones** goes on. +App, the MDM, Connect. Have at hand Deploy App's MDM page, open as an admin, and what your MDM +asks for. Add the Deploy App: on its MDM page press **Open in the MDM connector**, or copy its +settings line and paste it into the page, and confirm it. Choose the MDM when more than one is +installed; a plugin is asked about first, and used only once you agree, for that package and +version. Then fill in what the MDM asks, one field to a card, with the rarely changed ones under +**More settings**: for Fleet its address, an API token and the team, which the page suggests +naming after the deployment (``golden-monkey DeployApp`` for golden-monkey.example.fi). +**Connect** sets the MDM up and ticks off its steps; it says what is left to do by hand, if +anything, and **Show the phones** goes on. If it failed it says why, and **Change the settings** +goes back. The daily work is one view of the phones, as wide as the window. At the top, whether Deploy App -accepts phones now and until when; once enrolment has closed, **Open Deploy App** opens its MDM page -in a new tab. Under it one row of buttons, the ways to select, and the table: each phone's ID, -callsign, model, when it joined and where its certificate is. Click a row to select it, and -double-click it, or select one and press **Details**, to see that phone alone. The line at the -bottom says what was done last and, at its right end, when the phones were last listed: every -minute while the page is open, or at once with **Refresh**. **Settings** shows the MDM's -settings, whether its token is kept on this computer, and where the log is, and offers **Send the -policy again** for a phone whose browser refuses its certificate (see `The order that works`_): it -ticks off its steps as **Connect** does, and the phones keep their certificates and apps. The Deploy App's name -at the top right lists the Deploy Apps added, opens another, adds one or removes the one open. -One Fleet can serve several Deploy Apps. Each has a certificate authority of its own in Fleet and -a team of its own; the connector never points an authority that serves one Deploy App at another, -and refuses a team whose certificate template takes its certificates from another address (see -`The template`_). A challenge goes only to the authority the team's template is bound to. -The API token is a global admin's, so whoever runs the connector for one Deploy App can change -every team in that Fleet: share a Fleet only among people who trust each other with it. +accepts phones now and until when; once enrolment has closed, or when no opening is known, +**Open Deploy App** opens its MDM page in a new tab. Under it one row of buttons, the ways to +select, and the table: each phone's ID, callsign, model, when it joined and where its certificate +is. Click a row to select it, and double-click it, or select one and press **Details**, to see +that phone alone. The line at the bottom says what was done last and, at its right end, when the +phones were last listed: every minute while the page is open in a visible tab, or at once with +**Refresh**. **Settings** shows the MDM's settings, whether its token is kept on this computer, +and where the log is. For an MDM that can send its policy again, as Fleet can, it also offers +**Send the policy again** (see `The order that works`_): it ticks off its steps as **Connect** +does, and the phones keep their certificates and apps. The Deploy App's name at the top right +lists the Deploy Apps added, opens another, adds one or removes the one open. Each is a +connection of its own, with its own settings and its own token. For every batch: open enrolment in Deploy App and press **Open in the MDM connector** again, or -**New settings** and paste the line, so the MDM gets the new challenge. Let the phones enrol, then -**Give callsigns**, to the phones selected or else to every phone waiting for a name: numbered or -from a list. The preview below follows what you type, and **Name** names exactly the preview -shown, once it has passed. **Ask again** asks refused or failed phones for their certificates -again once the cause is fixed. +**New settings** and paste the line, then **Use the new settings** on the card that follows: only +then does the MDM get the new challenge. An MDM that cannot take it by API gets it by hand: the +page then shows the challenge to copy into the MDM. Let the phones +enrol, then **Give callsigns**, to the phones selected or else to every phone waiting for a name: +numbered or from a list. The preview below follows what you type, and the button, which then +reads **Name 3 phones**, names exactly the phones the preview shows, once it has passed. **Ask +again**, where the MDM can ask, asks refused or failed phones for their certificates again once +the cause is fixed. The MDM token is never in the settings file, the log or the page. With **Remember on this -computer** ticked, as it is at first, it is kept in this computer's keychain, under -``odmdm-connector``, and the page connects to the MDM at the next start without asking for it. -Without a keychain, as in the one file, the page says the token is kept only until the connector +computer** ticked, as it is each time its card is shown, it is kept in this computer's keychain, +under ``odmdm-connector``, and the page connects to the MDM at the next start without asking for +it. Without a keychain, as in the one file for Python (`Into a network without internet`_) or on +Linux where no Secret Service runs, the page says the token is kept only until the connector stops, and asks for it after a restart: then it shows the phones of the MDM set up before, without new settings from Deploy App. It asks for it the same way, with the MDM's reason, when the MDM no longer accepts it, and removes the copy kept. -To stop keeping the token on this computer, connect again with **Remember on this computer** -unticked, or remove the Deploy App: either removes it from the keychain. If the keychain does not -let it be removed, the page says so: delete the ``odmdm-connector`` item of that Deploy App there by -hand. +To stop keeping the token on this computer, go through the MDM's settings again (**Settings**, +then **Change the Fleet settings**, or your MDM's name in Fleet's place), untick **Remember on +this computer** on the token's card and press **Connect**; or remove the Deploy App. Either +removes it from the keychain. If removing the Deploy App cannot remove it from the keychain, the +page says so: delete the ``odmdm-connector`` item of that Deploy App there by hand. + +The connector keeps what you set on the page, never the token or the challenge, in +``settings.json`` in its own folder, beside its log: ``%LOCALAPPDATA%\odmdm-connector`` on +Windows, ``~/Library/Application Support/odmdm-connector`` on macOS, ``~/.config/odmdm-connector`` +on Linux (or under ``XDG_CONFIG_HOME``). -What guards the page: +How the page is guarded +----------------------- - It listens on this computer only (127.0.0.1), and answers only a request addressed to this computer (its Host header), so that a web page elsewhere cannot reach it through DNS rebinding. @@ -155,15 +169,17 @@ What guards the page: address printed at start holds, new at every start. The key is in the address's fragment, after ``#``, which a browser sends to no server. The page takes it out of the address, keeps it only once the connector accepts it, so that a page elsewhere cannot put a wrong one in its place, and - sends it with each request in a header of its own, never in a cookie, which a browser would also send to every - other program listening on this computer. + sends it with each request in a header of its own, never in a cookie, which a browser would also + send to every other program listening on this computer. - The address is never on another program's command line, where other users of the computer could read it: to open the browser, the connector writes a small file that leads on to it into its own - folder, which only you can read, and the browser gets the address through that file. The file - holds the key while the connector runs and is removed when it stops. + folder, readable by you alone on Linux and macOS and inside your own profile on Windows, and the + browser gets the address through that file. The file is removed when the connector stops; one + left behind by a connector that was killed holds a key that no longer works, and the next start + replaces it. - The browser keeps exactly one thing, that key, in the page's own storage, so that every tab of - the page has it. It is worthless once the connector stops. Nothing else is ever kept there. The - browser's history also keeps the address you opened, key and all; that matters only while the + the page has it. It is worthless once the connector stops. Nothing else is ever kept there. A + browser's history may also keep the address you opened, key and all; that matters only while the connector runs, as the next start makes a new key. - A request that changes something must come from the page itself (its Origin header). - **Open in the MDM connector** opens the page and hands it the settings line in a message, never in @@ -177,7 +193,7 @@ Its limits: line by hand instead. A program that listens on port 8737 while the connector is not running can also send the Deploy App tab that opened it elsewhere. - Any web page can open the connector and offer a Deploy App of its own: read the Deploy App's name - on the confirm card before pressing **Add**. + on the confirm card before pressing the button that adds it. - Another program on this computer can slow the page down, but without the key it can neither read nor drive it. A program that runs as you can read the key from your browser's storage, as it can read anything else of yours. @@ -186,21 +202,44 @@ A file to download ------------------ For an operator who has no Python, the connector is also one self-contained file per system, which -Deploy App's MDM page offers for download when a deployment serves them: Python, the connector, -Fleet and keyring are inside, so the token can be kept in the keychain. Started without a command, -as by a double-click, it opens the page; every command works as above. Started so again while the -page runs, it says the connector may be running already and, in a terminal window, waits for Enter -before the window closes. Each system has its own -file: ``odmdm-connector--windows-x64.exe`` as it is, and for macOS and Linux one -executable named ``odmdm-connector`` in a ``.zip`` or ``.tar.gz``, which keeps it executable through -a browser's download. Beside them, ``connector.json`` says the version, the MDMs built in, and each -file's system, size and SHA-256; Deploy App's page reads it. - -The files are NOT SIGNED yet, so the system warns at the first start. On macOS it refuses to open -the file: open **System Settings**, **Privacy & Security**, and press **Open Anyway** for +Deploy App's MDM page offers for download when the deployment serves them. Python, the connector, +the MDM built in (Fleet) and keyring are inside, so the token can be kept in the keychain. A +plugin cannot be added to these files: for another MDM, install the connector with uv, or build +the one file for Python with the plugin inside (`Into a network without internet`_). + +Started without a command, as by a double-click, the file opens the page; every command works as +above. Started so again while the page runs, it says the connector may be running already and, in +a terminal window, waits for Enter before the window closes. + +Each release has four such files and one for Python, in one archive (`Building and serving the +files`_): + +- ``odmdm-connector--windows-x64.exe``, as it is; +- ``odmdm-connector--macos-arm64.zip`` for a Mac with Apple Silicon and + ``odmdm-connector--macos-x64.zip`` for one with Intel; +- ``odmdm-connector--linux-x64.tar.gz``, which needs glibc 2.28 or newer; +- ``odmdm-connector-.pyz``, for any system with Python 3.11 or newer: without keyring, + so without a keychain (`Into a network without internet`_). + +The ``.zip`` and ``.tar.gz`` hold one executable named ``odmdm-connector``, and keep it executable +through a browser's download. Beside them, ``connector.json`` says the version, the MDMs built in, +and each file's system, size and SHA-256; Deploy App's page reads it. No file is built for Linux +or Windows on ARM: use the one for Python there, or install with uv (`Install`_). + +The files are NOT SIGNED yet, so Windows and macOS warn at the first start. On macOS it refuses to +open the file: open **System Settings**, **Privacy & Security**, and press **Open Anyway** for ``odmdm-connector``. On Windows, SmartScreen says it protected the PC: press **More info**, then -**Run anyway**. Before doing either, compare the file's SHA-256 with its line in the release's -``SHA256SUMS`` (below). +**Run anyway**; a computer that offers no **Run anyway** does not run unsigned files at all. +Before doing either, compare the file's SHA-256 with its line in the release's ``SHA256SUMS``: +Deploy App's page shows the same SHA-256 beside the download. With the file and ``SHA256SUMS`` in +one folder:: + + sha256sum -c --ignore-missing SHA256SUMS # Linux + shasum -a 256 -c --ignore-missing SHA256SUMS # macOS + Get-FileHash odmdm-connector-*.exe -Algorithm SHA256 # Windows PowerShell: compare by eye + +Building and serving the files +------------------------------ Build the file for the computer you are on from a checkout, with PyInstaller, a build tool kept in a dependency group of its own. ``packaging/build.py`` holds the build and is what CI runs:: @@ -208,11 +247,10 @@ a dependency group of its own. ``packaging/build.py`` holds the build and is wha uv run --locked --group dist python packaging/build.py It writes the packed file into ``dist/mdm-connector``. CI builds it on Windows, macOS (Apple -Silicon and Intel) and Linux, starts each, adds the one file for Python below, and writes the -manifest into that folder with ``uv run python packaging/manifest.py dist/mdm-connector``: the -artifact ``mdm-connector`` is the folder a deployment serves. The Linux file needs glibc 2.28 or -newer: CI builds it in AlmaLinux 8 (glibc 2.28) and starts it there, the keychain included, and in -Debian 11. +Silicon and Intel) and Linux, starts each, adds the one file for Python, and writes the manifest +into that folder with ``uv run python packaging/manifest.py dist/mdm-connector``: the artifact +``mdm-connector`` is the folder a deployment serves. CI builds the Linux file in AlmaLinux 8 +(glibc 2.28) and starts it there, the keychain included, and in Debian 11. Each release carries that folder, built from the release's tag, as one archive that unpacks to ``mdm-connector/``, the archive's SHA-256 beside it, and ``SHA256SUMS``, one line per file of the @@ -223,7 +261,7 @@ folder (``connector.json`` aside), all in the form ``sha256sum -c`` reads:: https://github.com/pvarki/python-odmdm-fleet/releases/download/v/SHA256SUMS The ``+`` in the version is written ``%2B`` in the address, as GitHub writes it: the tag of -1.3.0+261122 is ``v1.3.0%2B261122`` there. Check an archive before unpacking it:: +1.5.0+261122 is ``v1.5.0%2B261122`` there. Check an archive before unpacking it:: sha256sum -c mdm-connector.tar.gz.sha256 tar -xzf mdm-connector.tar.gz @@ -231,16 +269,15 @@ The ``+`` in the version is written ``%2B`` in the address, as GitHub writes it: Deploy App's UI image fetches the archive of one release, pins its SHA-256 and serves the folder beside the app: an image refuses to build from an archive with any other SHA-256. A release's assets are never replaced, so the SHA-256 the MDM page shows for a file is the line for that file in -the release's ``SHA256SUMS``. Check a downloaded file in its folder before the first start:: - - sha256sum -c --ignore-missing SHA256SUMS +the release's ``SHA256SUMS``. Into a network without internet ------------------------------- -The connector runs on Python's standard library alone, so it can be carried in as one file. On the -other computer it needs Python 3.11 or newer, and nothing else. The file leaves keyring out, so it -has no keychain: the MDM token is asked for at each start, and kept only until the connector stops. +The connector can be carried in as one file, which needs nothing but Python 3.11 or newer on the +other computer. The file leaves out the connector's one dependency, keyring, and the connector +runs without it: it has no keychain, so the page asks for the MDM token at each start and keeps +it only until the connector stops. The commands read the token from its file, as always. Build the file from a checkout, on a computer that has uv. The wheel goes into the file whole, with its metadata, which is how the connector finds Fleet and any plugin:: @@ -250,120 +287,112 @@ its metadata, which is how the connector finds Fleet and any plugin:: python3 -m zipapp build/pyz -m "odmdm_connector.console:odmdm_connector_cli" -p "/usr/bin/env python3" -o dist/odmdm-connector.pyz A plugin goes into the same file: build its wheel and name it in the same install line, after the -connector's. Start from an empty ``build/pyz`` each time, or what was installed there before stays in -the file. +connector's. Its own dependencies are not installed, so a plugin for this file has to run on the +standard library. Start from an empty ``build/pyz`` each time, or what was installed there before +stays in the file. -Copy ``dist/odmdm-connector.pyz`` across and run it as the command, ``py`` in place of ``python3`` on -Windows:: +Copy ``dist/odmdm-connector.pyz`` across and run it as the command, ``py`` in place of ``python3`` +on Windows:: python3 odmdm-connector.pyz --version python3 odmdm-connector.pyz mdms python3 odmdm-connector.pyz web -An MDM whose certificate comes from a private authority is trusted by pointing the -``SSL_CERT_FILE`` environment variable at that authority's certificate file, in PEM form, before -the connector starts. - Enrolling phones ---------------- -One Fleet team, the one with the certificate template. Phones enrol into it before anybody names -them, and each gets its certificate once it has a name. +The same work as on the page, by command. Phones enrol into the MDM's group for this Deploy App +before anybody names them, and each gets its certificate once it has a name. First set +``ODMDM_MDM`` to your MDM's name unless it is Fleet (``odmdm-connector mdms`` lists the names), +``ODMDM_DOMAIN`` to the deployment's DNS name, and what your MDM needs (`Configuration`_). -1. Once per deployment, and whenever the template changes:: +1. Once per deployment, and whenever what the phones need changes. The first time, open enrolment + first, as in step 2, and give that opening's settings line in ``ODMDM_CHALLENGE``: ``apply`` + then hands the MDM that challenge too, and ``challenge`` is for the openings after it:: odmdm-connector apply -2. Open enrolment in Deploy App (**User management → MDM**), copy its settings line or its - challenge, and give Fleet the new challenge. It asks for it, and changes nothing else:: +2. Open enrolment on Deploy App's MDM page (**User Management**, then **MDM**), copy its settings + line or its challenge, and give the MDM the new challenge. The command asks for it, and + changes nothing else:: odmdm-connector challenge -3. Enrol phones into the team, `` DeployApp`` by default, as many as you like, in - any order. Name them once every phone in the team has its apps: naming can send the policy to all of them again. +3. Enrol phones into that group in your MDM, as many as you like, in any order. -4. Name them, all at once or a few at a time:: +4. Name them, all at once or a few at a time; with Fleet, only once every phone has its apps + (`The order that works`_):: odmdm-connector name --all OTTER # OTTER1, OTTER2, ... in the order they enrolled - odmdm-connector name 31=OTTER4 32=OTTER5 # host id = callsign, the ids being what phones prints + odmdm-connector name 31=OTTER4 32=OTTER5 # the MDM's id of a phone = callsign, the ids being what phones prints - Each phone gets its certificate at its next check-in, within about 15 minutes, and greets its - callsign in Deploy App. ``phones`` shows where each one is. ``resend`` asks again for a refused - phone once the cause is fixed. + Each phone gets its certificate when it next asks its MDM. ``phones`` shows where each one is. + ``resend`` asks again for a refused phone once the cause is fixed. Close enrolment once ``phones`` says every phone has its certificate: a request that arrives after it closes is refused. The next opening makes a new challenge, so step 2 comes again before the next batch. -Without this tool, in Fleet: open the phone, **Edit user** to give it its callsign, then under -**OS settings** pick the certificate and **Resend**. Naming alone does not send the request again. -Once the phones have enrolled and their apps have arrived, delete the policy in Fleet and upload -it again: Fleet can overwrite a new phone's policy, see `The order that works`_. +A refusal is usually a callsign that is malformed or taken, an enrolment window that has closed, +or an MDM that still has the previous opening's challenge. A callsign is never freed, not even by +removing it in Deploy App: give the phone another. A phone that is renamed after it got its +certificate has two callsigns until the old one is removed in Deploy App, which revokes it; the +connector says which. -Phones already enrolled in another Fleet team: transfer them into this team in Fleet, then name -them like the rest. Apps install only at enrolment, so a transferred phone gets its certificate but -not this team's apps or launcher. For those, remove its work profile after the transfer and enrol -it again into this team; see `The order that works`_. +A command the MDM cannot do by API says what to do in the MDM instead, and changes nothing. +`Fleet`_ has Fleet's timing, its team and the same work done by hand in Fleet. Commands -------- .. code-block:: bash - odmdm-connector apply # state what devices need; --force-policy sends the policy again - odmdm-connector apply --dry-run # validate the template without touching Fleet - odmdm-connector challenge # give Fleet a new window's challenge, nothing else - odmdm-connector phones # each phone's host id, callsign, model and certificate - odmdm-connector name 31=OTTER4 32=OTTER5 # name these phones, and Fleet sends their certificates + odmdm-connector # the page, as web + odmdm-connector web # the page on this computer; --port N, --no-browser + odmdm-connector apply # state what the phones need; --force-policy sends the policy again + odmdm-connector apply --dry-run # read and check what would be stated, without touching the MDM + odmdm-connector challenge # give the MDM a new opening's challenge, nothing else + odmdm-connector phones # each phone's id, callsign, model, enrolment day and certificate + odmdm-connector name 31=OTTER4 32=OTTER5 # name these phones, and their certificates are asked for odmdm-connector name --all OTTER # the same for every phone without a name, numbered - odmdm-connector resend [HOST_ID ...] # ask again; without ids, every named phone that failed + odmdm-connector resend [ID ...] # ask again; without ids, every named phone that failed odmdm-connector mdms # the MDMs installed: fleet built in, and any plugins -``name --all`` numbers in enrolment order from one above the highest ``OTTER`` in the team, or -from ``--start N``, 1 or more. It sees only this team's phones, and Deploy App never gives a -callsign out twice: where callsigns were used by phones no longer in the team, give ``--start`` -above the highest ever used. ``name`` changes nothing at all if a callsign is malformed, given twice or -already another phone's, or if a phone is not in the team. A phone that already has its certificate -under the name is left alone. Renaming a phone that has its certificate says which old callsign to -revoke. +``name --all`` numbers in enrolment order from one above the highest ``OTTER`` among the +phones it sees, or from ``--start N``, 1 or more. It sees only this group's phones, and Deploy App +never gives a callsign out twice: where callsigns were used by phones no longer in the group, give +``--start`` above the highest ever used. ``name`` changes nothing at all if a callsign is +malformed, given twice or already another phone's, or if a phone is not in the group. Configuration ------------- -All configuration is via environment variables. ``--set KEY=VALUE`` before the command sets one -of the MDM's own for one run, ``mdm_url``, ``team``, ``template`` or ``key_alias`` for Fleet, as -does ``--mdm-url``, ``--team`` or ``--template`` after it. A secret, the token, is only ever read -from the file its ``_FILE`` variable names: - -``ODMDM_MDM_URL`` - Base URL of Fleet's API. Only https: the token goes with every request. +The commands are configured by environment variables, which options override for one run. The +page keeps its own settings instead (`The page`_). -``ODMDM_TOKEN_FILE`` - A file holding the Fleet API token. Changing the certificate authority's challenge needs a - global admin token, because Fleet keeps certificate authorities outside teams. - Keep the file outside this checkout, readable only by you: the token can change every - enrolled phone. The tool reads it and never prints, logs or writes it. - -``ODMDM_TEAM`` - The team phones enrol into and get the certificate in. Default `` DeployApp``, the - deployment being the first label of ``--domain`` or ``ODMDM_DOMAIN``: ``golden-monkey DeployApp`` - for golden-monkey.example.fi. Without either, give the team. A deployment set up with the - earlier default keeps its team only when it is given: ``--team "Deploy App"``. - -``ODMDM_TEMPLATE`` - The document saying what to install, see below. Default: the one shipped with the connector. +``ODMDM_MDM`` + Which MDM to talk to, as ``--mdm NAME`` before the command. Default ``fleet``; ``mdms`` lists + the names. ``ODMDM_DOMAIN`` - The deployment's DNS name. + The deployment's DNS name, as ``--domain`` after ``apply`` and ``challenge``. ``ODMDM_CHALLENGE`` The settings line or the bare challenge from Deploy App's MDM page, for ``challenge`` and a - first ``apply``. New for every enrolment window. + first ``apply``. New for every enrolment window. Without it, ``challenge`` asks at a hidden + prompt. It is never taken as an argument. -``ODMDM_KEY_ALIAS`` - The certificate template's name, which becomes the Android keystore alias. Default ``rmscep``, - what the first deployments were set up with. Never change it for a deployment: a second key - will not install over an existing alias. +``ODMDM_LOG_LEVEL`` + How much the commands log to stderr, as a whole number: 20 by default, 10 for more. For one + run, ``-vv`` before the command says 10 and ``-v`` 20. The page's own log is always at 20. + +Each MDM has settings of its own, which its plugin names. A setting ```` is read from +``ODMDM_``, or given for one run with ``--set =VALUE`` before the command; a command +says which one is missing. A secret, such as a token, is only ever read from the file that +``ODMDM__FILE`` names. Keep that file outside any checkout, readable only by you: the token +can change every enrolled phone. The tool reads it and never prints, logs or writes it. A default +may name the deployment, the first part of ``ODMDM_DOMAIN`` in lower case. Fleet's settings are +under `Fleet`_. The settings line ----------------- @@ -375,42 +404,52 @@ separated by whitespace:: ODMDM1 https://unit.example.fi/scep 0123456789abcdef0123456789abcdef 2026-11-21T14:00:00Z 1. The mark ``ODMDM1``. -2. The SCEP URL, ``https:///`` and nothing else: no user name, password, port, query, - fragment or backslash. Deploy App writes ``https:///scep``. -3. The challenge: 32 lowercase hex characters. It is a secret, and the tool never prints or logs it. +2. The SCEP URL, ``https:///`` with a plain DNS host name, and nothing else: no user + name, password, port, query, fragment or backslash. Deploy App writes ``https:///scep``. +3. The challenge: 32 lowercase hex characters. It is a secret: the tool never logs it and never + prints it on the command line. For an MDM that cannot take it by API, the page shows it for + you to copy into that MDM. 4. When the enrolment window closes, in UTC, as ``YYYY-MM-DDTHH:MM:SSZ``. Whitespace and line breaks before and after the line are ignored. A line with another mark or another number of fields, a URL that is not just https, a host and a path, a malformed challenge or time, or a window that has already closed is refused. A line that a page hands to the connector is taken only from that Deploy App's own pages, ``https://`` or ``https://mtls.``; one -typed or pasted by hand names no page. A value with whitespace inside it is read as a line, never -as a bare challenge, so a damaged paste is refused instead of being sent to Fleet. ``challenge`` -takes the line from ``ODMDM_CHALLENGE``, else at its hidden prompt, never as an argument; it refuses -one whose SCEP URL is not on ``ODMDM_DOMAIN``, and says until when the window is open, in this -computer's time. The line above is the shared test vector, in ``tests/data/settings-line-v1.txt``. +typed or pasted by hand names no page. The page takes only a whole line. The commands ``apply`` +and ``challenge`` also take a bare challenge, one word, as typed, for ``https:///scep``; +it says nothing of when the window closes. They read a value with whitespace inside it as a line, +never as a bare challenge, so a damaged paste is refused instead of being sent to the MDM, and +they refuse a line whose SCEP URL is not on ``ODMDM_DOMAIN``. ``challenge`` says until when the +window is open, in this computer's time. The line above is the shared test +vector, in ``tests/data/settings-line-v1.txt``; its window closed long ago, so the connector +refuses it as it is. Plugins ------- -Fleet is built in. Another MDM comes as a plugin: a Python package of its own, named -``odmdm-connector-``, that the connector finds once it is installed beside it. A plugin is -code that sees the MDM token, so installing one means trusting it as much as the connector -itself. Install only one you know the source of. When the MDM chosen is a plugin, every command -says on stderr which package and version it comes from. +Fleet is built in. Another MDM comes as a plugin: a Python package of its own, by convention named +``odmdm-connector-``, that the connector finds through its entry point once it is installed +in the same environment. A plugin is code that sees the MDM token, so installing one means +trusting it as much as the connector itself. Install only one you know the source of. The page +asks before it uses a plugin, once for each package and version, and the commands that use the +MDM say on stderr which package and version it comes from. + +Add one with the same install line and ``--with`` and the plugin's package: its name if it is on a +package index, else its wheel file or its ``git+https://`` address:: -Add one with the same install line and ``--with``:: + uv tool install git+https://github.com/pvarki/python-odmdm-fleet --with - uv tool install git+https://github.com/pvarki/python-odmdm-fleet --with odmdm-connector- +Into a network without internet a plugin goes inside the one file for Python (`Into a network +without internet`_). See what is installed, without loading any of it:: odmdm-connector mdms -Choose one with ``--mdm NAME`` before the command, or ``ODMDM_MDM``; the default is ``fleet``. -Its settings are given as for Fleet: ``--set KEY=VALUE``, or ``ODMDM_``, and a secret only -from the file ``ODMDM__FILE`` names. A plugin's MDM may lack something Fleet can do, such as -taking the challenge by API; the command then says what to do instead and changes nothing. +Choose one with ``--mdm NAME`` before the command, or ``ODMDM_MDM``; the default is ``fleet``. Its +settings are given as `Configuration`_ says. A plugin's MDM may lack something Fleet can do, such +as taking the challenge by API; the command or the page then says what to do instead and changes +nothing. To write one, see `Write a plugin`_. Fleet ----- @@ -598,62 +637,71 @@ it again into this team. Write a plugin -------------- -An MDM fits if it can do five things: +A plugin makes an MDM that can do what `What an MDM needs`_ lists work with the connector. It is +one class that satisfies ``Mdm`` in ``src/odmdm_connector/mdm.py``, which is standard library +only: -1. Keep one Deploy App's phones in a group of its own, with its own enrolment. -2. Send each phone's certificate request to Deploy App's SCEP URL with one static challenge, the - same for every phone. -3. Put a value that its API can set for each phone into the certificate subject: the callsign, as - the common name. -4. Take a new challenge for each enrolment window, by API or by hand. -5. Ask one phone for its certificate again and leave the others alone. - -A plugin is one class that satisfies ``Mdm`` in ``src/odmdm_connector/mdm.py``, which is standard -library only: - -- ``API_VERSION = 1``, a ``title``, the ``fields`` it needs (each a ``Field``; mark a token +- Its class attributes are ``API_VERSION = 1``, a ``title``, the ``fields`` it needs and + ``missing``; a class without them is not used. Each field is a ``Field``: mark a token ``secret``, one that must be given ``required``, and one rarely changed ``advanced``, which the - window shows only when asked) and ``missing``: for each of ``setup``, - ``set_challenge``, ``ask_again`` and ``send_policy`` it cannot do, the sentence the operator reads - instead. A default may hold ``{deployment}``, which the connector fills in with the deployment's - name, the first label of the Deploy App's host: ``{deployment} DeployApp`` is Fleet's team. -- ``__init__(values)`` takes the fields' values by key. -- ``setup(window, force, dry_run)`` yields ``Step`` objects, ``force`` sending the policy again - even if unchanged, unless ``send_policy`` is missing; ``set_challenge(window)``; ``phones()`` - answers ``Phone`` objects, oldest first, each with a ``State``; ``name(names)`` and ``ask_again(ids)`` - answer the lines to show. + page shows only under **More settings**. A field's ``key``, in lower case, is its setting: + ``--set key=VALUE``, ``ODMDM_`` in capitals, and ``ODMDM__FILE`` for a secret. A + default may hold ``{deployment}``, which the connector fills in with the deployment's name, the + first label of the Deploy App's host: ``{deployment} DeployApp`` is Fleet's team. Without a + host there is no such default, so make that field ``required``. +- ``missing`` holds, for each of ``setup``, ``set_challenge``, ``ask_again`` and ``send_policy`` + the MDM cannot do, the sentence the operator reads instead; it is an empty mapping when the MDM + can do them all. The connector never calls what is listed there; called anyway, it raises + ``MdmError`` with that sentence, ``send_policy`` being ``setup`` with ``force``. +- ``__init__(values)`` takes the fields' values by key. It does not call the MDM: on a dry run a + required value may still be empty. +- ``setup(window, force, dry_run)`` yields ``Step`` objects, one whose ``done`` is false being a + step left to the operator; ``force`` sends the policy again even if unchanged. + ``set_challenge(window)`` gives the MDM a new challenge and changes nothing else. ``window`` is + the enrolment window: its SCEP URL, its challenge, and when it closes. In ``setup`` the + challenge is empty on a dry run, when none was given and when only the policy is sent again: + the MDM's own is then left as it is. +- ``phones()`` answers ``Phone`` objects, oldest first, each with a ``State``. ``name(names)`` + takes callsigns by phone id, and ``ask_again(ids)`` phone ids, none meaning every named phone + whose certificate failed or was not asked for. Both answer the lines to show, and raise + ``MdmError`` for an id that is not in the group. - It raises only ``MdmError``. One that stops half-way through ``name`` says in ``named`` which phones it had already named, and in ``lines`` the lines already due to the operator, such as an - old callsign to revoke, which are shown before the error. One raised because the MDM does not - accept the secret it was given, such as a token that has ended, sets ``unauthorized``: the - connector then lets go of that secret, the copy in the keychain too, and asks for it again. -- Its sentences, in ``missing``, a ``Step``, the lines and an ``MdmError``, are shown as they are - by the command line and the window alike, so they name no command, option or button. - -Publish it as ``odmdm-connector-``, depending on ``odmdm-connector>=1.1,<2``, with the class -under the entry point group ``odmdm_connector.mdm``:: + old callsign to remove: the command line prints them before the error, the page lists them + under it. One raised because the MDM does not accept the secret it was given, such as a token + that has ended, sets ``unauthorized``: the page then lets go of that secret, the copy in the + keychain too, and asks for it again. +- Its sentences, in ``missing``, a ``Step``, a ``Phone``'s ``detail``, the lines and an + ``MdmError``, are shown as they are by the command line and the page alike, so they name no + command, option or button, and never hold the challenge or a secret. + +Name the package ``odmdm-connector-``, depending on ``odmdm-connector>=1.4,<2``, the first +release that has everything named above, with the class under the entry point group +``odmdm_connector.mdm``:: [project.entry-points."odmdm_connector.mdm"] = "odmdm_connector_:Mdm" The connector ships a test kit: ``odmdm_connector.testing.contract.CHECKS``, the checks every -plugin must pass given a factory for it, and ``odmdm_connector.testing.FakeMdm``, an MDM in -memory. Start from ``examples/odmdm-connector-demo``: a pretend MDM with three phones that cannot -take a challenge by API, its own ``pyproject.toml`` and its contract test. The repository's CI -builds it and the connector, installs both as above and runs ``odmdm-connector --mdm demo -phones``. +plugin must pass, and ``odmdm_connector.testing.FakeMdm``, an MDM in memory. Each check is given a +factory: a function that answers your MDM, configured, with at least two phones without a name in +its group, and that takes ``refuse_after=N`` to make it refuse to name any phone after N. Start +from ``examples/odmdm-connector-demo``: a pretend MDM with three phones that cannot take a +challenge by API, its own ``pyproject.toml`` and its contract test. The repository's CI builds it +and the connector, installs both and runs ``odmdm-connector --mdm demo phones``. Development ----------- - install uv: https://docs.astral.sh/uv/getting-started/installation/ -- Install project deps and pre-commit hooks:: +- Install project deps and the hooks, for commits and for commit messages:: uv sync - uv run prek install + uv run prek install --hook-type pre-commit --hook-type commit-msg uv run prek run --all-files -- Run the tests:: +- Run the tests. They fail below 88 % coverage, and they fail a test that starts a process: the + connector starts none, and imports only the standard library, keyring in ``store.py`` alone:: uv run pytest @@ -662,6 +710,6 @@ not hand edit the autogenerated section. .. _config-ci-library: https://github.com/pvarki/config-ci-library -Versioning is handled with bump-my-version_: ``bump-my-version bump ``. +Versioning is handled with bump-my-version_: ``uv run bump-my-version bump ``. .. _bump-my-version: https://github.com/callowayproject/bump-my-version From 29e7b847b887db1d1a8b3de80639915913d99c36 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 00:15:19 +0200 Subject: [PATCH 104/104] chore: bump version to 1.5.0+261122 --- .bumpversion.toml | 2 +- pyproject.toml | 2 +- src/odmdm_connector/__init__.py | 2 +- tests/test_odmdm_connector.py | 2 +- uv.lock | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 3ceaea3..7498d30 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.4.0+261122" +current_version = "1.5.0+261122" parse = "(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)\\+(?P\\d+)" serialize = ["{major}.{minor}.{patch}+{build}"] search = "{current_version}" diff --git a/pyproject.toml b/pyproject.toml index a4d4ed5..80e72e5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "1.4.0+261122" +version = "1.5.0+261122" description = "Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment" authors = [ { name = "Benjam", email = "benjam@opendefence.fi" }, diff --git a/src/odmdm_connector/__init__.py b/src/odmdm_connector/__init__.py index 2eb4e4a..ce54fa3 100644 --- a/src/odmdm_connector/__init__.py +++ b/src/odmdm_connector/__init__.py @@ -1,3 +1,3 @@ """Connects an MDM, FleetDM built in, to an OpenDefence deployment's SCEP device enrolment""" -__version__ = "1.4.0+261122" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.5.0+261122" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index e84d3e1..44443ce 100644 --- a/tests/test_odmdm_connector.py +++ b/tests/test_odmdm_connector.py @@ -5,4 +5,4 @@ def test_version() -> None: """Make sure version matches expected""" - assert __version__ == "1.4.0+261122" + assert __version__ == "1.5.0+261122" diff --git a/uv.lock b/uv.lock index 5fb7628..77e9c01 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "1.4.0+261122" +version = "1.5.0+261122" source = { editable = "." } dependencies = [ { name = "keyring" },