A stored admin password that gets no reply offers a new one

A stock repeater or room server does not answer a wrong password, so a password
that the owner changed comes back as no reply, the same as a node that is down.
MeshTerm kept the old password after the silence and tried it again at each
visit with no prompt, so the user could never type the new one (#28).

Now the dialog says that a changed password can be the cause, and offers Cancel
or "New password…". The new password replaces the stored one only when the node
accepts it, so a node that is down keeps its password. Repeater admin, the TX
sweep, and the neighbour fetch of the trace screen share this flow
(ui/admin_login.py). The bulk clock sync names the same two causes on its line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-03 23:34:26 -05:00
1 parent 44a7519681
commit d818331b36
5 files changed
+385 -105

No files matched your search

+193
View File
@@ -0,0 +1,193 @@
# SPDX-License-Identifier: Apache-2.0
"""The admin login of the menu: one flow for each screen that logs in to a remote node.
Repeater admin, the TX sweep, and the neighbour fetch of the trace screen all log in to a
node before they send it a command. Each of them asks for a password when MeshTerm has
none, tells a refusal from a silence, and keeps the password that works. This module is
that flow, so that the screens cannot answer the same outcome in different words.
**A stock node never refuses a password.** The firmware of a repeater (and of a room
server) checks the password and, when it is wrong, sends nothing at all. The companion
sends ``LOGIN_FAILED`` only when a reply arrives that is not "OK". Thus a password that
the owner changed (for example, with a serial console) comes back as
:attr:`~meshterm.core.models.LoginResult.NO_REPLY`, the same as a node that is down. The
credential policy keeps the password after a silence, which is correct for a node that is
down (refer to :meth:`~meshterm.core.admin_store.AdminStore.record`). But before, the
flow then tried the same stale password again at each visit, with no prompt, and the user
had no way to type the new one (GitHub issue 28).
Thus, when a stored password gets no reply, the flow asks the user: ``Cancel``, or
``New password…``. The second button opens the password prompt. The new password
replaces the stored one only when the node accepts it. Thus a node that is down keeps its
password, and a node whose password changed gets the new one in one step.
"""
from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING
from rich.text import Text
if TYPE_CHECKING:
from ..context import AppContext
from ..core.connection import Device
from ..core.models import Contact
#: The title of each dialog of the login.
TITLE = "Admin login"
async def ask_password(ctx: AppContext, node: Contact, *, why: str) -> str | None:
"""Ask for the admin password of ``node`` in a floating prompt.
The prompt floats also when it is the only screen on the stack (the picker dialog
closed before the login started). Then it is a box over a blank base, not a full-frame
prompt.
Args:
ctx: The shared application context (the interactive menu must be running).
node: The node that the password is for.
why: One line under the title that says why the node needs a login.
Returns:
The typed password, or ``None`` (or ``""``) when the user cancels.
"""
return await ctx.ui.session.text(
f"Admin password for {node.name}",
prompt=why,
password=True,
floating=True,
)
def refused_text(node: Contact, *, saved: bool, again: str) -> str:
"""The message for a login that the node refused.
Stock firmware never refuses (refer to the module docstring), but other firmware can.
A refusal is the one result that proves the password wrong, and the credential policy
forgets a stored password for it.
Args:
node: The node that refused.
saved: The password came from the admin store, so the store forgot it.
again: The words for a retry on the screen of the caller (``"try again"``,
``"sweep again"``).
"""
retry = f"{again} to enter a new one."
if saved:
return (
f"{node.name!r} rejected the admin login (wrong password?). "
f"The saved password was cleared; {retry}"
)
return f"{node.name!r} rejected the admin login (wrong password?). {retry.capitalize()}"
def no_reply_text(node: Contact, *, again: str) -> str:
"""The message for a typed password that got no reply.
MeshTerm stored nothing, so nothing changes in the store. The message says that the
password can be the cause, because a stock node does not answer a wrong password.
Args:
node: The node that did not answer.
again: The words for a retry on the screen of the caller.
"""
return (
f"No reply from {node.name} — it may be out of reach, asleep, or busy, or the "
f"password is wrong: a node does not answer a wrong password. "
f"{again.capitalize()} to enter it again."
)
async def offer_new_password(ctx: AppContext, node: Contact) -> bool:
"""Ask what to do after a stored password got no reply: stop, or type a new password.
The silence has two causes that MeshTerm cannot tell apart: the node is down, or its
password changed. Only the user knows which. ``New password…`` is the default, because
the user who opened the flow wants to log in, and the stored password stays until the
new one works.
Args:
ctx: The shared application context (the interactive menu must be running).
node: The node that did not answer.
Returns:
``True`` when the user wants to type a new password.
"""
return bool(
await ctx.ui.dialog(
f"No reply from {node.name} — it may be out of reach, asleep, or busy. Or its "
"admin password changed: a node does not answer a wrong password. The saved "
"password is kept until a new one works.",
[("Cancel", False), ("New password…", True)],
title=TITLE,
default=1,
)
)
async def log_in(
ctx: AppContext,
device: Device,
node: Contact,
*,
why: str,
again: str,
on_record: Callable[[], None] | None = None,
) -> bool:
"""Log in to ``node``: with the stored password silently, or else with a prompt.
The flow:
1. With no stored password, ask for one (:func:`ask_password`).
2. Log in under the busy card, and give the outcome to the credential policy
(:meth:`~meshterm.core.admin_store.AdminStore.record`). The policy stores a password
that works, forgets a refused one, and keeps a stored one after a silence.
3. After a refusal, or after a silence for a typed password, show why, and stop.
4. After a silence for a stored password, offer a new password
(:func:`offer_new_password`). If the user accepts, go back to step 1.
Args:
ctx: The shared application context (the interactive menu must be running).
device: The connected device.
node: The node to log in to.
why: The line of the password prompt that says why the node needs a login.
again: The words for a retry on the screen of the caller (``"try again"``).
on_record: Called after each change to the admin store, before a dialog opens.
Thus a screen that shows the state of the stored password (the TX sweep) is
correct behind the dialog.
Returns:
``True`` when the node accepted the login.
"""
from ..core.models import LoginResult
session = ctx.ui.session
password = ctx.admin_store.get(node)
saved = password is not None
while True:
if password is None:
password = await ask_password(ctx, node, why=why)
if not password:
return False
async with ctx.ui.busy_overlay():
outcome = await device.admin_login(node, password)
ctx.admin_store.record(node, password, outcome)
if on_record is not None:
on_record()
if outcome:
return True
if outcome is LoginResult.REFUSED:
await session.message_dialog(
Text(refused_text(node, saved=saved, again=again), style="err"), title=TITLE
)
return False
if not saved:
await session.message_dialog(
Text(no_reply_text(node, again=again), style="warn"), title=TITLE
)
return False
if not await offer_new_password(ctx, node):
return False
password, saved = None, False
+16 -47
View File
@@ -325,54 +325,21 @@ async def open_repeater_admin(ctx: AppContext) -> dict[str, Any] | None:
async def _login(ctx: AppContext, device: Device, node: Contact) -> bool:
"""Log in to ``node``: with a remembered password silently, or else one floating prompt.
MeshTerm remembers a password that works. It forgets a rejected password, so that the
next try asks for a new one (the convention for remote admin in all the app). But it
forgets only a rejected password. A node that never answered said nothing about the
password, so when there is no answer, MeshTerm keeps the password. Before, if the user
administered a repeater that was down at that time, MeshTerm erased its credential.
The flow is the shared admin login of the menu (refer to
:func:`~meshterm.ui.admin_login.log_in`). MeshTerm remembers a password that works and
forgets a refused one. A node that never answered said nothing about the password, so
MeshTerm keeps the password and offers to replace it. Before, if the user administered
a repeater that was down at that time, MeshTerm erased its credential.
"""
from ..core.models import LoginResult
from .admin_login import log_in
session = ctx.ui.session
password = ctx.admin_store.get(node)
prompted = password is None
if password is None:
password = await session.text(
f"Admin password for {node.name}",
prompt="The node ignores admin commands without a login.",
password=True,
# The picker dialog is closed now, so this prompt is the only screen on the stack.
# The flag keeps it a box over a blank base, not a full-frame prompt.
floating=True,
)
if not password:
return False
async with ctx.ui.busy_overlay():
outcome = await device.admin_login(node, password)
ctx.admin_store.record(node, password, outcome)
if outcome is LoginResult.REFUSED:
await session.message_dialog(
Text(
f"{node.name!r} rejected the admin login (wrong password?). "
+ ("" if prompted else "The saved password was cleared; ")
+ "try again to enter a new one.",
style="err",
),
title="Admin login",
)
return False
if not outcome:
await session.message_dialog(
Text(
f"No reply from {node.name} — it may be out of reach, asleep, or busy. "
+ ("" if prompted else "The saved password was kept; ")
+ "try again when it answers.",
style="warn",
),
title="Admin login",
)
return False
return True
return await log_in(
ctx,
device,
node,
why="The node ignores admin commands without a login.",
again="try again",
)
async def _admin_session(ctx: AppContext, device: Device, node: Contact) -> dict[str, Any]:
@@ -1206,7 +1173,9 @@ async def _quiet_login(ctx: AppContext, device: Device, node: Contact) -> tuple[
if outcome is LoginResult.REFUSED:
return False, "login refused; the saved password was cleared"
if not outcome:
return False, "no reply to the login"
# A stock node does not answer a wrong password, so a changed password also ends
# here (refer to :mod:`meshterm.ui.admin_login`).
return False, "no reply to the login — out of reach, or its password changed"
return True, ""
+25 -14
View File
@@ -1736,6 +1736,7 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
)
from ..services.path_probe import ProbeCandidate, ProbeOutcome, probe_paths
from ..services.topology import MeshTopology, build_topology, collapse_width, is_path_hash
from .admin_login import ask_password, no_reply_text, offer_new_password, refused_text
from .path_composer import FetchNeighbours, PathComposerScreen
from .surface import TuiUi
from .tui import CANCEL, Choice, SelectScreen, Separator
@@ -1878,7 +1879,9 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
title="No destination hash",
)
async def fetch_neighbours_via(repeater: Contact, repeater_id: str) -> bool:
async def fetch_neighbours_via(
repeater: Contact, repeater_id: str, *, ask: bool = False
) -> bool:
"""Log in to a repeater, get its neighbour table, and store the snapshot.
The fetch action of the composer comes here. The password comes from the admin
@@ -1887,20 +1890,28 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
spinner dialog with Abort. Each outcome closes its own ``runs`` row. A refused
login also forgets the stored password, so the next attempt asks again.
A stock repeater does not answer a wrong password. Thus, when a stored password
gets no reply, the function offers a new password, as the shared login of the menu
does (refer to :mod:`meshterm.ui.admin_login`). If the user accepts, the function
runs again with ``ask``.
Args:
repeater: The repeater contact to query (it has the public key).
repeater_id: Its canonical id, the key under which the snapshot is stored.
ask: Ask for a password, also when one is stored. The stored password stays
until the typed one works.
Returns:
``True`` when new neighbour links were stored (the caller must build the
topology again). ``False`` on a cancel, a failure, or an empty table.
"""
password = ctx.admin_store.get(repeater)
password = None if ask else ctx.admin_store.get(repeater)
saved = password is not None
# Set when a stored password got no reply: then a new password is offered.
stale = False
if password is None:
password = await session.text(
f"Admin password for {repeater.name}",
prompt="The repeater ignores neighbour requests without an admin login.",
password=True,
password = await ask_password(
ctx, repeater, why="The repeater ignores neighbour requests without an admin login."
)
if not password:
return False
@@ -1917,18 +1928,14 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
dialog.status = f"logging in to {repeater.name}…"
async def work() -> list[NeighbourInfo]:
nonlocal stale
outcome = await device.admin_login(repeater, password)
ctx.admin_store.record(repeater, password, outcome)
if outcome is LoginResult.REFUSED:
raise DeviceAuthenticationError(
f"{repeater.name!r} rejected the admin login (wrong password?). "
"The saved password was cleared; retry to enter a new one."
)
raise DeviceAuthenticationError(refused_text(repeater, saved=saved, again="retry"))
if not outcome:
raise DeviceCommandError(
f"No reply from {repeater.name} — it may be out of reach, asleep, or "
"busy. The saved password was kept; retry when it answers."
)
stale = saved
raise DeviceCommandError(no_reply_text(repeater, again="retry"))
dialog.status = "fetching the neighbour table…"
session.invalidate()
return await device.fetch_neighbours(repeater)
@@ -1970,6 +1977,10 @@ async def _open_session(ctx: AppContext, target: str | None, *, initial_spec: st
# ``work`` and AdminStore.record). Thus an exception here is only a message
# to show.
ctx.repo.finish_run(run_id, "error", {"error": str(error) or type(error).__name__})
if stale:
if await offer_new_password(ctx, repeater):
return await fetch_neighbours_via(repeater, repeater_id, ask=True)
return False
await session.message_dialog(Text(str(error), style="err"), title="Fetch neighbours")
return False
ctx.repo.record_neighbours(run_id, repeater_id, entries)
+17 -38
View File
@@ -46,7 +46,7 @@ from rich.table import Table
from rich.text import Text
from ..core.connection import REMOTE_TX_MAX, REMOTE_TX_MIN
from ..core.models import Contact, LoginResult, TraceResult, TxLevelResult, TxOptResult
from ..core.models import Contact, TraceResult, TxLevelResult, TxOptResult
from ..services import trace_runner, tx_optimizer
from ..services.topology import build_topology, render_custom_spec
from .menus import icon_lane, icon_mark
@@ -657,6 +657,7 @@ async def open_tx_optimize(
RuntimeError: If the caller calls it outside the interactive menu (there is no
full-screen session).
"""
from .admin_login import log_in
from .path_composer import AUTO_SPEC, PathComposerScreen
from .surface import TuiUi
from .tui import CANCEL, Choice, SelectScreen
@@ -850,44 +851,22 @@ async def open_tx_optimize(
nonlocal logged_in
if logged_in:
return True
password = ctx.admin_store.get(admin_node)
if password is None:
password = await session.text(
f"Admin password for {admin_node.name}",
prompt="The repeater ignores tuning commands without an admin login.",
password=True,
)
if not password:
return False
async with ctx.ui.busy_overlay():
outcome = await device.admin_login(admin_node, password)
ctx.admin_store.record(admin_node, password, outcome)
if outcome is LoginResult.REFUSED:
def show_login() -> None:
screen.login_text = login_text()
await session.message_dialog(
Text(
f"{admin_node.name!r} rejected the admin login (wrong password?). "
"The saved password was cleared; sweep again to enter a new one.",
style="err",
),
title="Admin login",
)
return False
if not outcome:
# No reply is not a denial. The password stays for the next attempt.
screen.login_text = login_text()
await session.message_dialog(
Text(
f"No reply from {admin_node.name} — it may be out of reach, asleep, "
"or busy. The saved password was kept; sweep again when it answers.",
style="warn",
),
title="Admin login",
)
return False
logged_in = True
screen.login_text = login_text()
return True
# The shared login of the menu. It offers a new password when the stored one gets
# no reply (refer to :mod:`meshterm.ui.admin_login`).
logged_in = await log_in(
ctx,
device,
admin_node,
why="The repeater ignores tuning commands without an admin login.",
again="sweep again",
on_record=show_login,
)
show_login()
return logged_in
async def apply_dialog() -> None:
"""Offer the winner in a floating dialog. If the user selects Apply, write it."""
+134 -6
View File
@@ -524,12 +524,13 @@ async def _step_until(predicate, *, limit: int = 200):
return value
async def _run_login(ctx, node): # noqa: ANN001
async def _run_login(ctx, node, *, answer: object = "ok"): # noqa: ANN001
"""Run ``ui.repeater_admin._login`` to its end, and read and close its dialog.
Returns the result of the flow and the words that it showed on the screen. Both are
important. What happens to the password is one half of the fix. The other half is that
the flow does not tell the user that a password was wrong when it was not.
the flow does not tell the user that a password was wrong when it was not. ``answer``
is the value of the button that the test presses.
"""
from meshterm.ui.repeater_admin import _login
from meshterm.ui.surface import TuiUi
@@ -553,7 +554,7 @@ async def _run_login(ctx, node): # noqa: ANN001
if dialog is not None:
prompt = dialog._prompt
shown = prompt.plain if hasattr(prompt, "plain") else str(prompt)
dialog.resolve("ok")
dialog.resolve(answer)
return await task, shown
finally:
if not task.done():
@@ -561,14 +562,18 @@ async def _run_login(ctx, node): # noqa: ANN001
async def test_the_admin_flow_says_no_reply_and_keeps_the_password(ctx) -> None: # noqa: ANN001
"""The screen that JP was on. It must not report a wrong password, and must not clear it."""
"""The screen that JP was on. It must not report a refusal, and must not clear the password.
The dialog offers a new password, because a stock node does not answer a wrong
password either. Cancel leaves the stored password as it was.
"""
node = await _mock_node(ctx, down=True)
ok, shown = await _run_login(ctx, node)
ok, shown = await _run_login(ctx, node, answer=False)
assert ok is False
assert "No reply" in shown and "kept" in shown
assert "wrong password" not in shown
assert "rejected" not in shown
assert ctx.admin_store.get(node) == "admin"
@@ -584,6 +589,129 @@ async def test_the_admin_flow_still_clears_a_password_the_node_rejected(ctx) ->
assert ctx.admin_store.get(node) is None
class _StockNode:
"""A device whose node answers only its current password, as stock firmware does.
A wrong password gets no reply, never a refusal (GitHub issue 28). ``tried`` lists the
passwords in the order of the logins.
"""
def __init__(self, password: str) -> None:
self.password = password
self.tried: list[str] = []
async def admin_login(self, node: Contact, password: str) -> LoginResult: # noqa: ARG002
self.tried.append(password)
await asyncio.sleep(0)
return LoginResult.ACCEPTED if password == self.password else LoginResult.NO_REPLY
async def _top(ctx, kind): # noqa: ANN001, ANN202
"""The top screen of the session once it is a ``kind``, or ``None``."""
session = ctx.ui.session
return await _step_until(lambda: session.top if isinstance(session.top, kind) else None)
async def test_a_changed_password_is_offered_and_replaced(ctx) -> None: # noqa: ANN001
"""The owner changed the password. The stored one gets silence, and the user types the new one.
Before, the flow showed "No reply" and kept the old password, and each later visit
tried the old password again with no prompt. The user had no way to type the new one.
"""
from meshterm.ui.admin_login import log_in
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.prompt import ButtonDialog, TextScreen
from meshterm.ui.tui.session import TuiSession
ctx.ui = TuiUi(TuiSession())
ctx.admin_store.remember(_NODE, "old")
device = _StockNode("new")
task = asyncio.ensure_future(log_in(ctx, device, _NODE, why="Log in.", again="try again"))
try:
offer = await _top(ctx, ButtonDialog)
assert offer is not None, "a silence after a stored password offers a choice"
assert [label for label, _ in offer._buttons] == ["Cancel", "New password…"]
assert offer._index == 1, "New password… is the default"
offer.resolve(True)
prompt = await _top(ctx, TextScreen)
assert prompt is not None, "the choice opens the password prompt"
prompt.resolve("new")
ok = await task
finally:
if not task.done():
task.cancel()
assert ok is True
assert device.tried == ["old", "new"]
assert ctx.admin_store.get(_NODE) == "new"
async def test_a_new_password_that_also_gets_no_reply_keeps_the_old_one(ctx) -> None: # noqa: ANN001
"""The node can be down after all. A typed password replaces the stored one only if it works."""
from meshterm.ui.admin_login import log_in
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.prompt import ButtonDialog, TextScreen
from meshterm.ui.tui.session import TuiSession
ctx.ui = TuiUi(TuiSession())
ctx.admin_store.remember(_NODE, "old")
device = _StockNode("unknown")
task = asyncio.ensure_future(log_in(ctx, device, _NODE, why="Log in.", again="try again"))
try:
(await _top(ctx, ButtonDialog)).resolve(True)
(await _top(ctx, TextScreen)).resolve("typo")
notice = await _top(ctx, ButtonDialog)
assert notice is not None
shown = notice._prompt.plain
assert "No reply" in shown and "wrong password" in shown
assert "Try again to enter it again." in shown
notice.resolve("ok")
ok = await task
finally:
if not task.done():
task.cancel()
assert ok is False
assert device.tried == ["old", "typo"]
assert ctx.admin_store.get(_NODE) == "old"
async def test_a_typed_password_with_no_reply_asks_nothing_more(ctx) -> None: # noqa: ANN001
"""With no stored password, there is nothing to replace. The flow explains and stops."""
from meshterm.ui.admin_login import log_in
from meshterm.ui.surface import TuiUi
from meshterm.ui.tui.prompt import ButtonDialog, TextScreen
from meshterm.ui.tui.session import TuiSession
ctx.ui = TuiUi(TuiSession())
device = _StockNode("unknown")
task = asyncio.ensure_future(log_in(ctx, device, _NODE, why="Log in.", again="sweep again"))
try:
(await _top(ctx, TextScreen)).resolve("typo")
notice = await _top(ctx, ButtonDialog)
assert [label for label, _ in notice._buttons] == ["OK"]
assert "Sweep again to enter it again." in notice._prompt.plain
notice.resolve("ok")
ok = await task
finally:
if not task.done():
task.cancel()
assert ok is False
assert ctx.admin_store.get(_NODE) is None
def test_a_refusal_message_starts_its_sentences_with_a_capital() -> None:
"""A typed password has nothing to clear. The message once read "(wrong password?). try"."""
from meshterm.ui.admin_login import refused_text
typed = refused_text(_NODE, saved=False, again="try again")
saved = refused_text(_NODE, saved=True, again="try again")
assert typed.endswith("(wrong password?). Try again to enter a new one.")
assert saved.endswith("The saved password was cleared; try again to enter a new one.")
# --- no call site decides this locally again --------------------------------------------