Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(control-api): validate parked config writes when proposed

rubenluetke10-beepecf6944e7256
diff --git a/docs/jarvis-control-api.md b/docs/jarvis-control-api.md
index 0ccb01ae45..10b920409a 100644
--- a/docs/jarvis-control-api.md
+++ b/docs/jarvis-control-api.md
@@ -99,6 +99,22 @@ subscriber calls `BrainManager.set_reply_language`) with **no restart**.
`needs_confirmation=true` + a `pending_id`; confirm to apply. `requires_restart`
is reported honestly (e.g. STT re-init).
+### Status codes for config writes
+
+| Status | When |
+|---|---|
+| 200 | Applied (SAFE), parked for confirmation (ASK, with `pending_id`), or confirmed and applied |
+| 400 | Path is not in the allowlist, or `pending_id` is not a valid id |
+| 403 | Protected path (secrets, safety lists) |
+| 410 | `pending_id` expired (5 minutes) or was already confirmed or rejected |
+| 422 | The value fails schema validation. An ASK-tier value is validated when it is proposed, so `PUT /config` refuses it before any `pending_id` exists |
+| 500 | Backup, write, reload or rollback failed. The detail is a fixed sentence; the cause is in the Jarvis log |
+
+`POST /config/confirm` answers 200 only when the change landed. A failed
+apply is an error status, never `200` with `ok: false`. A confirmed or failed
+entry is consumed either way, so propose the change again to retry.
+`POST /config/reject` is idempotent and answers 200 for an unknown id.
+
## Voice path
"Jarvis, switch your language to English" works end-to-end without this HTTP
diff --git a/jarvis/core/self_mod/pending.py b/jarvis/core/self_mod/pending.py
index 4979b6c66a..f7e83ffbad 100644
--- a/jarvis/core/self_mod/pending.py
+++ b/jarvis/core/self_mod/pending.py
@@ -110,8 +110,8 @@ class PendingMutationStore:
"""Prepare a mutation — or confirm immediately for SAFE-tier paths.
Raises `AllowlistViolationError` / `SecretAccessError` from the
- allowlist check and (for SAFE auto-confirm) `PreValidateError` from
- the writer. The tool layer converts these into a
+ allowlist check and `PreValidateError` from the writer — for an
+ auto-applied write and for a parked one alike. The tool layer converts these into a
`ToolResult(success=False, ...)` response.
"""
spec: MutableSpec = SelfModRegistry.require_spec(request.path)
@@ -138,6 +138,10 @@ class PendingMutationStore:
description=spec.description,
)
+ # Refuse a value the schema rejects now, while the caller can still
+ # correct it — not after the user confirmed a change that cannot land.
+ self._writer.prevalidate(request)
+
pending = PendingMutation(
id=request.correlation_id,
path=request.path,
diff --git a/jarvis/core/self_mod/writer.py b/jarvis/core/self_mod/writer.py
index 202e5c730d..d1d8ee5522 100644
--- a/jarvis/core/self_mod/writer.py
+++ b/jarvis/core/self_mod/writer.py
@@ -175,6 +175,38 @@ class AtomicConfigWriter:
) from exc
return self._read_dotted(doc, path)
+ def prevalidate(self, request: MutationRequest) -> None:
+ """Run step 5 (pre-validate) alone, without backup or write.
+
+ For a mutation that is parked until the user confirms it: a value the
+ schema rejects must be refused when it is proposed, not after the user
+ said yes. Raises `PreValidateError` (audited like the real step 5).
+ A config that cannot be read or parsed right now is not the request's
+ fault; that case returns quietly and `mutate()` reports it on confirm.
+ """
+ try:
+ raw = self._config_path.read_text(encoding="utf-8")
+ if raw.startswith(self._BOM):
+ raw = raw[len(self._BOM):]
+ doc = tomlkit.parse(raw)
+ except Exception as exc: # noqa: BLE001 — mutate() owns the read/parse failure
+ _LOG.debug("prevalidate skipped, config unreadable: %s", exc)
+ return
+ old_value = self._read_dotted(doc, request.path)
+ self._apply_dotted(doc, request.path, request.new_value)
+ try:
+ JarvisConfig.model_validate(doc.unwrap())
+ except (PydanticValidationError, ValueError, TypeError) as exc:
+ self._audit_failure(
+ request,
+ old_value=old_value,
+ error=f"validate_failed: {_summarize_error(exc)}",
+ )
+ raise PreValidateError(
+ f"Pre-validate for '{request.path}' = {request.new_value!r} "
+ f"failed: {_summarize_error(exc)}"
+ ) from exc
+
def mutate(self, request: MutationRequest) -> MutationResult:
"""Plan-§7.2 pipeline.
diff --git a/jarvis/ui/web/control_routes.py b/jarvis/ui/web/control_routes.py
index 4eac595a0b..f8bfa8d353 100644
--- a/jarvis/ui/web/control_routes.py
+++ b/jarvis/ui/web/control_routes.py
@@ -40,11 +40,17 @@ from jarvis.core.self_mod import (
SelfModAudit,
SelfModRegistry,
)
+from jarvis.core.self_mod.errors import (
+ ProviderSwitchLockedError,
+ SelfModError,
+ TypeMismatchError,
+)
from jarvis.core.self_mod.pending import PendingMutationStore
from jarvis.ui.web.control_auth import (
require_control_key,
require_control_key_or_session,
)
+from jarvis.ui.web.error_text import internal_error
log = logging.getLogger("jarvis.control")
@@ -215,6 +221,27 @@ def get_config(path: str, request: Request) -> dict[str, Any]:
}
+def _self_mod_http_error(exc: SelfModError) -> HTTPException:
+ """Map a failed self-mod step to an HTTP status the caller can act on.
+
+ The request's own faults keep their message (it names the path and the
+ reason); a failed backup, write, reload or rollback is the server's
+ problem and gets a stable sentence, with the detail in the log.
+ """
+ if isinstance(exc, (SecretAccessError, ProviderSwitchLockedError)):
+ return HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc))
+ if isinstance(exc, AllowlistViolationError):
+ return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
+ if isinstance(exc, (PreValidateError, TypeMismatchError)):
+ return HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
+ )
+ return HTTPException(
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ detail=internal_error("config write", exc, logger=log),
+ )
+
+
def _apply_config_write(
store: PendingMutationStore, path: str, value: Any, reason: str | None
) -> dict[str, Any]:
@@ -227,18 +254,16 @@ def _apply_config_write(
)
try:
pending = store.create(request_obj)
- except SecretAccessError as exc:
- raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc
- except AllowlistViolationError as exc:
- raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
- except PreValidateError as exc:
- raise HTTPException(
- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
- ) from exc
+ except SelfModError as exc:
+ raise _self_mod_http_error(exc) from exc
return _pending_envelope(pending)
[email protected]("/config", dependencies=[Depends(require_control_key)], openapi_extra={"x-jarvis-dangerous": True})
+ "/config",
+ dependencies=[Depends(require_control_key)],
+ openapi_extra={"x-jarvis-dangerous": True},
+)
def put_config(body: ConfigWriteBody, request: Request) -> dict[str, Any]:
store = _pending_store(request)
return _apply_config_write(store, body.path, body.value, body.reason)
@@ -255,6 +280,10 @@ def confirm_config(body: PendingIdBody, request: Request) -> dict[str, Any]:
result = store.confirm(mutation_id)
except KeyError as exc:
raise HTTPException(status_code=410, detail="pending mutation expired or unknown") from exc
+ except SelfModError as exc:
+ # The entry is consumed either way; a failed apply is an error status,
+ # never a 200 the caller would read as "applied".
+ raise _self_mod_http_error(exc) from exc
return {
"ok": result.ok,
"applied": result.ok,
@@ -290,13 +319,41 @@ def put_language(body: LanguageBody, request: Request) -> dict[str, Any]:
mirrors the input language). Both are SAFE -> applied immediately, and the
interface switches live in the open UI via the ConfigReloaded broadcast."""
store = _pending_store(request)
- result = _apply_config_write(
- store, "brain.reply_language", body.reply_language, "control-api language switch"
- )
- if body.reply_language in ("de", "en", "es"):
- ui = _apply_config_write(
- store, "ui.language", body.reply_language, "control-api language switch"
- )
+ reason = "control-api language switch"
+ switch_ui = body.reply_language in ("de", "en", "es")
+ # Validate BOTH writes before applying either, so a refused interface
+ # language never leaves the reply language switched on its own.
+ writer = _control_writer(request)
+ paths = ["brain.reply_language"] + (["ui.language"] if switch_ui else [])
+ for path in paths:
+ try:
+ writer.prevalidate(
+ MutationRequest(
+ path=path,
+ new_value=body.reply_language,
+ actor=AuditActor.USER,
+ source=AuditSource.UI,
+ reason=reason,
+ )
+ )
+ except SelfModError as exc:
+ raise _self_mod_http_error(exc) from exc
+ result = _apply_config_write(store, "brain.reply_language", body.reply_language, reason)
+ if switch_ui:
+ try:
+ ui = _apply_config_write(store, "ui.language", body.reply_language, reason)
+ except HTTPException:
+ # The second write failed after the first landed (a disk or
+ # reload error). Put the reply language back, then report.
+ previous = result.get("old_value")
+ if previous is not None:
+ try:
+ _apply_config_write(
+ store, "brain.reply_language", previous, f"{reason} (rolled back)"
+ )
+ except HTTPException:
+ log.error("control: reply_language rollback failed after ui.language error")
+ raise
result["ui_language"] = {"applied": ui.get("applied"), "value": body.reply_language}
return result
@@ -351,7 +408,11 @@ def list_secrets() -> dict[str, Any]:
return {"secrets": items}
[email protected]("/secrets/{key}", dependencies=[Depends(require_control_key)], openapi_extra={"x-jarvis-dangerous": True})
+ "/secrets/{key}",
+ dependencies=[Depends(require_control_key)],
+ openapi_extra={"x-jarvis-dangerous": True},
+)
async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict[str, Any]:
if key not in ALLOWED_SECRET_KEYS:
raise HTTPException(status_code=404, detail=f"Unknown secret key: {key}")
diff --git a/tests/integration/test_control_routes.py b/tests/integration/test_control_routes.py
index 5492aaee28..5532d87bfd 100644
--- a/tests/integration/test_control_routes.py
+++ b/tests/integration/test_control_routes.py
@@ -25,6 +25,8 @@ def client(monkeypatch, tmp_path):
config_file = tmp_path / "jarvis.toml"
config_file.write_text('[brain]\nreply_language = "de"\n', encoding="utf-8")
monkeypatch.setenv("JARVIS_CONFIG", str(config_file))
+ # Config backups and the audit log land in the temp dir, never the real data dir.
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(tmp_path / "data"))
# Deterministic auth: a fixed stored key, no real keyring access.
monkeypatch.setattr(control_key, "get_control_key", lambda: KEY)
@@ -160,6 +162,86 @@ def test_put_config_unknown_path_is_400(client) -> None:
assert res.status_code == 400
+# --- ASK tier: propose, confirm, fail honestly ---
+
+ASK_PATH = "trigger.session_idle_timeout_s"
+
+
+def test_ask_tier_write_parks_and_confirm_applies(client) -> None:
+ tc, _, _ = client
+ res = tc.put("/api/control/config", json={"path": ASK_PATH, "value": 120}, headers=AUTH)
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["needs_confirmation"] is True and body["applied"] is False
+
+ confirm = tc.post(
+ "/api/control/config/confirm", json={"pending_id": body["pending_id"]}, headers=AUTH
+ )
+ assert confirm.status_code == 200, confirm.text
+ assert confirm.json()["applied"] is True
+ assert cfg_mod.load_config().trigger.session_idle_timeout_s == 120
+
+ # The entry is consumed: a second confirm is gone, not re-applied.
+ again = tc.post(
+ "/api/control/config/confirm", json={"pending_id": body["pending_id"]}, headers=AUTH
+ )
+ assert again.status_code == 410
+
+
+def test_ask_tier_invalid_value_is_refused_when_proposed(client) -> None:
+ # Used to answer 200 "needs_confirmation" and then 500 on confirm: the
+ # value was only validated after the user had already said yes.
+ tc, config_file, _ = client
+ before = config_file.read_text(encoding="utf-8")
+ res = tc.put(
+ "/api/control/config", json={"path": ASK_PATH, "value": "not-a-number"}, headers=AUTH
+ )
+ assert res.status_code == 422
+ assert ASK_PATH in res.json()["detail"]
+ assert config_file.read_text(encoding="utf-8") == before
+
+
+def test_failed_confirm_is_an_error_status_not_ok_200(client, monkeypatch) -> None:
+ from jarvis.core.self_mod import AtomicConfigWriter
+ from jarvis.core.self_mod.errors import ReloadError
+
+ tc, _, _ = client
+ res = tc.put("/api/control/config", json={"path": ASK_PATH, "value": 90}, headers=AUTH)
+ pending_id = res.json()["pending_id"]
+
+ def _reload_fails(self, request): # noqa: ANN001, ARG001
+ raise ReloadError("reload of C:/secret/path/jarvis.toml failed")
+
+ monkeypatch.setattr(AtomicConfigWriter, "mutate", _reload_fails)
+ confirm = tc.post(
+ "/api/control/config/confirm", json={"pending_id": pending_id}, headers=AUTH
+ )
+ assert confirm.status_code == 500
+ detail = confirm.json()["detail"]
+ assert detail.startswith("config write failed")
+ assert "secret/path" not in detail
+
+
+def test_language_switch_is_all_or_nothing(client, monkeypatch) -> None:
+ # The verb writes reply_language, then ui.language. When the second write
+ # failed, the first used to stay applied: half a language switch.
+ from jarvis.core.self_mod import AtomicConfigWriter
+ from jarvis.core.self_mod.errors import ReloadError
+
+ tc, _, _ = client
+ real_mutate = AtomicConfigWriter.mutate
+
+ def _ui_write_fails(self, request): # noqa: ANN001
+ if request.path == "ui.language":
+ raise ReloadError("reload failed")
+ return real_mutate(self, request)
+
+ monkeypatch.setattr(AtomicConfigWriter, "mutate", _ui_write_fails)
+ res = tc.put("/api/control/language", json={"reply_language": "en"}, headers=AUTH)
+ assert res.status_code == 500
+ assert cfg_mod.load_config().brain.reply_language == "de"
+
+
# --- secrets ---
diff --git a/tests/unit/self_mod/test_pending_store.py b/tests/unit/self_mod/test_pending_store.py
index 506704f946..3bb8402909 100644
--- a/tests/unit/self_mod/test_pending_store.py
+++ b/tests/unit/self_mod/test_pending_store.py
@@ -7,9 +7,8 @@ REST/CLI keep the SAFE-auto / ASK-confirm split. The store carries the policy:
"""
from __future__ import annotations
-from pathlib import Path
-
import tomllib
+from pathlib import Path
import pytest
@@ -17,6 +16,7 @@ from jarvis.core.config import JarvisConfig
from jarvis.core.self_mod import (
AtomicConfigWriter,
PendingMutationStore,
+ PreValidateError,
SecretAccessError,
SelfModAudit,
)
@@ -77,3 +77,15 @@ class TestDefaultSafeOnly:
pending = store.create(_req("tts.speed", 1.25))
assert pending.applied is True
assert pending.needs_confirmation is False
+
+ def test_refuses_an_invalid_ask_value_before_parking_it(
+ self, writer: AtomicConfigWriter
+ ) -> None:
+ # A parked change is confirmed later; a value the schema rejects must
+ # fail now, not after the user said yes.
+ store = PendingMutationStore(writer=writer)
+ before = writer.config_path.read_text(encoding="utf-8")
+ with pytest.raises(PreValidateError):
+ store.create(_req("trigger.session_idle_timeout_s", "not-a-number"))
+ assert len(store) == 0
+ assert writer.config_path.read_text(encoding="utf-8") == before