Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20467,3 +20467,39 @@ at capacity instead of queueing (a small model handles "it starts when a
slot frees" better than "try again"); starting a writer from the latest
checkpoint instead of `HEAD` (it would need the checkpoint code reviewed;
the spawn note says uncommitted edits are not in the child's worktree).

## 2026-11-24 — TD-5301: what no phone permission opens (Class B)

**Decision:** four acts are refused from a paired phone (or the legacy
token) whatever it was granted, with `loopback_only` and no switch:
releasing the computer-use stop (TD-5297), `shutdown`, sending a saved key
to a server it does not already go to, and pointing the mail server
elsewhere without typing the password. The two read off the message stay
in `phone_verbs.never_from_a_phone`. The two that depend on what is saved
live in `core/tstd/phone_never.py`, which `Hub.intercept` asks before the
permission check, through a callable the daemon passes with its live
config, so `peer_policy.check` stays a pure table.

"Another server" reuses TD-5182's rule (`key_hosts.key_refusal`): a key's
own host, or, for a key saved without one, the URLs of the models it is
bound to, with a server on this computer allowed. `set_credential` is
refused when it changes or clears an existing key's host so the key would
reach a new origin; `set_tier_credential` when it binds a host-less key to
a model elsewhere. A new key (no id yet) and `set_api_key` (the phone types
the key) are not a move. For mail, any SMTP host other than the saved one,
compared case-blind, needs `password` in the same message.

**Found at runtime before the change** (a live test daemon, a paired phone):
`set_email_notify` with a new host and no password was accepted with no
grant; `set_credential` moved the saved OpenRouter key's host once
`models_and_keys` was on; `shutdown` stopped the daemon. `add_model` reusing
a saved key at another URL was already refused for every client (TD-5182).

**Rationale:** each sends something the person saved at the computer (a
key, a password) somewhere they never chose, or leaves the computer out of
reach; none is undone by revoking the phone. Asking before the grant check
gives the same answer with or without a grant.

**Rejected:** a sixth capability for these (the owner chose "never"); and
refusing every `set_credential` with a `base_url`, which would also block
saving a new key with its own host.
204 changes: 204 additions & 0 deletions core/tests/test_phone_never.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
"""What no phone permission opens (owner decision #5, TD-5301).

Checked against a running daemon before the change: a paired phone could
point the mail server elsewhere with no grant and no password, so the
saved password went to the new server on the next send; with "Adding
models and keys" on it could move a saved key's host; and it could shut
the daemon down. Each is now refused from a phone with any grant, and
stays the computer's own.
"""

from __future__ import annotations

import asyncio
import json
from pathlib import Path
from typing import Any

import pytest

from tests.test_add_model import _stop
from tests.test_mcp_peer import _drain, _fresh, _pair
from tests.test_models_on_phone import _seeded
from tests.test_peer_policy import (
LOOPBACK_PLAIN,
PHONE_PLAIN,
PHONE_VIEWER,
PLAIN_REMOTE,
_code,
_msg,
)
from tests.test_preset_engine import _config
from tstd.config import CredentialConfig, ModelConfig
from tstd.peer_policy import check
from tstd.phone_never import COMPUTER_ONLY, KEY_ELSEWHERE, MAIL_PASSWORD, never_refusal

EVERY_GRANT = frozenset(
{"mcp_servers", "approval_switches", "models_and_keys", "computer_use", "unattended_runs"}
)
GRANT_KEYS = {"type": "set_phone_permission", "capability": "models_and_keys", "enabled": True}


def _with_mail(config: ModelConfig, host: str = "smtp.first.example") -> ModelConfig:
config.notify.email.host = host
config.notify.email.username = "me"
return config


class TestTheRules:
def test_shutdown_is_the_computers(self) -> None:
msg = _msg("shutdown")
for phone in (PHONE_VIEWER, PHONE_PLAIN, PLAIN_REMOTE):
assert _code(check(msg, phone, bridged=False, grants=EVERY_GRANT)) == "loopback_only"
assert check(msg, LOOPBACK_PLAIN, bridged=False) is None

def test_releasing_the_stop_stays_refused(self, tmp_path: Path) -> None:
config = _config(tmp_path)
assert never_refusal(_msg("set_cu_kill", killed=False), config) == COMPUTER_ONLY
assert never_refusal(_msg("set_cu_kill", killed=True), config) is None

@pytest.mark.parametrize(
("fields", "refused"),
[
({"host": "smtp.elsewhere.example"}, True),
({"host": "SMTP.First.Example "}, False),
({"host": "smtp.first.example", "port": 465, "security": "tls"}, False),
({"host": "smtp.elsewhere.example", "password": "typed"}, False),
({"host": "smtp.elsewhere.example", "method": "microsoft"}, False),
({"host": "", "username": "someone-else"}, True),
],
)
def test_a_new_mail_server_needs_the_password(
self, tmp_path: Path, fields: dict[str, Any], refused: bool
) -> None:
config = _with_mail(_config(tmp_path))
msg = _msg("set_email_notify", **{"enabled": True, "username": "me", **fields})
assert never_refusal(msg, config) == (MAIL_PASSWORD if refused else None)

@pytest.mark.parametrize(
("base_url", "refused"),
[
("https://elsewhere.example/v1", True),
("", True), # cleared: the key would go to each bound model's own URL
("https://openrouter.ai/api/v1/", False),
("https://OPENROUTER.ai/other/path", False),
(None, False), # a rename
],
)
def test_a_saved_keys_host(self, tmp_path: Path, base_url: str | None, refused: bool) -> None:
config = _config(tmp_path)
# A model bound to the key whose own URL is another server.
config.presets["budget"].brain.base_url = "https://models.example.com/v1"
fields: dict[str, Any] = {"name": "OpenRouter", "credential": "openrouter"}
if base_url is not None:
fields["base_url"] = base_url
assert never_refusal(_msg("set_credential", **fields), config) == (
KEY_ELSEWHERE if refused else None
)

def test_a_new_key_has_nothing_to_move(self, tmp_path: Path) -> None:
config = _config(tmp_path)
msg = _msg("set_credential", name="Fresh", base_url="https://elsewhere.example/v1")
assert never_refusal(msg, config) is None

def test_binding_a_key_without_a_host(self, tmp_path: Path) -> None:
config = _config(tmp_path)
config.credentials["lab"] = CredentialConfig(name="Lab")
config.presets["local"].brain.credential = "lab"
config.presets["budget"].brain.credential = None

def bind(preset: str) -> str | None:
msg = _msg("set_tier_credential", preset=preset, tier="brain", credential="lab")
return never_refusal(msg, config)

assert bind("local") is None # where it already goes
assert bind("vllm") is None # another server on this computer
assert bind("budget") == KEY_ELSEWHERE # a hosted server it never went to
unbind = _msg("set_tier_credential", preset="budget", tier="brain", credential="")
assert never_refusal(unbind, config) is None

def test_a_key_with_a_host_goes_there_whatever_it_is_bound_to(self, tmp_path: Path) -> None:
config = _config(tmp_path)
msg = _msg("set_tier_credential", preset="local", tier="brain", credential="openrouter")
assert never_refusal(msg, config) is None


async def _ask_phone(phone: Any, msg: dict[str, Any]) -> dict[str, Any]:
await _drain(phone)
await phone.send(json.dumps(msg))
return dict(json.loads(await asyncio.wait_for(phone.recv(), 5)))


class TestOverTheWire:
async def test_the_mail_server_and_a_keys_host_stay_put(self, tmp_path: Path) -> None:
daemon, task, ws = await _seeded(tmp_path)
phone, _ = await _pair(daemon)
first = {"type": "set_email_notify", "enabled": True, "host": "smtp.first.example"}
moved = {**first, "host": "smtp.elsewhere.example"}
key = {"type": "set_credential", "name": "OpenRouter", "credential": "openrouter"}
try:
await _fresh(ws, {**first, "username": "me"})
reply = await _ask_phone(phone, {**moved, "username": "me"})
assert (reply["type"], reply["code"]) == ("error", "loopback_only"), reply
assert reply["message"] == MAIL_PASSWORD
assert daemon.config.notify.email.host == "smtp.first.example"

await _fresh(ws, GRANT_KEYS)
reply = await _ask_phone(phone, {**key, "base_url": "https://elsewhere.example/v1"})
assert (reply["type"], reply["message"]) == ("error", KEY_ELSEWHERE), reply
assert (
daemon.config.credentials["openrouter"].base_url == "https://openrouter.ai/api/v1"
)
# A rename with the grant still works.
done = await _fresh(phone, {**key, "name": "Router"})
assert done["type"] == "setup_state", done
assert daemon.config.credentials["openrouter"].name == "Router"
# The computer itself does both.
await _fresh(ws, {**key, "base_url": "https://elsewhere.example/v1"})
assert (
daemon.config.credentials["openrouter"].base_url == "https://elsewhere.example/v1"
)
await _fresh(ws, {**moved, "username": "me"})
assert daemon.config.notify.email.host == "smtp.elsewhere.example"
finally:
await phone.close()
await _stop(task, ws)

async def test_typing_the_password_moves_the_mail_server(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
stored: list[str] = []

async def store(password: str) -> None:
stored.append(password)

monkeypatch.setattr("tstd.keychain.store_smtp_password", store)
daemon, task, ws = await _seeded(tmp_path)
phone, _ = await _pair(daemon)
try:
change = {
"type": "set_email_notify",
"enabled": True,
"host": "smtp.elsewhere.example",
"username": "me",
"password": "typed-on-the-phone",
}
done = await _fresh(phone, change)
assert done["type"] == "setup_state", done
assert daemon.config.notify.email.host == "smtp.elsewhere.example"
assert stored == ["typed-on-the-phone"]
finally:
await phone.close()
await _stop(task, ws)

async def test_a_phone_cannot_shut_the_daemon_down(self, tmp_path: Path) -> None:
daemon, task, ws = await _seeded(tmp_path)
phone, _ = await _pair(daemon)
try:
reply = await _ask_phone(phone, {"type": "shutdown"})
assert (reply["type"], reply["code"]) == ("error", "loopback_only"), reply
await asyncio.sleep(0.2)
assert not task.done()
finally:
await phone.close()
await _stop(task, ws)
2 changes: 2 additions & 0 deletions core/tstd/daemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@
from .notify.slack import send as send_slack_notify
from .notify.telegram import schedule as schedule_telegram_notify
from .peer_policy import outbound_event, service_hosts
from .phone_never import never_refusal
from .phone_permissions import (
APPROVAL_SWITCHES,
COMPUTER_USE,
Expand Down Expand Up @@ -1330,6 +1331,7 @@ def __init__(
self._handle_list_sessions,
policy=dial_policy,
phone_grants=self.phone_store.live,
phone_never=lambda msg: never_refusal(msg, self.config),
)
self._cu_server: Any = None
# TD-4835: keychain presence cache — see _credential_is_stored.
Expand Down
9 changes: 9 additions & 0 deletions core/tstd/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
ListMachines,
ReconnectMachine,
RemoveMachine,
build_error,
scrub_wire_json,
)
from .ws import WebSocketServer
Expand Down Expand Up @@ -89,11 +90,15 @@ def __init__(
policy: DialPolicy | None = None,
timings: Timings = DEFAULT_TIMINGS,
phone_grants: Callable[[], Collection[str]] | None = None,
phone_never: Callable[[ClientMessage], str | None] | None = None,
) -> None:
self._ws = ws_server
# TD-5279: the phone permissions switched on right now. Without a
# source there are none, so every opt-in verb is refused.
self._phone_grants = phone_grants
# TD-5301: what no grant opens to a phone, read against the live
# config. Asked first, so the answer does not depend on a grant.
self._phone_never = phone_never
self._own_session_list = own_session_list
self.registry = MachineRegistry(data_dir)
self.registry.load()
Expand Down Expand Up @@ -131,6 +136,10 @@ async def intercept(self, msg: ClientMessage, connection: Any) -> object:
peer = self._ws.peer_view(connection)
sid = message_session_id(msg)
bridged = sid is not None and is_bridged(sid)
if peer.remote and not peer.machine and self._phone_never is not None:
never = self._phone_never(msg)
if never is not None:
return build_error("loopback_only", never, session_id=sid, in_reply_to=msg.type)
grants = self._phone_grants() if self._phone_grants is not None else ()
refusal = check(msg, peer, bridged=bridged, grants=grants)
if refusal is not None:
Expand Down
84 changes: 84 additions & 0 deletions core/tstd/phone_never.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""What no phone permission opens (owner decision #5, TD-5301).

A paired phone acts as the person, but some acts are the computer's
whatever a phone was granted. They are hard refusals with no switch:

- releasing the computer-use stop (TD-5297) and ``shutdown``: both
pure, read off the message (``phone_verbs.never_from_a_phone``);
- sending a saved key to a server it does not already go to;
- changing the mail server without typing the mail password again, which
would send the saved password to the new server.

The last two depend on what is saved, so they are read against the live
config here, before the permission check: a phone that has the grant
gets the same answer as one that does not. ``add_model`` and the model
list already keep a saved key on its own server for every client
(TD-5182); this covers the two verbs that change where a key goes.
"""

from __future__ import annotations

from .config import ModelConfig, credential_base_url
from .key_hosts import key_hosts, key_refusal, origin
from .phone_verbs import never_from_a_phone
from .protocol import ClientMessage, SetCredential, SetEmailNotify, SetTierCredential

COMPUTER_ONLY = "Only the computer itself can do that."
KEY_ELSEWHERE = (
"A phone cannot send a saved key to another server. Type the key for that "
"server instead, or make this change at the computer."
)
MAIL_PASSWORD = (
"To change the mail server from a phone, type the mail password again. "
"The saved one is not sent to a new server."
)


def never_refusal(msg: ClientMessage, config: ModelConfig) -> str | None:
"""Why a phone may never send *msg*, or None. The same with any grant."""
if never_from_a_phone(msg):
return COMPUTER_ONLY
if isinstance(msg, SetCredential):
return KEY_ELSEWHERE if _moves_key(msg, config) else None
if isinstance(msg, SetTierCredential):
return KEY_ELSEWHERE if _binds_elsewhere(msg, config) else None
if isinstance(msg, SetEmailNotify):
return MAIL_PASSWORD if _new_mail_host(msg, config) else None
return None


def _moves_key(msg: SetCredential, config: ModelConfig) -> bool:
"""A saved key's own host changed or cleared. A new key has no secret yet."""
if msg.base_url is None or not msg.credential or msg.credential not in config.credentials:
return False
hosts = {origin(url) for url in key_hosts(config, msg.credential)}
after = msg.base_url.strip()
if not after:
# Cleared: the key goes to the URL of each model it is bound to.
cleared = config.model_copy(deep=True)
cleared.credentials[msg.credential].base_url = None
return any(origin(url) not in hosts for url in key_hosts(cleared, msg.credential))
return origin(after) not in hosts


def _binds_elsewhere(msg: SetTierCredential, config: ModelConfig) -> bool:
"""A key saved without a host, bound to a model on a server it is not sent to.

A key saved with a host goes there whatever it is bound to.
"""
credential = msg.credential.strip()
if not credential or credential_base_url(config, credential) is not None:
return False
preset = config.presets.get(msg.preset)
tiers = preset.tier_map() if preset is not None else {}
tier = next((t for name, t in tiers.items() if name == msg.tier), None)
if tier is None:
return False # the handler refuses an unknown model itself
return key_refusal(config, credential, tier.base_url) is not None


def _new_mail_host(msg: SetEmailNotify, config: ModelConfig) -> bool:
"""SMTP to a different server with the saved password, not a typed one."""
if msg.method != "smtp" or msg.password:
return False
return msg.host.strip().lower() != config.notify.email.host.strip().lower()
Loading
Loading