From 5f71a54de9806f61448a48f472efa5d41f50d85c Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:18:55 +0200 Subject: [PATCH 1/9] feat(fleet): delete a team's certificate template and an authority it no longer needs --- AGENTS.md | 8 +++ src/odmdm_connector/fleet.py | 63 +++++++++++++++++- tests/test_fleet.py | 124 +++++++++++++++++++++++++++++++++++ 3 files changed, 194 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 07d86cd..fe73ee3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,6 +177,14 @@ A certificate authority is the exception: it is known by the address it serves, 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). +Ending a Deploy App makes the only two deletions there are, `FleetMdm.delete_certificate` and +`delete_authority`, measured on a live Fleet 4.90.1: deleting a team's certificate template is +answered 2xx, and Fleet's console says of it that it removes the certificate from all hosts of the +team; deleting an authority is answered 2xx once no template is bound to it, and 409 with +"Certificate templates still reference it" while one of any team is. An authority is deleted only +after its address is compared with this Deploy App's, and a team whose template is bound to an +authority of another address is left alone: never loosen either. + ## Commands - Setup: `uv sync` diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index f92be4e..d46cad1 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -121,6 +121,9 @@ def _multipart( #: 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" +#: What Fleet says, with a 409, when it keeps an authority because a certificate template is still bound to +#: it (measured against a live Fleet 4.90.1; in its source, server/datastore/mysql/certificate_authorities.go) +IN_USE = "Certificate templates still reference it" def authority_name(scep_url: str) -> str: @@ -470,6 +473,44 @@ def bound_authority(self, team: int, certificate: str) -> int | None: return int(template.get("certificate_authority_id", 0)) return None + def authority(self, authority_id: int) -> tuple[str, str]: + """An authority's name and the address it serves""" + held = self._authority(authority_id) + return str(held.get("name") or ""), str(held.get("url") or "") + + def authority_serving(self, scep_url: str) -> tuple[int, str] | None: + """The custom SCEP proxy that serves scep_url, by its id and name; None when Fleet has none""" + for listed in self._authorities(): + if listed.get("type", "custom_scep_proxy") != "custom_scep_proxy": + continue + authority_id = int(listed["id"]) + if _same_case(self.authority(authority_id)[1]) == _same_case(scep_url): + return authority_id, str(listed.get("name") or "") + return None + + def delete_authority(self, authority_id: int, scep_url: str) -> bool: + """Delete the authority, which must serve scep_url; False when Fleet keeps it, as a template still uses it + + Fleet keeps an authority while any team's certificate template is bound to it, and says so + with a conflict: another team, of this Deploy App or another, still takes its certificates + there. One that serves another address is never deleted: it is another Deploy App's. + """ + name, serves = self.authority(authority_id) + if _same_case(serves) != _same_case(scep_url): + raise FleetError( + f"certificate authority {name} serves {serves or 'another address'}, not {scep_url}, so it was left " + "as it is" + ) + try: + self._call("DELETE", f"/api/latest/fleet/certificate_authorities/{authority_id}") + except FleetError as exc: + if "answered 409" not in str(exc) or IN_USE not in str(exc): + raise + LOGGER.info("Certificate authority %s stays: a certificate template still uses it", name) + return False + LOGGER.info("Deleted certificate authority %s", name) + return True + 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: @@ -581,7 +622,7 @@ def ensure_certificate(self, team: int, name: str, subject: str, authority: int) 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}") + self.delete_certificate(team, int(template["id"])) LOGGER.info("Replacing certificate template %s", name) created = self._call( @@ -633,6 +674,26 @@ def phones(self, team: int, certificate: str) -> list[Phone]: ) return sorted(found, key=lambda phone: (phone.enrolled, phone.id)) + def team_certificate(self, team: int, name: str) -> tuple[int, int] | None: + """The team's certificate template of that name, by its id and its authority's; 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") == name: + return int(template["id"]), int(template.get("certificate_authority_id", 0)) + return None + + def delete_certificate(self, team: int, template_id: int) -> None: + """Delete the team's certificate template: Fleet then has every host that holds its certificate remove it + + Each phone removes it at its next check-in (Fleet 4.90.1's source: DeleteCertificateTemplate + marks it pending removal on every host that has it). + """ + self._call("DELETE", f"/api/latest/fleet/certificates/{template_id}?team_id={team}") + LOGGER.info("Deleted certificate template %s of team %s", template_id, team) + + def host_count(self, team: int) -> int: + """How many devices the team has""" + return len(self._hosts(team)) + 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", []): diff --git a/tests/test_fleet.py b/tests/test_fleet.py index fbf6555..b1374fc 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -144,6 +144,18 @@ def handler(self, request: Request) -> Response: 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 == "DELETE": + # Fleet keeps an authority while a certificate template is bound to it, with a conflict + # in its usual error body (Fleet 4.90.1's source) + which = int(path.rsplit("/", 1)[-1]) + if any(c.get("certificate_authority_id") == which for c in self.certificates): + reason = ( + "Couldn't delete certificate authority. Certificate templates still reference it. " + "Please remove the certificate templates first." + ) + return Response(409, json={"message": "Conflict", "errors": [{"name": "base", "reason": reason}]}) + self.authorities = [a for a in self.authorities if a["id"] != which] + return Response(200, json={}) if "/certificate_authorities/" in path and request.method == "PATCH": which = int(path.rsplit("/", 1)[-1]) body = json.loads(request.content)["custom_scep_proxy"] @@ -763,6 +775,118 @@ def test_without_a_scep_url_a_template_must_name_its_authority(monkeypatch: pyte assert not fleet.calls +def test_a_teams_certificate_template_is_found_by_its_name(monkeypatch: pytest.MonkeyPatch) -> None: + """By its id and the authority it is bound to; a team without one has none""" + fleet = _Fleet() + fleet.certificates = [ + {"id": 80, "name": "other", "team_id": 7, "certificate_authority_id": 4}, + {"id": 81, "name": "rmscep", "team_id": 7, "certificate_authority_id": 3}, + ] + mdm = _mdm(fleet, monkeypatch) + + assert mdm.team_certificate(7, "rmscep") == (81, 3) + assert mdm.team_certificate(8, "rmscep") is None + + +def test_deleting_a_certificate_template_names_its_team(monkeypatch: pytest.MonkeyPatch) -> None: + """Fleet then has every phone that holds its certificate remove it""" + fleet = _Fleet() + fleet.certificates = [{"id": 81, "name": "rmscep", "team_id": 7, "certificate_authority_id": 3}] + seen: list[Request] = [] + + def answer(request: Request) -> Response: + seen.append(request) + return fleet.handler(request) + + _answering(answer, monkeypatch) + FleetMdm("https://mdm.test", "token").delete_certificate(7, 81) + + assert [(r.method, r.url.path, r.url.params) for r in seen] == [ + ("DELETE", "/api/latest/fleet/certificates/81", {"team_id": "7"}) + ] + assert not fleet.certificates + + +def test_the_hosts_of_a_team_are_counted(monkeypatch: pytest.MonkeyPatch) -> None: + fleet = _Fleet() + fleet.hosts = [_host(31), _host(32)] + + assert _mdm(fleet, monkeypatch).host_count(7) == 2 + + +def test_the_authority_serving_an_address_is_found_by_it(monkeypatch: pytest.MonkeyPatch) -> None: + """Its host compared without case; one of another kind, or serving another address, is not it""" + fleet = _Fleet() + fleet.authorities = [ + {"id": 2, "name": "DIGI", "type": "digicert", "url": "https://deployment.test/scep"}, + {"id": 3, "name": "ODMDM_OTHER", "url": "https://other.test/scep"}, + {"id": 4, "name": "ODMDM_DEPLOYMENT", "url": "https://Deployment.TEST/scep"}, + ] + mdm = _mdm(fleet, monkeypatch) + + assert mdm.authority_serving("https://deployment.test/scep") == (4, "ODMDM_DEPLOYMENT") + assert mdm.authority_serving("https://gone.test/scep") is None + assert mdm.authority(3) == ("ODMDM_OTHER", "https://other.test/scep") + + +def test_an_authority_is_deleted_once_no_template_uses_it(monkeypatch: pytest.MonkeyPatch) -> None: + fleet = _Fleet() + + assert _mdm(fleet, monkeypatch).delete_authority(3, "https://deployment.test/scep") + + assert not fleet.authorities + assert ("DELETE", "/api/latest/fleet/certificate_authorities/3") in fleet.calls + + +def test_an_authority_a_template_still_uses_stays(monkeypatch: pytest.MonkeyPatch) -> None: + """Fleet answers a conflict: another team still takes its certificates there""" + fleet = _Fleet() + fleet.certificates = [{"id": 90, "name": "rmscep", "team_id": 8, "certificate_authority_id": 3}] + + assert not _mdm(fleet, monkeypatch).delete_authority(3, "https://deployment.test/scep") + + assert [a["id"] for a in fleet.authorities] == [3] + + +@pytest.mark.parametrize( + ("status", "reason"), + [ + (409, "Locked"), + (500, "Couldn't delete certificate authority. Certificate templates still reference it."), + ], +) +def test_any_other_refusal_to_delete_an_authority_is_a_refusal( + monkeypatch: pytest.MonkeyPatch, status: int, reason: str +) -> None: + """A conflict for another reason, or Fleet's words under another status, is not taken for a template that uses it""" + fleet = _Fleet() + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.method == "DELETE": + return Response(status, json={"message": "Refused", "errors": [{"name": "base", "reason": reason}]}) + return answer(request) + + fleet.handler = refusing # type: ignore[method-assign] + + with pytest.raises(FleetError, match=f"answered {status}"): + _mdm(fleet, monkeypatch).delete_authority(3, "https://deployment.test/scep") + + +def test_an_authority_serving_another_address_is_never_deleted(monkeypatch: pytest.MonkeyPatch) -> None: + """It is another Deploy App's: deleting it would leave that one's phones without an authority""" + fleet = _Fleet() + + with pytest.raises(FleetError) as raised: + _mdm(fleet, monkeypatch).delete_authority(3, "https://golden-monkey.example.fi/scep") + + assert str(raised.value) == ( + "certificate authority RMSCEP serves https://deployment.test/scep, not " + "https://golden-monkey.example.fi/scep, so it was left as it is" + ) + assert not [c for c in fleet.calls if c[0] != "GET"], "nothing changed in Fleet" + + 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 From da21c09b7903442a170a1db8e8eba9be5425cb85 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:20:09 +0200 Subject: [PATCH 2/9] feat(fleet): end a Deploy App in its team, the team and its phones kept --- src/odmdm_connector/fleet.py | 5 + src/odmdm_connector/fleet_plugin.py | 62 +++++++++++- tests/test_fleet_plugin.py | 148 ++++++++++++++++++++++++++++ 3 files changed, 214 insertions(+), 1 deletion(-) diff --git a/src/odmdm_connector/fleet.py b/src/odmdm_connector/fleet.py index d46cad1..e4cd50c 100644 --- a/src/odmdm_connector/fleet.py +++ b/src/odmdm_connector/fleet.py @@ -35,6 +35,11 @@ def _same_case(url: str) -> str: return parts._replace(scheme=parts.scheme.lower(), netloc=parts.netloc.lower()).geturl() +def same_address(one: str, other: str) -> bool: + """Whether two addresses are one, their scheme and host compared without case""" + return _same_case(one) == _same_case(other) + + class FleetError(RuntimeError): """Fleet refused, or answered something we cannot use""" diff --git a/src/odmdm_connector/fleet_plugin.py b/src/odmdm_connector/fleet_plugin.py index d6c60c6..fb9aaff 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, NoTeam, Unauthorized +from .fleet import FleetError, FleetMdm, NoTeam, Unauthorized, same_address from .fleet import Phone as FleetPhone from .mdm import API_VERSION, Field, MdmError, Phone, State, Step from .settings import Settings @@ -262,3 +262,63 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: except FleetError as exc: raise _refused(exc, lines=lines) from exc return lines + + def end(self, window: Settings) -> list[str]: + """Take this Deploy App out of the team: its certificate template, then its authority if no team uses it + + The team, its hosts, its policy, its apps and its launcher stay. The authority is the one + the template was bound to, or with no template left, the one that serves this Deploy App's + address, so that a call which stopped half-way is finished by the next. Fleet keeps an + authority another team's template still uses. A template bound to an authority of another + address is another Deploy App's, and nothing is changed. + """ + api = self._fleet() + lines: list[str] = [] + try: + try: + team = api.team_id(self.team) + except NoTeam as exc: + raise MdmError( + f"Fleet has no team named {self.team}, so nothing was changed. Check the team's name." + ) from exc + found = api.team_certificate(team, self.key_alias) + if found is None: + lines.append( + f"Team {self.team} has no certificate template {self.key_alias}: there was nothing to remove from it." + ) + authority = api.authority_serving(window.scep_url) + else: + template_id, bound = found + name, serves = api.authority(bound) + if not same_address(serves, window.scep_url): + raise MdmError( + f"Team {self.team} takes its certificates from authority {name}, which serves " + f"{serves or 'another address'}, not {window.scep_url}, so nothing was changed. Check the " + "team's name." + ) + phones = api.host_count(team) + api.delete_certificate(team, template_id) + lines.append(_removed(self.key_alias, self.team, phones)) + authority = (bound, name) + if authority is not None: + authority_id, name = authority + if api.delete_authority(authority_id, window.scep_url): + lines.append(f"Certificate authority {name} is removed from Fleet.") + else: + lines.append( + f"Certificate authority {name} stays in Fleet: another team's certificate template still uses it." + ) + lines.append("The team, its phones, their names and their apps stay.") + except FleetError as exc: + raise _refused(exc, lines=lines) from exc + return lines + + +def _removed(alias: str, team: str, phones: int) -> str: + """What removing the team's certificate template does to its phones""" + removed = f"Certificate template {alias} is removed from team {team}" + if not phones: + return f"{removed}, which has no phones." + lose = "its phone loses" if phones == 1 else f"its {phones} phones lose" + their = "its" if phones == 1 else "their" + return f"{removed}: {lose} this Deploy App's certificate at {their} next check-in, {CHECK_IN}." diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py index b90f174..835785f 100644 --- a/tests/test_fleet_plugin.py +++ b/tests/test_fleet_plugin.py @@ -274,3 +274,151 @@ def test_setup_with_force_sends_the_unchanged_policy_again_and_no_challenge(flee assert _policy_uploads(fleet) == before + 1 assert steps[-1].label.startswith("Applied to team rmscep (7): ") assert fleet.authorities[0]["challenge"] == "old" + + +#: The Deploy App the stub's authority serves; ending takes no challenge +ENDED = Settings("https://deployment.test/scep", "") +KEPT = "The team, its phones, their names and their apps stay." + + +def _ending(**values: str) -> FleetPlugin: + """The plugin itself: until the contract has end, an Mdm does not""" + return FleetPlugin({"mdm_url": "https://mdm.test", "token": "token", "team": "rmscep", **values}) + + +def _changes(fleet: _Fleet) -> list[tuple[str, str]]: + return [call for call in fleet.calls if call[0] != "GET"] + + +def test_ending_removes_the_template_and_then_the_authority(fleet: _Fleet) -> None: + """Only those two: the team, its hosts, its policy and its apps stay""" + fleet.hosts = [_host(31, "verified", "OTTER1"), _host(32)] + + lines = _ending().end(ENDED) + + assert lines == [ + ( + "Certificate template rmscep is removed from team rmscep: its 2 phones lose this Deploy App's certificate " + "at their next check-in, up to 15 minutes." + ), + "Certificate authority RMSCEP is removed from Fleet.", + KEPT, + ] + assert _changes(fleet) == [ + ("DELETE", "/api/latest/fleet/certificates/81"), + ("DELETE", "/api/latest/fleet/certificate_authorities/3"), + ] + assert not fleet.certificates and not fleet.authorities + assert [host["id"] for host in fleet.hosts] == [31, 32] and fleet.teams == [{"id": 7, "name": "rmscep"}] + + +@pytest.mark.parametrize( + ("hosts", "said"), + [ + (1, ": its phone loses this Deploy App's certificate at its next check-in, up to 15 minutes."), + (0, ", which has no phones."), + ], +) +def test_ending_says_how_many_phones_lose_the_certificate(fleet: _Fleet, hosts: int, said: str) -> None: + fleet.hosts = [_host(31 + n) for n in range(hosts)] + + assert _ending().end(ENDED)[0] == f"Certificate template rmscep is removed from team rmscep{said}" + + +def test_an_authority_another_team_still_uses_stays(fleet: _Fleet) -> None: + """Fleet's conflict is a line for the operator, not a failure""" + fleet.certificates = [ + {"id": 81, "name": "rmscep", "team_id": 7, "subject_name": "CN=$X", "certificate_authority_id": 3}, + {"id": 90, "name": "rmscep", "team_id": 8, "subject_name": "CN=$X", "certificate_authority_id": 3}, + ] + + lines = _ending().end(ENDED) + + assert lines[1:] == [ + "Certificate authority RMSCEP stays in Fleet: another team's certificate template still uses it.", + KEPT, + ] + assert [c["id"] for c in fleet.certificates] == [90] and [a["id"] for a in fleet.authorities] == [3] + + +def test_ending_again_finishes_what_an_earlier_call_left(fleet: _Fleet) -> None: + """The template gone already, the authority that serves this Deploy App is found by its address""" + fleet.certificates = [] + fleet.authorities = [ + {"id": 3, "name": "ODMDM_OTHER", "url": "https://other.test/scep"}, + {"id": 4, "name": "ODMDM_DEPLOYMENT", "url": "https://deployment.test/scep"}, + ] + + lines = _ending().end(ENDED) + + assert lines == [ + "Team rmscep has no certificate template rmscep: there was nothing to remove from it.", + "Certificate authority ODMDM_DEPLOYMENT is removed from Fleet.", + KEPT, + ] + assert [a["id"] for a in fleet.authorities] == [3], "another Deploy App's authority stays" + + +def test_ending_when_nothing_is_left_says_so(fleet: _Fleet) -> None: + fleet.certificates = [] + fleet.authorities = [{"id": 3, "name": "ODMDM_OTHER", "url": "https://other.test/scep"}] + + assert _ending().end(ENDED) == [ + "Team rmscep has no certificate template rmscep: there was nothing to remove from it.", + KEPT, + ] + assert not _changes(fleet) + + +def test_ending_without_the_team_changes_nothing(fleet: _Fleet) -> None: + with pytest.raises(MdmError) as raised: + _ending(team="golden-monkey DeployApp").end(ENDED) + + assert str(raised.value) == ( + "Fleet has no team named golden-monkey DeployApp, so nothing was changed. Check the team's name." + ) + assert not _changes(fleet) + + +def test_a_team_bound_to_another_deploy_apps_authority_is_left_as_it_is(fleet: _Fleet) -> None: + """Its phones take their certificates from another Deploy App, so removing the template would end that one""" + with pytest.raises(MdmError) as raised: + _ending().end(Settings("https://golden-monkey.example.fi/scep", "")) + + assert str(raised.value) == ( + "Team rmscep takes its certificates from authority RMSCEP, which serves https://deployment.test/scep, not " + "https://golden-monkey.example.fi/scep, so nothing was changed. Check the team's name." + ) + assert not _changes(fleet) + + +def test_a_refusal_half_way_carries_the_lines_already_due(fleet: _Fleet) -> None: + """The template is gone, so the operator learns it; ending again finishes the rest""" + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.method == "DELETE" and "/certificate_authorities/" in request.url.path: + return Response(500, text="database is locked") + return answer(request) + + fleet.handler = refusing # type: ignore[method-assign] + + with pytest.raises(MdmError) as raised: + _ending().end(ENDED) + + assert str(raised.value).startswith( + "Fleet refused: DELETE /api/latest/fleet/certificate_authorities/3 answered 500" + ) + assert raised.value.lines == [ + "Certificate template rmscep is removed from team rmscep, which has no phones.", + ] + assert not raised.value.unauthorized + + +def test_a_token_refused_while_ending_is_said_as_such(fleet: _Fleet) -> None: + fleet.handler = lambda request: Response(401, json={"message": "Authentication required"}) # type: ignore[method-assign] + + with pytest.raises(MdmError) as raised: + _ending().end(ENDED) + + assert raised.value.unauthorized From 5e64cb7a7d6c7a62a0317b1d49334a63fd1a8c2f Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:22:55 +0200 Subject: [PATCH 3/9] feat(demo): the demo plugin ends its Deploy App, its phones and their names kept --- .../src/odmdm_connector_demo/__init__.py | 11 +++++++++++ 1 file changed, 11 insertions(+) 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 a2f3a2a..44abdce 100644 --- a/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py +++ b/examples/odmdm-connector-demo/src/odmdm_connector_demo/__init__.py @@ -36,6 +36,8 @@ def __init__(self, values: Mapping[str, str], refuse_after: int | None = None) - """refuse_after: for tests, the pretend MDM refuses to name more phones than that""" self.group = values.get("group", "") self.refuse_after = refuse_after + #: Whether this Deploy App was taken out of the pretend group + self.ended = False 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), @@ -81,3 +83,12 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: for each in again: self._waiting(each.id, each.callsign) return [f"Phone {each.id}: certificate asked for again" for each in again] + + def end(self, window: Settings) -> list[str]: + """Take the Deploy App out of the pretend group: its phones lose the certificate and keep their names""" + kept = f"Group {self.group}, its phones, their names and their apps stay" + if self.ended: + return [f"Group {self.group} has nothing of {window.scep_url} left to take out", kept] + self.ended = True + self.found = [replace(each, state=State.NO_REQUEST) for each in self.found] + return [f"Group {self.group} no longer takes certificates from {window.scep_url}", kept] From 6d4d3e0bb63d34b84622f25008baf1ff55a84532 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:23:22 +0200 Subject: [PATCH 4/9] feat: end in the MDM contract, the fake and the plugin authors' checks --- src/odmdm_connector/mdm.py | 37 +++++++++++++++++++--- src/odmdm_connector/testing/contract.py | 17 ++++++++++ src/odmdm_connector/testing/fake.py | 14 ++++++++- tests/test_fleet_plugin.py | 23 ++++++-------- tests/test_mdm.py | 41 ++++++++++++++++++++++++- tests/test_testing.py | 35 +++++++++++++++++++++ 6 files changed, 147 insertions(+), 20 deletions(-) diff --git a/src/odmdm_connector/mdm.py b/src/odmdm_connector/mdm.py index 3d1a02d..d4382f7 100644 --- a/src/odmdm_connector/mdm.py +++ b/src/odmdm_connector/mdm.py @@ -4,9 +4,9 @@ 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, by the command line and the page alike, so it names no -command, option or button. The SCEP challenge is never in one. +Every sentence a plugin hands back, a Step's message, a line from name, ask_again or end, an +MdmError, 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. """ from collections.abc import Iterator, Mapping, Sequence @@ -24,7 +24,9 @@ ASK_AGAIN = "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) +#: end: this Deploy App taken out of the MDM once its deployment is over +END = "end" +CAPABILITIES = (SETUP, SET_CHALLENGE, ASK_AGAIN, SEND_POLICY, END) #: In a Field's default, the deployment's name: the first label of its Deploy App's host DEPLOYMENT = "{deployment}" @@ -168,12 +170,38 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: Answers the lines to show the operator, none when nothing was asked. """ + def end(self, window: Settings) -> list[str]: + """Take this Deploy App out of the MDM once its deployment is over + + The group's phones lose this Deploy App's certificate; the group, its phones, their names + and their apps stay, ready for the group's next Deploy App. window says which Deploy App by + its scep_url; its challenge is not used. Answers the lines to show the operator: what was + taken out and what stays. Called again, it takes out what an earlier call left and says so + when nothing was left. An MDM that cannot lists END in missing. + """ + + +def cannot_end(mdm: "Mdm | type[Mdm]") -> str: + """Why this MDM cannot end a Deploy App, empty when it can + + A plugin made before END was in the contract has no end and does not list END in missing: it + cannot, and the connector says so in a sentence of its own rather than call what is not there. + """ + if END in mdm.missing: + return mdm.missing[END] + if not callable(getattr(mdm, "end", None)): + return ( + f"This {mdm.title} plugin cannot end a Deploy App in {mdm.title}: it was made before the connector could." + ) + return "" + __all__ = [ "API_VERSION", "ASK_AGAIN", "CAPABILITIES", "DEPLOYMENT", + "END", "SEND_POLICY", "SETUP", "SET_CHALLENGE", @@ -184,4 +212,5 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: "Settings", "State", "Step", + "cannot_end", ] diff --git a/src/odmdm_connector/testing/contract.py b/src/odmdm_connector/testing/contract.py index eaa57e8..b63b699 100644 --- a/src/odmdm_connector/testing/contract.py +++ b/src/odmdm_connector/testing/contract.py @@ -23,6 +23,7 @@ def test_the_contract(check: contract.Check) -> None: API_VERSION, ASK_AGAIN, CAPABILITIES, + END, SEND_POLICY, SET_CHALLENGE, SETUP, @@ -177,6 +178,21 @@ def sends_the_policy_again(factory: Factory) -> None: _require(steps and all(isinstance(step, Step) for step in steps), "setup with force must report Steps") +def ends(factory: Factory) -> None: + """Ends the Deploy App twice over, its phones and their names left as they were; or says it cannot""" + mdm = factory() + if _lacking(mdm, END, lambda: mdm.end(WINDOW)): + return + _require(callable(getattr(mdm, "end", None)), "end must be a method, or END listed in missing with its sentence") + before = [(phone.id, phone.callsign) for phone in mdm.phones()] + _lines(mdm.end(WINDOW), "end") + again = mdm.end(WINDOW) + _lines(again, "end, called again") + _require(again, "end, called again, must say what it found left") + after = [(phone.id, phone.callsign) for phone in mdm.phones()] + _require(after == before, "end must leave the group's phones and their names as they were") + + CHECKS: tuple[Check, ...] = ( declares_the_contract_version, declares_its_fields, @@ -189,4 +205,5 @@ def sends_the_policy_again(factory: Factory) -> None: sets_the_challenge, sets_up, sends_the_policy_again, + ends, ) diff --git a/src/odmdm_connector/testing/fake.py b/src/odmdm_connector/testing/fake.py index a3d9f18..ba8eda6 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, SEND_POLICY, SET_CHALLENGE, SETUP, Field, MdmError, Phone, State, Step +from ..mdm import API_VERSION, ASK_AGAIN, END, 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 @@ -43,6 +43,8 @@ def __init__( self.calls: list[str] = [] #: The challenge last given, kept so a test can see it arrived self.challenge = "" + #: The SCEP URL of the Deploy App taken out of the group by end, empty while none was + self.ended = "" @classmethod def lacking(cls, *capabilities: str) -> type["FakeMdm"]: @@ -107,3 +109,13 @@ def ask_again(self, ids: Sequence[str]) -> list[str]: for phone in again: self._waiting(phone) return [f"Phone {phone}: certificate asked for again" for phone in again] + + def end(self, window: Settings) -> list[str]: + self._able(END) + group = self.values.get("group", "Deploy App") + kept = f"Group {group}, its phones, their names and their apps stay" + if self.ended == window.scep_url: + return [f"Group {group} has nothing of {window.scep_url} left to take out", kept] + self.ended = window.scep_url + self.group = [replace(each, state=State.NO_REQUEST) for each in self.group] + return [f"Group {group} no longer enrols at {window.scep_url}: its phones lose its certificate", kept] diff --git a/tests/test_fleet_plugin.py b/tests/test_fleet_plugin.py index 835785f..f0db691 100644 --- a/tests/test_fleet_plugin.py +++ b/tests/test_fleet_plugin.py @@ -281,11 +281,6 @@ def test_setup_with_force_sends_the_unchanged_policy_again_and_no_challenge(flee KEPT = "The team, its phones, their names and their apps stay." -def _ending(**values: str) -> FleetPlugin: - """The plugin itself: until the contract has end, an Mdm does not""" - return FleetPlugin({"mdm_url": "https://mdm.test", "token": "token", "team": "rmscep", **values}) - - def _changes(fleet: _Fleet) -> list[tuple[str, str]]: return [call for call in fleet.calls if call[0] != "GET"] @@ -294,7 +289,7 @@ def test_ending_removes_the_template_and_then_the_authority(fleet: _Fleet) -> No """Only those two: the team, its hosts, its policy and its apps stay""" fleet.hosts = [_host(31, "verified", "OTTER1"), _host(32)] - lines = _ending().end(ENDED) + lines = _plugin().end(ENDED) assert lines == [ ( @@ -322,7 +317,7 @@ def test_ending_removes_the_template_and_then_the_authority(fleet: _Fleet) -> No def test_ending_says_how_many_phones_lose_the_certificate(fleet: _Fleet, hosts: int, said: str) -> None: fleet.hosts = [_host(31 + n) for n in range(hosts)] - assert _ending().end(ENDED)[0] == f"Certificate template rmscep is removed from team rmscep{said}" + assert _plugin().end(ENDED)[0] == f"Certificate template rmscep is removed from team rmscep{said}" def test_an_authority_another_team_still_uses_stays(fleet: _Fleet) -> None: @@ -332,7 +327,7 @@ def test_an_authority_another_team_still_uses_stays(fleet: _Fleet) -> None: {"id": 90, "name": "rmscep", "team_id": 8, "subject_name": "CN=$X", "certificate_authority_id": 3}, ] - lines = _ending().end(ENDED) + lines = _plugin().end(ENDED) assert lines[1:] == [ "Certificate authority RMSCEP stays in Fleet: another team's certificate template still uses it.", @@ -349,7 +344,7 @@ def test_ending_again_finishes_what_an_earlier_call_left(fleet: _Fleet) -> None: {"id": 4, "name": "ODMDM_DEPLOYMENT", "url": "https://deployment.test/scep"}, ] - lines = _ending().end(ENDED) + lines = _plugin().end(ENDED) assert lines == [ "Team rmscep has no certificate template rmscep: there was nothing to remove from it.", @@ -363,7 +358,7 @@ def test_ending_when_nothing_is_left_says_so(fleet: _Fleet) -> None: fleet.certificates = [] fleet.authorities = [{"id": 3, "name": "ODMDM_OTHER", "url": "https://other.test/scep"}] - assert _ending().end(ENDED) == [ + assert _plugin().end(ENDED) == [ "Team rmscep has no certificate template rmscep: there was nothing to remove from it.", KEPT, ] @@ -372,7 +367,7 @@ def test_ending_when_nothing_is_left_says_so(fleet: _Fleet) -> None: def test_ending_without_the_team_changes_nothing(fleet: _Fleet) -> None: with pytest.raises(MdmError) as raised: - _ending(team="golden-monkey DeployApp").end(ENDED) + _plugin(team="golden-monkey DeployApp").end(ENDED) assert str(raised.value) == ( "Fleet has no team named golden-monkey DeployApp, so nothing was changed. Check the team's name." @@ -383,7 +378,7 @@ def test_ending_without_the_team_changes_nothing(fleet: _Fleet) -> None: def test_a_team_bound_to_another_deploy_apps_authority_is_left_as_it_is(fleet: _Fleet) -> None: """Its phones take their certificates from another Deploy App, so removing the template would end that one""" with pytest.raises(MdmError) as raised: - _ending().end(Settings("https://golden-monkey.example.fi/scep", "")) + _plugin().end(Settings("https://golden-monkey.example.fi/scep", "")) assert str(raised.value) == ( "Team rmscep takes its certificates from authority RMSCEP, which serves https://deployment.test/scep, not " @@ -404,7 +399,7 @@ def refusing(request: Request) -> Response: fleet.handler = refusing # type: ignore[method-assign] with pytest.raises(MdmError) as raised: - _ending().end(ENDED) + _plugin().end(ENDED) assert str(raised.value).startswith( "Fleet refused: DELETE /api/latest/fleet/certificate_authorities/3 answered 500" @@ -419,6 +414,6 @@ def test_a_token_refused_while_ending_is_said_as_such(fleet: _Fleet) -> None: fleet.handler = lambda request: Response(401, json={"message": "Authentication required"}) # type: ignore[method-assign] with pytest.raises(MdmError) as raised: - _ending().end(ENDED) + _plugin().end(ENDED) assert raised.value.unauthorized diff --git a/tests/test_mdm.py b/tests/test_mdm.py index 4b54ead..2ed3063 100644 --- a/tests/test_mdm.py +++ b/tests/test_mdm.py @@ -3,6 +3,8 @@ import pytest from odmdm_connector import mdm +from odmdm_connector.settings import Settings +from odmdm_connector.testing import FakeMdm def test_an_error_carries_the_phones_named_before_it() -> None: @@ -20,7 +22,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", "send_policy"} + assert set(mdm.CAPABILITIES) == {"setup", "set_challenge", "ask_again", "send_policy", "end"} assert mdm.API_VERSION == 1 @@ -54,3 +56,40 @@ def test_a_default_may_name_the_deployment() -> None: 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 + + +class _Older(FakeMdm): + """A plugin made before END was in the contract: no end, and END not in missing""" + + end = None # type: ignore[assignment] + + +@pytest.mark.parametrize( + ("chosen", "says"), + [ + (FakeMdm, ""), + (FakeMdm.lacking(mdm.END), "The fake MDM cannot end"), + (_Older, "This Fake MDM plugin cannot end a Deploy App in Fake MDM: it was made before the connector could."), + ], +) +def test_why_an_mdm_cannot_end(chosen: type[FakeMdm], says: str) -> None: + """Its own sentence when it lists END, the connector's when it is older than END; the class and an MDM alike""" + assert mdm.cannot_end(chosen) == says + assert mdm.cannot_end(chosen({})) == says + + +def test_the_fake_ends_once_and_then_says_nothing_was_left() -> None: + """Its phones keep their names and lose the certificate; a second call finds nothing to take out""" + fake = FakeMdm({"group": "golden-monkey DeployApp"}) + window = Settings("https://golden-monkey.example.fi/scep", "") + + first = fake.end(window) + again = fake.end(window) + + assert first[0].startswith( + "Group golden-monkey DeployApp no longer enrols at https://golden-monkey.example.fi/scep" + ) + assert again[0].startswith("Group golden-monkey DeployApp has nothing of") + assert [phone.callsign for phone in fake.phones()] == ["", "", "OTTER1"] + assert {phone.state for phone in fake.phones()} == {mdm.State.NO_REQUEST} + assert fake.calls.count("end") == 2 diff --git a/tests/test_testing.py b/tests/test_testing.py index 4a688f0..a72928e 100644 --- a/tests/test_testing.py +++ b/tests/test_testing.py @@ -1,6 +1,7 @@ """The plugin authors' test kit, run against the fake and against Fleet over the stub""" from collections.abc import Iterator, Mapping, Sequence +from dataclasses import replace from typing import ClassVar import pytest @@ -107,6 +108,36 @@ def set_challenge(self, window: object) -> None: raise MdmError("Something else") +class _Older(FakeMdm): + """Made before END was in the contract: no end, and END not in missing""" + + end = None # type: ignore[assignment] + + +class _Silent(FakeMdm): + """Ends once, then says nothing of what it found left""" + + def end(self, window: Settings) -> list[str]: + return super().end(window) if not self.ended else [] + + +class _Renaming(FakeMdm): + """Ends, and takes the phones' names with it""" + + def end(self, window: Settings) -> list[str]: + self.group = [replace(phone, callsign="") for phone in self.group] + return super().end(window) + + +class _Ending(FakeMdm): + """Says it cannot end, then ends anyway""" + + missing: ClassVar[Mapping[str, str]] = {"end": "Not here"} + + def end(self, window: Settings) -> list[str]: + return ["Ended"] + + @pytest.mark.parametrize( ("factory", "check", "says"), [ @@ -117,6 +148,10 @@ def set_challenge(self, window: object) -> None: (_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"), + (_Older, contract.ends, "end must be a method, or END listed in missing"), + (_Silent, contract.ends, "end, called again, must say what it found left"), + (_Renaming, contract.ends, "must leave the group's phones and their names as they were"), + (_Ending, contract.ends, "end is listed as missing but did not raise"), ], ) def test_a_plugin_breaking_the_contract_fails_its_check( From 413b4b82b65c4e251a1d7bd6165449c214e68be7 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:24:31 +0200 Subject: [PATCH 5/9] feat: end a Deploy App in its MDM through the core, then remove it --- src/odmdm_connector/app.py | 70 ++++++++++- tests/test_app.py | 231 +++++++++++++++++++++++++++++++++++++ 2 files changed, 299 insertions(+), 2 deletions(-) diff --git a/src/odmdm_connector/app.py b/src/odmdm_connector/app.py index de8d66d..0ebb8d3 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, SEND_POLICY, 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, cannot_end from .settings import Settings LOGGER = logging.getLogger(__name__) @@ -183,6 +183,8 @@ class Job(Enum): ASK_AGAIN = "ask again" #: Setup again with the policy sent even if unchanged POLICY = "policy" + #: The Deploy App taken out of its MDM, then removed from the app + END = "end" @dataclass(frozen=True) @@ -423,6 +425,8 @@ def __init__( #: 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) + #: The Deploy Apps whose end waits or runs, each its own job: nothing more goes to the MDM for them + self._ending: set[str] = set() # 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() @@ -468,6 +472,11 @@ def _drop(self) -> None: self.mdm = self.mdm_class = self.window = self._passed = None self.phones, self._listed, self._progress = [], False, () + def _unended(self, host: str) -> None: + """Refuse to send anything more to the MDM for a Deploy App whose end waits or runs""" + if host in self._ending: + raise AppError(f"Deploy App {host} is being ended in its MDM, so nothing more is sent to the MDM for it.") + 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 @@ -646,6 +655,7 @@ def connect(self, name: str, values: Mapping[str, str], remember: bool = True) - 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.") + self._unended(self.saved.active) 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}, " @@ -715,6 +725,7 @@ def send_policy(self) -> str: for capability in (SETUP, SEND_POLICY): if capability in self.mdm.missing: raise AppError(self.mdm.missing[capability]) + self._unended(self.saved.active) 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) @@ -780,6 +791,50 @@ def remove(self, host: str) -> str: ) return self._say(f"Deploy App {host} is removed from this app, and its MDM token from this computer.") + def end_note(self) -> str: + """Why the active Deploy App cannot be ended in its MDM from here; empty when it can, or has no MDM""" + if not self.conn.mdm: + return "" + if self.mdm is None: + return "The MDM is not connected, so this Deploy App can only be removed from this app." + return cannot_end(self.mdm) + + @property + def ending(self) -> bool: + """Whether the active Deploy App's end waits or runs""" + return self.saved.active in self._ending + + @property + def can_end(self) -> bool: + """Whether the active Deploy App can be ended in its MDM from here""" + return self.mdm is not None and not cannot_end(self.mdm) + + def end(self, host: str) -> str: + """Take the Deploy App out of its MDM on the worker, and once that is done remove it as remove does + + It needs the MDM connected, which only the active Deploy App's is. The MDM is handed the + window held, else one made from the host, with no challenge. Ended, the MDM's lines are said + and then remove's sentence; failed, nothing is removed, so that it can be tried again. Asked + again while it waits or runs, nothing more is sent, and nothing else goes to the MDM for that + Deploy App until it is done. Another Deploy App's end is a job of its own. + """ + if host not in self.saved.connections: + raise AppError(f"There is no Deploy App {host} in this app.") + if host != self.saved.active or self.mdm is None: + raise AppError(f"Connect to the MDM of Deploy App {host} first: ending it there needs the MDM connected.") + why = cannot_end(self.mdm) + if why: + raise AppError(why) + said = f"Ending Deploy App {host} in {self.mdm.title}." + if host in self._ending: + return self._say(said) + mdm = self.mdm + window = Settings(self.window.scep_url if self.window else f"https://{host}/scep", "") + self._ending.add(host) + self._submit(Job.END, lambda: Result(Job.END, lines=tuple(mdm.end(window)))) + LOGGER.info("Ending Deploy App %s in the MDM", host) + return self._say(said) + # The enrolment window def paste_settings(self, text: str, now: datetime.datetime, sender: str = "") -> str: @@ -791,6 +846,7 @@ def paste_settings(self, text: str, now: datetime.datetime, sender: str = "") -> pasted by hand; a line sent from a page other than its own Deploy App's is refused. """ window, host = _read(text, now, sender) + self._unended(host) closes = window.closes.isoformat() if window.closes else "" connection = replace(self.saved.connections.get(host, store.Connection()), closes=closes) changed = self._activate(host, connection) @@ -979,6 +1035,7 @@ 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.") + self._unended(self.saved.active) 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 @@ -992,6 +1049,7 @@ def ask_again(self, ids: Sequence[str]) -> str: raise AppError("Connect to the MDM first.") if ASK_AGAIN in self.mdm.missing: raise AppError(self.mdm.missing[ASK_AGAIN]) + self._unended(self.saved.active) if not ids: mdm = self.mdm self._submit(Job.ASK_AGAIN, lambda: Result(Job.ASK_AGAIN, lines=tuple(mdm.ask_again([])))) @@ -1028,6 +1086,8 @@ def drain(self) -> list[Result]: except queue.Empty: return done self._pending[result.job] -= 1 + if result.job is Job.END: + self._ending.discard(result.host) result = self._scrubbed(result) self._take(result) done.append(result) @@ -1096,5 +1156,11 @@ def _take(self, result: Result) -> None: 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): + elif result.job is Job.END: + try: + removed = self.remove(result.host) + except AppError as exc: + removed = str(exc) + self._say(removed, *result.lines) + if result.job in (Job.NAME, Job.ASK_AGAIN, Job.END): self.lines = result.lines diff --git a/tests/test_app.py b/tests/test_app.py index b433301..5bed1dc 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -3,6 +3,7 @@ import datetime import io import logging +import re import sys import threading import time @@ -1507,3 +1508,233 @@ def test_a_team_saved_or_typed_stays_as_it_is(rig: Rig) -> None: 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": " "}) + + +class Ending(FakeMdm): + """Records the windows it ends, by class, so that a test sees them across a restart""" + + windows: ClassVar[list[Settings]] = [] + + def end(self, window: Settings) -> list[str]: + self.windows.append(window) + return super().end(window) + + +class EndRefused(FakeMdm): + """Takes the certificate out, then is refused""" + + def end(self, window: Settings) -> list[str]: + raise MdmError("Fleet refused: the authority cannot be deleted", lines=["Certificate template removed"]) + + +def test_ending_takes_the_deploy_app_out_of_the_mdm_and_then_removes_it(keyed: Rig) -> None: + """The MDM's lines and then remove's sentence; the window held goes without its challenge""" + keyed.classes["fake"] = Ending + Ending.windows.clear() + keyed.connected() + + assert (keyed.app.can_end, keyed.app.end_note()) == (True, "") + said = keyed.app.end("unit.example.fi") + [result] = keyed.settle() + + assert said == "Ending Deploy App unit.example.fi in Fake MDM." + assert (result.job, result.error) == (app.Job.END, "") + assert Ending.windows == [Settings("https://unit.example.fi/scep", "")] + assert keyed.app.lines == ( + "Group Deploy App no longer enrols at https://unit.example.fi/scep: its phones lose its certificate", + "Group Deploy App, its phones, their names and their apps stay", + ) + assert keyed.app.status == ( + "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + ) + assert keyed.app.saved == store.Saved() + assert keyed.backend is not None and keyed.backend.items == {} + assert not keyed.app.connected + + +def test_ending_without_a_window_held_names_the_deploy_app_by_its_host(keyed: Rig) -> None: + """After a restart no window is held, as for sending the policy again""" + keyed.classes["fake"] = Ending + keyed.connected() + keyed.app.close() + keyed.app = keyed.start() + Ending.windows.clear() + + keyed.app.end("unit.example.fi") + keyed.settle() + + assert Ending.windows == [Settings("https://unit.example.fi/scep", "")] + assert keyed.app.saved == store.Saved() + + +def test_an_end_that_fails_removes_nothing(rig: Rig) -> None: + """The lines already due and the refusal are said, and the operator can try again""" + rig.classes["fake"] = EndRefused + rig.connected() + + rig.app.end("unit.example.fi") + [result] = rig.settle() + + assert result.error == rig.app.status == "Fleet refused: the authority cannot be deleted" + assert rig.app.lines == ("Certificate template removed",) + assert list(rig.app.saved.connections) == ["unit.example.fi"] + assert rig.app.connected and rig.app.can_end + assert not rig.app.ending + rig.app.end("unit.example.fi") + assert rig.app.busy(app.Job.END) + rig.settle() + + +def test_ending_is_asked_once_while_it_waits_or_runs(rig: Rig) -> None: + rig.classes["fake"] = Ending + Ending.windows.clear() + rig.connected() + + first = rig.app.end("unit.example.fi") + second = rig.app.end("unit.example.fi") + rig.settle() + + assert first == second == "Ending Deploy App unit.example.fi in Fake MDM." + assert len(Ending.windows) == 1 + + +def test_ending_hands_the_mdm_the_window_held(rig: Rig) -> None: + """Its SCEP URL as pasted, whatever its path""" + rig.classes["fake"] = Ending + Ending.windows.clear() + rig.app.paste_settings(LINE.replace("/scep ", "/enrol/scep "), NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + rig.app.end("unit.example.fi") + rig.settle() + + assert Ending.windows == [Settings("https://unit.example.fi/enrol/scep", "")] + + +def test_nothing_more_goes_to_the_mdm_for_a_deploy_app_being_ended(rig: Rig) -> None: + """Else the worker would set the MDM up again behind the end, for a Deploy App then removed""" + rig.connected() + rig.app.end("unit.example.fi") + refused = "^Deploy App unit.example.fi is being ended in its MDM, so nothing more is sent to the MDM for it.$" + + assert rig.app.ending + for asked in ( + rig.app.send_policy, + lambda: rig.app.connect("fake", VALUES), + lambda: rig.app.paste_settings(LINE, NOW), + lambda: rig.app.name({}), + lambda: rig.app.ask_again([]), + ): + with pytest.raises(app.AppError, match=refused): + asked() + results = rig.settle() + + assert [result.job for result in results] == [app.Job.END] + assert not rig.app.ending + assert rig.app.saved == store.Saved() + + +def test_another_deploy_app_is_ended_while_one_is(rig: Rig) -> None: + """Each end is a job of its own, for its own Deploy App""" + rig.classes["fake"] = Ending + Ending.windows.clear() + rig.connected() + rig.app.end("unit.example.fi") + rig.app.paste_settings(OTHER, NOW) + rig.app.connect("fake", VALUES) + + assert not rig.app.ending + said = rig.app.end("other.example.fi") + assert rig.app.ending + results = rig.settle() + + assert said == "Ending Deploy App other.example.fi in Fake MDM." + assert [(result.job, result.host) for result in results] == [ + (app.Job.END, "unit.example.fi"), + (app.Job.SETUP, "other.example.fi"), + (app.Job.END, "other.example.fi"), + ] + assert Ending.windows == [ + Settings("https://unit.example.fi/scep", ""), + Settings("https://other.example.fi/scep", ""), + ] + assert rig.app.saved == store.Saved() + + +def test_a_deploy_app_removed_while_it_was_ended_is_said(rig: Rig) -> None: + """The MDM's lines are still said, beside why there was nothing left to remove""" + rig.connected() + rig.app.end("unit.example.fi") + rig.app.remove("unit.example.fi") + rig.settle() + + assert rig.app.status == "There is no Deploy App unit.example.fi in this app." + assert rig.app.lines[0].startswith("Group Deploy App no longer enrols") + + +class Older(FakeMdm): + """A plugin made before END was in the contract""" + + end = None # type: ignore[assignment] + + +@pytest.mark.parametrize( + ("chosen", "says"), + [ + (FakeMdm.lacking("end"), "The fake MDM cannot end"), + (Older, "This Fake MDM plugin cannot end a Deploy App in Fake MDM: it was made before the connector could."), + ], +) +def test_ending_is_not_offered_by_an_mdm_that_cannot(rig: Rig, chosen: type[FakeMdm], says: str) -> None: + rig.classes["fake"] = chosen + rig.connected() + + assert (rig.app.can_end, rig.app.end_note()) == (False, says) + with pytest.raises(app.AppError, match=f"^{re.escape(says)}$"): + rig.app.end("unit.example.fi") + assert not rig.app.busy() + assert list(rig.app.saved.connections) == ["unit.example.fi"] + + +def test_ending_needs_the_mdm_connected(rig: Rig) -> None: + """No MDM chosen: nothing to say; chosen but not connected in this run: why not""" + rig.app.paste_settings(LINE, NOW) + assert (rig.app.can_end, rig.app.end_note()) == (False, "") + with pytest.raises(app.AppError, match="^There is no Deploy App other.example.fi in this app.$"): + rig.app.end("other.example.fi") + + rig.connected() + rig.app.close() + rig.app = rig.start() + + assert rig.app.end_note() == "The MDM is not connected, so this Deploy App can only be removed from this app." + with pytest.raises( + app.AppError, + match="^Connect to the MDM of Deploy App unit.example.fi first: ending it there needs the MDM connected.$", + ): + rig.app.end("unit.example.fi") + assert list(rig.app.saved.connections) == ["unit.example.fi"] + + +def test_only_the_active_deploy_app_can_be_ended(rig: Rig) -> None: + """Its MDM is the one held""" + rig.connected() + rig.app.paste_settings(OTHER, NOW) + + with pytest.raises(app.AppError, match="^Connect to the MDM of Deploy App unit.example.fi first"): + rig.app.end("unit.example.fi") + + +def test_a_deploy_app_not_active_is_not_ended_with_the_active_ones_mdm(rig: Rig) -> None: + """The MDM held, its group and its token, are the active Deploy App's""" + rig.connected() + rig.app.paste_settings(OTHER, NOW) + rig.app.connect("fake", VALUES) + rig.settle() + + assert rig.app.connected + with pytest.raises(app.AppError, match="^Connect to the MDM of Deploy App unit.example.fi first"): + rig.app.end("unit.example.fi") + assert not rig.app.busy() + assert list(rig.app.saved.connections) == ["unit.example.fi", "other.example.fi"] From d33d933c40aa923a28c5f96562dae99023ae829f Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:26:26 +0200 Subject: [PATCH 6/9] feat: the Remove dialog can end the Deploy App in its MDM too --- AGENTS.md | 8 +-- src/odmdm_connector/static/app.css | 5 ++ src/odmdm_connector/static/app.js | 78 +++++++++++++++++++++++------- src/odmdm_connector/web.py | 14 +++++- tests/test_web.py | 65 ++++++++++++++++++++++++- 5 files changed, 147 insertions(+), 23 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fe73ee3..868bff7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,11 +129,13 @@ giving callsigns, one phone, the settings and removing a Deploy App. Keep these 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, + dialog's lines on what removing changes and on what ending the Deploy App in its MDM changes + (never how soon: only the MDM's plugin knows that), 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 + confirm card for a new Deploy App, on Cancel. Enter on the Remove dialog's box does nothing: only + its button ends a Deploy App. 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 diff --git a/src/odmdm_connector/static/app.css b/src/odmdm_connector/static/app.css index 6372076..2dc91d8 100644 --- a/src/odmdm_connector/static/app.css +++ b/src/odmdm_connector/static/app.css @@ -1038,6 +1038,11 @@ dialog .check { margin-bottom: 0; } +/* What a ticked box changes is said right under it, a little apart */ +dialog .check + p { + margin-top: 10px; +} + dialog h3 { font-size: 13px; color: var(--muted); diff --git a/src/odmdm_connector/static/app.js b/src/odmdm_connector/static/app.js index 024a1e1..10e51cd 100644 --- a/src/odmdm_connector/static/app.js +++ b/src/odmdm_connector/static/app.js @@ -15,6 +15,8 @@ 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 told = []; // the MDM's lines said before notice, once a Deploy App was ended in it +let ending = ""; // the Deploy App being ended in its MDM, until that is done 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 @@ -147,6 +149,7 @@ async function act(path, body, then, fail = say) { return; } notice = answer.said || ""; + told = []; if (await refresh(false)) then(answer); } @@ -177,6 +180,14 @@ async function refresh(redraw = true) { 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; + // Ended in its MDM and so removed: what the MDM said and the removal go with the card that follows + if (ending && !S.busy.includes("end")) { + if (!S.connections.some((each) => each.host === ending)) { + notice = S.status; + told = S.lines; + } + ending = ""; + } if (!screen || screen === "away") begin(); else if (!redraw) return true; else if (screen === "app" && !S.connected) { @@ -217,6 +228,7 @@ function show(name) { function go(name) { notice = ""; + told = []; show(name); } @@ -295,6 +307,7 @@ function frame({ parts, step = null, back = null, corner = "", host = false }) { function begin() { problem = notice = ""; + told = []; if (!arriving) return home(); closeOverlays(); const { line, from } = arriving; @@ -429,6 +442,7 @@ const CARDS = { back: S.connections.length ? { text: "Back", action: flow.back || home } : null, parts: [ h1(renew ? ["New settings for Deploy App ", named(S.active)] : "Add your Deploy App"), + told.map((line) => el("p", { class: "muted" }, line)), 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 @@ -483,6 +497,7 @@ const CARDS = { return { parts: [ h1("Which Deploy App?"), + told.map((line) => el("p", { class: "muted" }, line)), notice ? lead(notice) : null, S.connections.map((each) => choice(each.host, each.short, () => act("/api/open", { host: each.host }, home), each.level), @@ -779,11 +794,11 @@ function phones() { el( "div", { class: "tools" }, - main("Give callsigns", () => giveCallsigns([...selected]), settling || !(selected.size || waiting), "tool go"), - tool("Ask again", () => askAgain([...selected]), settling || !askable), + main("Give callsigns", () => giveCallsigns([...selected]), settling || S.ending || !(selected.size || waiting), "tool go"), + tool("Ask again", () => askAgain([...selected]), settling || S.ending || !askable), tool("Details", () => detail([...selected][0]), settling || selected.size !== 1), tool("Refresh", () => act("/api/refresh", {}, () => draw(false))), - tool("New settings", () => adding(true)), + tool("New settings", () => adding(true), S.ending), tool("Settings", settings, false, "push"), ), el( @@ -928,13 +943,17 @@ function detail(id) { }; const foot = phone.can_ask_again ? [ - second(give, giving), - main("Ask again", () => { - dialog.close(); - askAgain([phone.id]); - }), + second(give, giving, S.ending), + main( + "Ask again", + () => { + dialog.close(); + askAgain([phone.id]); + }, + S.ending, + ), ] - : [main(give, giving)]; + : [main(give, giving, S.ending)]; open( phone.callsign || `Phone ${phone.id}`, [ @@ -1174,8 +1193,8 @@ function settings() { { 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), - 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, + second(`Change the ${answer.title} settings`, change, S.ending), + S.policy ? [el("h3", { class: "sect" }, "Policy"), el("p", { class: "muted" }, S.policy), second("Send the policy again", resend, S.ending || 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}`), @@ -1185,28 +1204,51 @@ function settings() { }); } +// Removing forgets the Deploy App here; ticked, where the MDM can, it is ended in the MDM first function remove() { const host = S.active; + const title = S.title; + const n = S.rows.length; + let end = false; submit = null; - const removing = () => + const removing = () => { + // Set before asking, as the MDM may be done by the time the answer comes + if (end) ending = host; act( "/api/remove", - { host }, + { host, end }, () => { dialog.close(); home(); }, (text) => tell(text), ); + }; + const forgets = "The connector forgets this Deploy App and its MDM token on this computer. Nothing changes in Deploy App, the MDM or the phones."; + const loses = + n === 0 + ? `It has no phones in ${title} now. This cannot be undone.` + : n === 1 + ? `Its phone loses this Deploy App's certificate. This cannot be undone. The phone stays in ${title} with its name and apps.` + : `Its ${n} phones lose this Deploy App's certificate. This cannot be undone. The phones stay in ${title} with their names and apps.`; + const said = el("p", {}, forgets); const button = main("Remove", removing, false, "danger"); + const tick = (on) => { + end = on; + said.textContent = on ? loses : forgets; + button.textContent = on ? "End and remove" : "Remove"; + }; + const also = S.can_end ? check(`Also end it in ${title}`, false, tick) : null; + // Enter on a checkbox submits its form: only the button ends a Deploy App, never a stray Enter + also?.querySelector("input").addEventListener("keydown", (event) => { + if (event.key === "Enter") event.preventDefault(); + }); const tell = open( ["Remove Deploy App ", named(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.", - ), + also, + said, + !S.can_end && S.mdm && S.end_note ? el("p", { class: "note" }, S.end_note) : null, ], [cancel(() => dialog.close()), button], ); diff --git a/src/odmdm_connector/web.py b/src/odmdm_connector/web.py index 6350bcf..a998b54 100644 --- a/src/odmdm_connector/web.py +++ b/src/odmdm_connector/web.py @@ -176,6 +176,13 @@ def state(self) -> Body: ], # What sending the policy again does, empty when the MDM cannot "policy": app.policy_note(), + # The MDM connected's name as the operator knows it, empty while none is + "title": app.mdm.title if app.mdm else "", + # Whether removing the Deploy App can end it in its MDM too, and why not when it has an MDM and cannot + "can_end": app.can_end, + "end_note": app.end_note(), + # The active Deploy App's end waits or runs: nothing more goes to the MDM for it + "ending": app.ending, # 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, @@ -209,7 +216,12 @@ def open(self, body: Body) -> Body: return {"said": said} def remove(self, body: Body) -> Body: - return {"said": self.app.remove(_text(body, "host"))} + """Remove the Deploy App from this app; with end, end it in its MDM first, which removes it once done""" + end = body.get("end", False) + if not isinstance(end, bool): + raise AppError("The page sent end as something other than yes or no.") + host = _text(body, "host") + return {"said": self.app.end(host) if end else self.app.remove(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""" diff --git a/tests/test_web.py b/tests/test_web.py index d181076..c7de0e4 100644 --- a/tests/test_web.py +++ b/tests/test_web.py @@ -15,7 +15,7 @@ import pytest from odmdm_connector import app, browser, console, store, web -from odmdm_connector.mdm import ASK_AGAIN, SEND_POLICY, State, Step +from odmdm_connector.mdm import ASK_AGAIN, END, SEND_POLICY, State, Step from odmdm_connector.settings import Settings from odmdm_connector.testing import FakeMdm @@ -1050,3 +1050,66 @@ def test_the_team_card_suggests_the_deployments_team(served: Served) -> None: "golden-monkey DeployApp", True, ) + + +def test_removing_with_end_ends_it_in_the_mdm_first(served: Served) -> None: + """Offered while the MDM connected can end; removed once the MDM has said what it took out""" + assert (served.state()["can_end"], served.state()["title"]) == (False, "") + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + offered = served.state() + + said = served.post("/api/remove", {"host": "unit.example.fi", "end": True}) + state = served.state() + + assert (offered["can_end"], offered["end_note"], offered["title"]) == (True, "", "Fake MDM") + assert said == {"said": "Ending Deploy App unit.example.fi in Fake MDM."} + assert state["connections"] == [] + assert ( + state["status"] == "Deploy App unit.example.fi is removed from this app, and its MDM token from this computer." + ) + assert state["lines"] == [ + "Group Deploy App no longer enrols at https://unit.example.fi/scep: its phones lose its certificate", + "Group Deploy App, its phones, their names and their apps stay", + ] + + +def test_ending_is_refused_for_an_mdm_that_cannot(served: Served) -> None: + """Its note is in the state, and removing without end still removes""" + served.rig.classes["fake"] = FakeMdm.lacking(END) + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + state = served.state() + + assert (state["can_end"], state["end_note"]) == (False, "The fake MDM cannot end") + assert served.post("/api/remove", {"host": "unit.example.fi", "end": True}, status=400) == { + "error": "The fake MDM cannot end" + } + assert served.post("/api/remove", {"host": "unit.example.fi", "end": "yes"}, status=400) == { + "error": "The page sent end as something other than yes or no." + } + assert served.post("/api/remove", {"host": "unit.example.fi", "end": False})["said"].startswith( + "Deploy App unit.example.fi is removed from this app" + ) + + +def test_the_state_says_while_the_active_deploy_app_is_being_ended(served: Served) -> None: + """The page disables what would send more to the MDM for it""" + go = threading.Event() + + class Slow(FakeMdm): + def end(self, window: Settings) -> list[str]: + go.wait(5) + return super().end(window) + + served.rig.classes["fake"] = Slow + served.post("/api/add", {"line": LINE}) + served.post("/api/connect", {"mdm": "fake", "values": VALUES}) + assert served.state()["ending"] is False + + served.post("/api/remove", {"host": "unit.example.fi", "end": True}) + running = json.loads(served.request("GET", "/api/state")[2]) + go.set() + + assert (running["ending"], "end" in running["busy"]) == (True, True) + assert served.state()["connections"] == [] From aca36dc4998bdc453c3bd3faa9d7feb7992228d9 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:27:44 +0200 Subject: [PATCH 7/9] feat: end, on the command line, ends a Deploy App in its MDM only with --yes --- src/odmdm_connector/console.py | 39 +++++++++++++-- tests/test_console.py | 88 ++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 3 deletions(-) diff --git a/src/odmdm_connector/console.py b/src/odmdm_connector/console.py index 55bcb49..0b0f451 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, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError +from .mdm import ASK_AGAIN, END, SEND_POLICY, SET_CHALLENGE, SETUP, Field, Mdm, MdmError, cannot_end from .settings import Settings #: Said when ODMDM_LOG_LEVEL is not a number @@ -163,8 +163,9 @@ def _mdm(args: argparse.Namespace, *capabilities: str, complete: bool = True) -> given = {key: setting for key, _, setting in (value.partition("=") for value in args.given)} chosen = _chosen(args.chosen) for capability in capabilities: - if capability in chosen.missing: - raise _Failed(chosen.missing[capability]) + why = cannot_end(chosen) if capability == END else chosen.missing.get(capability, "") + if why: + raise _Failed(why) for key in ("mdm_url", "team", "template"): if getattr(args, key, None) is not None: given[key] = getattr(args, key) @@ -352,6 +353,36 @@ def resend(args: argparse.Namespace) -> int: return 0 +def end(args: argparse.Namespace) -> int: + """Take this Deploy App out of the MDM once its deployment is over + + The team's phones lose this Deploy App's certificate at their next check-in, within about 15 + minutes. The team, its phones, their names and their apps stay, so the next Deploy App can be + connected to the same team. No challenge is needed. Without --yes nothing is changed: it says + how many phones would lose the certificate. + """ + the_domain = _domain(args) + mdm = _mdm(args, END) + try: + if not args.yes: + found = len(mdm.phones()) + would = ( + "The team has no phones" + if not found + else f"{found} phone{'' if found == 1 else 's'} in the team would lose this Deploy App's certificate" + ) + print(f"{would}. Nothing was changed: give --yes to end {the_domain} in {mdm.title}") + return 0 + lines = mdm.end(Settings(f"https://{the_domain}/scep", "")) + except MdmError as exc: + for line in exc.lines: + print(line) + raise _Failed(str(exc)) from exc + for line in lines: + print(line) + return 0 + + def mdms(args: argparse.Namespace) -> int: """List the MDMs installed: the name --mdm takes, the package and its version, built in or a plugin @@ -505,6 +536,8 @@ def command(called: str, run: Callable[[argparse.Namespace], int], *shared: str) ) sub = command("resend", resend, "--mdm-url", "--team") sub.add_argument("ids", nargs="*", metavar="ID") + sub = command("end", end, "--mdm-url", "--team", "--domain") + sub.add_argument("--yes", action="store_true", help="End it: without, nothing is changed") command("mdms", mdms) sub = command("web", page) sub.set_defaults(alone=False) diff --git a/tests/test_console.py b/tests/test_console.py index f0322d2..4b9d3c6 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -975,6 +975,7 @@ def refuse(self: Path) -> bytes: (["apply"], "setup"), (["resend"], "ask_again"), (["apply", "--force-policy"], "send_policy"), + (["end", "--yes"], "end"), ], ) def test_a_capability_the_mdm_lacks_is_its_sentence( @@ -1183,3 +1184,90 @@ def test_the_default_team_reaches_fleet(fleet: _Fleet, monkeypatch: pytest.Monke 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") + + +def _writes(fleet: _Fleet) -> list[tuple[str, str]]: + return [call for call in fleet.calls if call[0] != "GET"] + + +@pytest.mark.parametrize( + ("hosts", "says"), + [ + (2, "2 phones in the team would lose this Deploy App's certificate"), + (1, "1 phone in the team would lose this Deploy App's certificate"), + (0, "The team has no phones"), + ], +) +def test_end_without_yes_changes_nothing( + fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run, hosts: int, says: str +) -> None: + """It says how many phones would lose the certificate; no challenge is asked for""" + fleet.hosts = [_host(31 + n) for n in range(hosts)] + monkeypatch.delenv("ODMDM_CHALLENGE", raising=False) + monkeypatch.setattr(getpass, "getpass", lambda prompt: pytest.fail("end asks for no challenge")) + + result = run(["end", "--domain", "example.fi"]) + + assert result.exit_code == 0, result.output + assert result.stdout == f"{says}. Nothing was changed: give --yes to end example.fi in Fleet\n" + assert not _writes(fleet) + + +def test_end_with_yes_prints_what_fleet_took_out(fleet: _Fleet, run: Run) -> None: + fleet.hosts = [_host(31, "verified", "OTTER1")] + + result = run(["end", "--domain", "example.fi", "--yes"]) + + assert result.exit_code == 0, result.output + assert result.stdout.splitlines() == [ + ( + "Certificate template rmscep is removed from team rmscep: its phone loses this Deploy App's certificate " + "at its next check-in, up to 15 minutes." + ), + "Certificate authority RMSCEP is removed from Fleet.", + "The team, its phones, their names and their apps stay.", + ] + assert _writes(fleet) == [ + ("DELETE", "/api/latest/fleet/certificates/81"), + ("DELETE", "/api/latest/fleet/certificate_authorities/3"), + ] + + +def test_end_for_a_team_fleet_lacks_changes_nothing(fleet: _Fleet, run: Run) -> None: + result = run(["end", "--domain", "example.fi", "--team", "golden-monkey DeployApp", "--yes"]) + + assert result.exit_code == 1 + assert result.stderr == ( + "Fleet has no team named golden-monkey DeployApp, so nothing was changed. Check the team's name.\n" + ) + assert not _writes(fleet) + + +def test_an_end_stopped_half_way_says_what_was_taken_out(fleet: _Fleet, run: Run) -> None: + answer = fleet.handler + + def refusing(request: Request) -> Response: + if request.method == "DELETE" and "/certificate_authorities/" in request.url.path: + return Response(500, text="database is locked") + return answer(request) + + fleet.handler = refusing # type: ignore[method-assign] + + result = run(["end", "--domain", "example.fi", "--yes"]) + + assert result.exit_code == 1 + assert result.stdout == "Certificate template rmscep is removed from team rmscep, which has no phones.\n" + assert result.stderr.startswith("Fleet refused: DELETE /api/latest/fleet/certificate_authorities/3 answered 500") + + +def test_an_mdm_plugin_older_than_end_says_so(fleet: _Fleet, monkeypatch: pytest.MonkeyPatch, run: Run) -> None: + """It has no end to call, and does not list END in missing""" + monkeypatch.delattr(FleetPlugin, "end") + + result = run(["end", "--domain", "example.fi", "--yes"]) + + assert result.exit_code == 1 + assert ( + result.stderr == "This Fleet plugin cannot end a Deploy App in Fleet: it was made before the connector could.\n" + ) + assert not fleet.calls From 5d2423fcb8087b27fd54d2a02d0ee09c8044c4dc Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:28:39 +0200 Subject: [PATCH 8/9] docs: ending a Deploy App in its MDM, and what Fleet keeps --- README.rst | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index 9855727..785c757 100644 --- a/README.rst +++ b/README.rst @@ -155,6 +155,16 @@ this computer** on the token's card and press **Connect**; or remove the Deploy 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. +Once a deployment is over, end it in the MDM as you remove it: in the Remove dialog tick **Also +end it in Fleet**, or your MDM's name in Fleet's place, and press **End and remove**. The MDM takes +this Deploy App's certificate from the group's phones, at their next check-in, and then the +connector removes the Deploy App as Remove does; until then it changes nothing else in the MDM +for that Deploy App. The group, its phones, their names and their apps stay in the MDM, and the +next Deploy App can be connected to that group. It cannot be undone, so end a Deploy App only when +its deployment is over. The box is there while the MDM is connected and can end a Deploy App; +otherwise the dialog says why. If the MDM refuses on the way, nothing is removed from the +connector, the page says what was already taken out, and ending again finishes the rest. + 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`` @@ -333,6 +343,12 @@ Close enrolment once ``phones`` says every phone has its certificate: a request it closes is refused. The next opening makes a new challenge, so step 2 comes again before the next batch. +Once the deployment is over, ``end`` takes this Deploy App out of the MDM as the page's **End and +remove** does, but leaves the page's settings as they are, and needs no challenge. Without +``--yes`` it changes nothing and says how many phones in the team would lose the certificate:: + + odmdm-connector end --yes + 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 @@ -356,6 +372,7 @@ Commands 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 [ID ...] # ask again; without ids, every named phone that failed + odmdm-connector end --yes # once the deployment is over, take it out of the MDM; without --yes, only say what would change odmdm-connector mdms # the MDMs installed: fleet built in, and any plugins ``name --all`` numbers in enrolment order from one above the highest ``OTTER`` among the @@ -542,6 +559,20 @@ 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. +When a deployment ends +~~~~~~~~~~~~~~~~~~~~~~ + +Ending a Deploy App, **End and remove** on the page or ``end --yes``, deletes two things in Fleet: +the team's certificate template, named as ``ODMDM_KEY_ALIAS`` says, and then the certificate +authority that template was bound to. Fleet then has every phone in the team that holds that +certificate remove it at its next check-in, within about 15 minutes. The team, its phones, their names, its +policy, its apps and its launcher stay, and the next Deploy App can be connected to that team. +Fleet keeps an authority while another team's certificate template still uses it: the connector +then says the authority stays. A team whose template is bound to an authority that serves another +address is left as it is, with both addresses said, and so is Fleet when it has no team of that +name. When the team has no such template, as after an ending that stopped half-way, ending again +deletes the authority that serves this Deploy App's address, never one that serves another. + The template ~~~~~~~~~~~~ @@ -647,8 +678,8 @@ only: 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 +- ``missing`` holds, for each of ``setup``, ``set_challenge``, ``ask_again``, ``send_policy`` and + ``end`` 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 @@ -663,6 +694,13 @@ only: 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. +- ``end(window)`` takes this Deploy App out of the MDM once its deployment is over: the group's + phones lose its certificate, and the group, its phones, their names and their apps stay, ready + for the group's next Deploy App. ``window`` names the Deploy App by its SCEP URL; its challenge + is not used. It answers the lines to show, what was taken out and what stays, and called again + it takes out what an earlier call left, saying so when nothing was left. A plugin made before + ``end`` was in the contract has no ``end`` and does not list it in ``missing``: the connector + says that plugin cannot end a Deploy App, and never calls it. - 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 remove: the command line prints them before the error, the page lists them @@ -674,8 +712,8 @@ only: 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``:: +release that has everything named above but ``end``, which came in 1.7 (a connector before it +never calls it), with the class under the entry point group ``odmdm_connector.mdm``:: [project.entry-points."odmdm_connector.mdm"] = "odmdm_connector_:Mdm" From 46bf4ff2c3f3a8b145fc457c509ebafd429d6f90 Mon Sep 17 00:00:00 2001 From: benjamsf Date: Mon, 23 Nov 2026 23:29:03 +0200 Subject: [PATCH 9/9] chore: bump version to 1.7.0+261123 --- .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 7aeae93..562c5ea 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "1.6.0+261123" +current_version = "1.7.0+261123" 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 5659425..5dc8ffd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "odmdm-connector" -version = "1.6.0+261123" +version = "1.7.0+261123" 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 b77d48c..7a3e5d3 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.6.0+261123" # NOTE Use `bump-my-version` to bump versions correctly +__version__ = "1.7.0+261123" # NOTE Use `bump-my-version` to bump versions correctly diff --git a/tests/test_odmdm_connector.py b/tests/test_odmdm_connector.py index e026256..f27a86d 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.6.0+261123" + assert __version__ == "1.7.0+261123" diff --git a/uv.lock b/uv.lock index c811bde..c1799b1 100644 --- a/uv.lock +++ b/uv.lock @@ -923,7 +923,7 @@ wheels = [ [[package]] name = "odmdm-connector" -version = "1.6.0+261123" +version = "1.7.0+261123" source = { editable = "." } dependencies = [ { name = "keyring" },