Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(auth): personal editors use local resources (binding rewrite) (#1606)

Max37639f90e9e8
diff --git a/config/v2_config.py b/config/v2_config.py
index a5f286900..d4e17f742 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -3644,6 +3644,7 @@ class V2Config:
cls,
config_path: Optional[Path] = None,
*,
+ persist_migrations: bool = True,
_migration_reload_depth: int = 0,
) -> "V2Config":
paths.ensure_data_dirs()
@@ -3713,7 +3714,12 @@ class V2Config:
recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")
all_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))
- if migrated and not migration_warnings and not recovery_warnings:
+ if (
+ persist_migrations
+ and migrated
+ and not migration_warnings
+ and not recovery_warnings
+ ):
persisted_payload = copy.deepcopy(payload)
persisted_payload["model_hub"] = config.model_hub.to_payload()
try:
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index 4e86e1e3c..28090f821 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -7,7 +7,7 @@ import json
import logging
import threading
import time
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from datetime import datetime, timezone
from typing import Any, Mapping
@@ -97,7 +97,46 @@ def _load_notification_config() -> tuple[Any, bool]:
return None, True
-def _notification_policy_for_record(config: Any, record: Mapping[str, Any]) -> str:
+def _binding_snapshot(config: Any) -> tuple[bool, str, int]:
+ """One evaluation, one snapshot of (ready, kind, generation).
+
+ Policy selection and the later gate MUST use this same snapshot. Mixing
+ a reconciling-inferred Personal policy with a later-ready Organization
+ binding is the class this closes.
+ """
+
+ from vibe import remote_access
+ from storage import remote_access_authorization_service
+
+ cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
+ kind = str(getattr(cloud, "instance_kind", "") or "") if cloud is not None else ""
+ try:
+ generation = remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ except Exception:
+ generation = 0
+ ready = False
+ if kind in {"personal", "organization"} and config is not None:
+ try:
+ ready = bool(remote_access.binding_is_ready(config))
+ except Exception:
+ ready = False
+ if not ready:
+ # A known configured kind that is not ready (reconciling / pending /
+ # mismatched) must not leak into policy selection as if it were live.
+ # Mixing a reconciling-inferred Personal policy with a later-ready
+ # Organization binding is the class this snapshot closes.
+ kind = ""
+ return ready, kind, int(generation)
+
+
+def _notification_policy_for_record(
+ config: Any,
+ record: Mapping[str, Any],
+ *,
+ snapshot_kind: str = "",
+) -> str:
"""Select the notification authorization policy for one persisted record.
Policy selection follows the paired Instance kind (#1433): Personal and
@@ -105,10 +144,12 @@ def _notification_policy_for_record(config: Any, record: Mapping[str, Any]) -> s
pairings with an unknown kind fall back to the record's own claim shape —
claims issued through Organization membership follow the Organization
policy, everything else follows the Personal policy.
+
+ ``snapshot_kind`` is the kind captured once for this evaluation; do not
+ re-read the live binding here.
"""
- cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
- instance_kind = str(getattr(cloud, "instance_kind", "") or "")
+ instance_kind = snapshot_kind
if instance_kind == "organization":
return "organization"
if instance_kind == "personal":
@@ -188,8 +229,26 @@ def _evaluate_record_authorization(
"""
from vibe import remote_access
+ from storage import remote_access_authorization_service
- policy = _notification_policy_for_record(config, record)
+ snapshot_ready, snapshot_kind, snapshot_generation = _binding_snapshot(config)
+ policy = _notification_policy_for_record(
+ config, record, snapshot_kind=snapshot_kind
+ )
+ if config is None:
+ reason = (
+ "paired configuration could not be read; instance binding cannot be validated"
+ if config_load_failed
+ else "paired configuration is unavailable; instance binding cannot be validated"
+ )
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ reason=reason,
+ )
cloud = getattr(getattr(config, "remote_access", None), "vibe_cloud", None)
if cloud is not None and not cloud.enabled:
# Disabling remote access is a confirmed, deliberate removal of every
@@ -216,6 +275,66 @@ def _evaluate_record_authorization(
disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
reason="paired configuration could not be read; instance binding cannot be validated",
)
+ from vibe.authorization import instance_kind_is_unsupported
+
+ record_kind = record.get("vibe_instance_kind")
+ if instance_kind_is_unsupported(record_kind):
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_REVOKED,
+ reason="persisted snapshot instance kind is unrecognized",
+ )
+ paired_kind = snapshot_kind
+ try:
+ live_generation = remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ except Exception:
+ live_generation = snapshot_generation
+ configured_kind = str(getattr(cloud, "instance_kind", "") or "") if cloud is not None else ""
+ generation_moved = int(live_generation) != int(snapshot_generation)
+ if configured_kind in {"personal", "organization"} and not snapshot_ready:
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ reason="durable instance binding is not ready",
+ )
+ if (
+ configured_kind in {"personal", "organization"}
+ and snapshot_ready
+ and generation_moved
+ and int(snapshot_generation) > 0
+ ):
+ # The binding advanced under us after we captured a real (non-zero)
+ # generation. Mixing the original policy with the new binding is the
+ # class this snapshot closes. Generation 0 → N is bootstrap, not TOCTOU.
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ reason="durable instance binding is not ready",
+ )
+ if (
+ paired_kind in {"personal", "organization"}
+ and cloud is not None
+ and cloud.runtime_credentials() is None
+ ):
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ reason="current pairing lacks complete runtime credentials",
+ )
context = context_from_session_payload(record)
if not (
context.subject
@@ -250,6 +369,48 @@ def _evaluate_record_authorization(
disposition=WEB_PUSH_DISPOSITION_REVOKED,
reason="persisted snapshot was issued for a different paired instance",
)
+ record_kind = record.get("vibe_instance_kind")
+ if (
+ record_kind in {"personal", "organization"}
+ and paired_kind not in {"personal", "organization"}
+ ):
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ reason="current pairing instance kind is unavailable",
+ )
+ if (
+ record_kind in {"personal", "organization"}
+ and paired_kind in {"personal", "organization"}
+ and record_kind != paired_kind
+ ):
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_REVOKED,
+ reason="persisted snapshot instance kind differs from the current pairing",
+ )
+ if (
+ context.instance_kind is None
+ and record_kind is None
+ and paired_instance_id
+ and paired_kind in {"personal", "organization"}
+ ):
+ if record_instance_id != paired_instance_id:
+ return OwnerAuthorizationDecision(
+ user_key=user_key,
+ policy=policy,
+ context=None,
+ authorized=False,
+ disposition=WEB_PUSH_DISPOSITION_REVOKED,
+ reason="persisted snapshot lacks a binding to the current paired instance",
+ )
+ context = replace(context, instance_kind=paired_kind)
if policy == "personal":
return OwnerAuthorizationDecision(
user_key=user_key,
@@ -342,11 +503,17 @@ def _resolve_owner_authorization_decisions(
if not records:
return {}
config, config_load_failed = _load_notification_config()
+ snapshot_ready, snapshot_kind, _snapshot_generation = (
+ _binding_snapshot(config) if config is not None else (False, "", 0)
+ )
if (
allow_sync_retry
and not config_load_failed
and any(
- _notification_policy_for_record(config, record) == "organization"
+ _notification_policy_for_record(
+ config, record, snapshot_kind=snapshot_kind
+ )
+ == "organization"
for _user_key, record in records
)
):
@@ -626,6 +793,7 @@ def web_push_authorization_context_record(
"sub": context.subject,
"vibe_instance_role": context.instance_role,
"vibe_instance_access_source": context.instance_access_source,
+ "vibe_instance_kind": context.instance_kind,
"vibe_group_ids": sorted(context.group_ids),
"claims_issued_at": context.claims_issued_at,
}
diff --git a/docs/plans/personal-editor-local-resources.md b/docs/plans/personal-editor-local-resources.md
new file mode 100644
index 000000000..c288fe52e
--- /dev/null
+++ b/docs/plans/personal-editor-local-resources.md
@@ -0,0 +1,119 @@
+# Spec: Personal Editor local-resource access — binding state machine rewrite
+
+Status: APPROVED (owner signed off D1/D2 defaults + D3 naming). Supersedes closed PR #1562.
+Branch: `personal-editor-local-resources`
+PR title: `fix(auth): personal editors use local resources (binding rewrite)`
+
+## 1. Background — why we're rewriting
+
+PR #1562 added the first cross-process authorization signal (`instance_kind`) but never
+wrote down the concurrency model for it. Five bot-review rounds later the thread count went
+7 → 9 → 11 → 15 → 19: every patch inlined a partial answer, and the last two rounds produced
+self-inflicted regressions (a gate that permanently locks out legacy no-kind pairings; a lock
+acquired before SQLite init that creates an ABBA deadlock).
+
+Root cause (one sentence): **durable binding state was added, but "who is the single writer,
+what is the lock order, and which writes must be generation-fenced" was never defined as a
+contract — so transient state keeps getting latched into permanent decisions across two
+processes (controller + ui_server).**
+
+Correct parts of the current work ARE kept (see §4). Only the binding state machine + the
+authorization fencing is rewritten.
+
+## 2. Goal
+
+A Personal Editor gets full Agent/Project access on a Personal instance, independent of
+Organization ACLs; Organization + unknown kinds stay fail-closed. This must hold:
+- across the two-process boundary (controller / ui_server), and
+- through every transient state (credentials temporarily missing, kind not yet backfilled,
+ kind being reclassified by heartbeat, fresh install with no config, legacy no-kind pairing).
+
+## 3. The three contracts (approved by owner)
+
+### C1 — Single source of truth
+A durable binding = `(instance_id, kind, generation)`, persisted in `state_meta`.
+- Only a binding in `ready` state may admit the kind-specific (Personal) bypass.
+- `reconciling` / `unpaired` / `unavailable` states FAIL CLOSED (no bypass).
+- Kind is authoritative mutable provenance: unknown ≠ Personal ≠ Organization; a kind
+ backfill or reclassification must go through a transition, never be silently relabeled.
+
+### C2 — One writer + canonical lock order + generation CAS
+- `generation` is monotonic and durable; every write (config, binding, authorization rows)
+ does compare-and-swap: read the persisted generation inside the critical section
+ immediately before writing; refuse if it no longer matches.
+- Canonical lock order: **SQLite initialization FIRST, then the cross-process config lock**
+ (`config_file_lock`, NOT the process-local `CONFIG_LOCK`). Never acquire config lock while
+ `ensure_sqlite_state()` / `migration.lock` may be needed — this kills the ABBA deadlock.
+- The whole read-generation → compare → config-write → transition is ONE cross-process
+ critical section.
+
+### C3 — One gate for every consumer
+A single predicate `binding_is_ready(config, identity)` gates ALL authorization reads and
+writes before they touch instance-kind logic:
+1. interactive refresh (`_fetch_authorization_context`),
+2. non-interactive metadata (`resource_user_context_from_metadata`),
+3. Web Push authorization,
+4. OAuth callback writes,
+5. legacy inline-cookie migration writes.
+No consumer reads `config.instance_kind` directly to make an authorization decision.
+
+## 4. Scope — carried over vs rewritten
+
+### Carried over verbatim (correct, concurrency-independent — do NOT rework)
+- deferred-context migration + snapshot/provenance logic (`storage/resource_access_service.py`):
+ the typed UNAVAILABLE/UNPAIRED/PARTIAL/READY reader, migration state machine, old-marker
+ compatibility, sealed_unattributed.
+- the 435 passing tests (they are the executable spec of all known invariants).
+
+### Rewritten (the module that keeps leaking)
+`vibe/remote_access.py` binding machinery + every authorization write/read gate:
+- `_transition_instance_binding` → single cross-process critical section (C2),
+- `_AUTHORIZATION_BINDING_EPOCH` (process-local) → removed in favor of durable generation (C1/C2),
+- `_durable_binding_allows_cached_authorization` → replaced by the single `binding_is_ready` gate (C3),
+- `pair()` ordering: provenance validated BEFORE one-time-key redeem (fail without redeem on
+ unavailable provenance; treat **absent config as authoritative `unpaired`, not `UNAVAILABLE`**),
+- `_fetch_authorization_context` + `_store_scoped_authorization` + revocation/denied path →
+ all writes generation-fenced, including the 403 path (C3),
+- non-interactive + Web Push + OAuth callback + legacy cookie paths → route through the gate (C3),
+- legacy no-kind pairing stays usable (fail-open for the legacy path, not permanently locked out).
+
+## 5. Files
+
+- `vibe/remote_access.py` — binding state machine, transition hook, all gated write/read sites.
+- `storage/remote_access_authorization_service.py` — durable generation storage + targeted
+ invalidation/revocation (keep the `show_page` exemption contract).
+- `storage/resource_access_service.py` — carried over, only touch if a gate needs the typed
+ reader's result.
+- `config/v2_config.py` — confirm `config_file_lock` is the single cross-process lock (no change
+ expected; do not add locks).
+
+## 6. Tests
+
+Carried: all 435. New (each maps to a regression this PR actually hit):
+1. legacy/invalid no-kind pairing stays usable (round-5 #1) — fail-open for legacy, not locked out.
+2. fresh install with NO config → authoritative `unpaired`, pair() redeems successfully (round-5 #4).
+3. lock order: binding transition does NOT acquire config lock before SQLite init (round-5 #2).
+4. reconciling window: an OAuth-callback / legacy-cookie write is generation-fenced and cannot
+ publish stale Editor claims under the new Personal kind (round-5 #3).
+5. stale 403/revocation is fenced by generation (round-4 #4).
+6. cross-process CAS: a stale writer cannot reverse a newer binding (round-4 #1, #2).
+7. non-interactive + Web Push consumers return no Personal bypass while `reconciling`.
+
+## 7. Delivery plan
+
+1. (this doc) — owner approves.
+2. New branch off latest `origin/master` (`84702f73`), fresh worktree (NOT the old #1562 worktree).
+3. Carry over §4 "kept" code + 435 tests; rewrite §4 "rewritten" module per C1–C3.
+4. Open a NEW PR (correct scope + evidence numbers); commit this spec to `docs/plans/`.
+5. Close PR #1562 with a comment pointing to the new PR.
+6. Re-point the durable watch from #1562 to the new PR; retire #1562's watch.
+
+## 8. Open owner decisions (need your call before/at implementation)
+
+- D1: keep the three prior decisions? (a) Org↔Personal reclassification keeps completed legacy
+ authorizations REJECTED; (b) exact `show_page_email` grants survive kind transitions; (c)
+ config-persist-OK but SQLite-reconcile-fails → durable `reconciling` + fail closed. — assumed YES.
+- D2: legacy no-kind pairing (round-5 #1) — confirm we keep it usable via a legacy path (fail-open),
+ rather than forcing these pairings to re-pair. — assumed YES, confirm.
+- D3: PR/branch naming — propose branch `personal-editor-local-resources`, PR title
+ "fix(auth): personal editors use local resources (binding rewrite)". — confirm or rename.
diff --git a/storage/importer.py b/storage/importer.py
index 737996945..cad9dafb7 100644
--- a/storage/importer.py
+++ b/storage/importer.py
@@ -269,7 +269,9 @@ def _set_background_import_marker(conn: Connection) -> None:
def _run_sqlite_data_migrations(conn: Connection) -> dict[str, int]:
- return {}
+ from storage.resource_access_service import migrate_legacy_deferred_resource_contexts
+
+ return migrate_legacy_deferred_resource_contexts(conn)
def _backup_json_state(state_dir: Path) -> Path:
diff --git a/storage/project_access_service.py b/storage/project_access_service.py
index de536b282..7b9bae451 100644
--- a/storage/project_access_service.py
+++ b/storage/project_access_service.py
@@ -319,6 +319,8 @@ def get_effective_project_role(
instance_role = context.instance_role
if instance_role not in _ROLE_RANK:
return None
+ if context.is_personal_instance and context.has_role("editor"):
+ return instance_role
policy = get_project_policy(conn, project_id)
if policy is None or policy["mode"] == "inherit":
return instance_role
diff --git a/storage/remote_access_authorization_service.py b/storage/remote_access_authorization_service.py
index c197357cb..a1c5c9a37 100644
--- a/storage/remote_access_authorization_service.py
+++ b/storage/remote_access_authorization_service.py
@@ -4,13 +4,28 @@ from __future__ import annotations
import json
import secrets
-from typing import Any, Mapping
+import time
+from contextlib import contextmanager
+from typing import Any, Callable, Iterator, Mapping
-from sqlalchemy import and_, or_, select, update
+from sqlalchemy import and_, delete, or_, select, update
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
+from sqlalchemy.exc import OperationalError
from storage.db import get_cached_sqlite_engine
-from storage.models import remote_access_authorizations
+from storage.models import remote_access_authorizations, state_meta
+
+INSTANCE_BINDING_STATE_META_KEY = "remote_access.instance_binding.v1"
+INSTANCE_BINDING_STATE_RECONCILING = "reconciling"
+INSTANCE_BINDING_STATE_READY = "ready"
+# A durable, USABLE legacy state: the pairing reconciled successfully but the
+# control plane never reported a recognized kind. No kind-specific bypass is
+# available, and a later authoritative backfill completes it via a normal
+# transition.
+INSTANCE_BINDING_STATE_PENDING_KIND = "pending_kind"
+INSTANCE_BINDING_STATE_INVALID = "invalid"
+INSTANCE_BINDING_GENERATION_KEY = "vibe_instance_binding_generation"
+INSTANCE_BINDING_LOCK_FILENAME = "remote-access-instance-binding.lock"
def store(
@@ -133,6 +148,10 @@ def load_scoped(
return _record_from_row(row) if row is not None else None
+class InstanceBindingChangedError(RuntimeError):
+ """A durable binding generation advanced while this authorization write was in flight."""
+
+
def upsert_scoped(
*,
reference: str | None,
@@ -145,8 +164,14 @@ def upsert_scoped(
claims: Mapping[str, Any],
last_checked_at: int,
updated_at: int,
+ expected_binding_generation: int | None = None,
) -> str:
- """Store one current Instance or Show Page context without expiring it."""
+ """Store one current Instance or Show Page context without expiring it.
+
+ When ``expected_binding_generation`` is provided, the compare and the write
+ run atomically under the cross-process binding lock (C2): a generation
+ that advanced, or a binding still reconciling, refuses the write.
+ """
from storage.importer import ensure_sqlite_state
@@ -167,7 +192,19 @@ def upsert_scoped(
"updated_at": updated_at,
}
engine = get_cached_sqlite_engine()
+ # Compare and write share one SQLite writer transaction: that is the
+ # cross-process CAS for authorization rows (C2). Generation is monotonic
+ # so a peer completing a transition after we captured expected_generation
+ # is still refused here.
with engine.begin() as conn:
+ if expected_binding_generation is not None:
+ live = _load_binding_state_from_connection(conn)
+ live_generation = int((live or {}).get("generation") or 0)
+ live_state = (live or {}).get("state")
+ if live_generation > int(expected_binding_generation) or (
+ live_state == INSTANCE_BINDING_STATE_RECONCILING
+ ):
+ raise InstanceBindingChangedError("instance_binding_changed")
existing_scope_reference = conn.execute(
select(remote_access_authorizations.c.id)
.where(remote_access_authorizations.c.instance_id == instance_id)
@@ -292,3 +329,593 @@ def delete_for_instance(instance_id: str) -> int:
)
)
return int(result.rowcount or 0)
+
+
+def _decode_binding_state(value: Any) -> dict[str, Any] | None:
+ """Decode one state row, rejecting malformed values instead of guessing."""
+
+ if not isinstance(value, str):
+ return None
+ try:
+ payload = json.loads(value)
+ if not isinstance(payload, dict):
+ return None
+ state = payload.get("state")
+ if state not in {
+ INSTANCE_BINDING_STATE_RECONCILING,
+ INSTANCE_BINDING_STATE_READY,
+ INSTANCE_BINDING_STATE_PENDING_KIND,
+ }:
+ return None
+ instance_id = payload.get("instance_id")
+ if not isinstance(instance_id, str) or not instance_id.strip():
+ return None
+ instance_kind = payload.get("instance_kind")
+ if instance_kind not in {None, "personal", "organization"}:
+ return None
+ if state == INSTANCE_BINDING_STATE_READY and instance_kind is None:
+ return None
+ generation = int(payload.get("generation"))
+ raw_schema_version = payload.get("schema_version")
+ if raw_schema_version is None:
+ schema_version = 1
+ else:
+ schema_version = int(raw_schema_version)
+ if schema_version != 1:
+ return None
+ except (TypeError, ValueError, json.JSONDecodeError):
+ return None
+ if generation <= 0:
+ return None
+ return {
+ "schema_version": schema_version,
+ "state": state,
+ "instance_id": instance_id.strip(),
+ "instance_kind": instance_kind,
+ "generation": generation,
+ "updated_at": payload.get("updated_at"),
+ }
+
+
+def _load_binding_state_from_connection(conn) -> dict[str, Any] | None:
+ raw = conn.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key == INSTANCE_BINDING_STATE_META_KEY
+ )
+ ).scalar_one_or_none()
+ if raw is None:
+ return None
+ decoded = _decode_binding_state(raw)
+ if decoded is not None:
+ return decoded
+ # Keep corruption distinguishable from a never-initialized install. Any
+ # caller that sees this value must fail closed until a transition repairs it.
+ return {
+ "schema_version": 0,
+ "state": INSTANCE_BINDING_STATE_INVALID,
+ "instance_id": None,
+ "instance_kind": None,
+ "generation": 0,
+ "updated_at": None,
+ }
+
+
+def _ensure_sqlite_state() -> None:
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+
+
+def _binding_file_lock():
+ from config import paths
+ from storage.lock import MigrationFileLock
+
+ return MigrationFileLock(paths.get_state_dir() / INSTANCE_BINDING_LOCK_FILENAME)
+
+
+@contextmanager
+def instance_binding_lock() -> Iterator[None]:
+ """Serialize binding transitions across controller and UI processes."""
+
+ _ensure_sqlite_state()
+ with _binding_file_lock():
+ yield
+
+
+def load_instance_binding_state(*, ensure: bool = True) -> dict[str, Any] | None:
+ """Read the durable binding epoch shared by UI and controller processes."""
+
+ if ensure:
+ _ensure_sqlite_state()
+ engine = get_cached_sqlite_engine()
+ try:
+ with engine.connect() as conn:
+ return _load_binding_state_from_connection(conn)
+ except OperationalError as exc:
+ # A pre-migration process may not have created state_meta yet. Treat
+ # that as a legacy no-row install; callers that need a durable write
+ # use the default ``ensure=True`` path and will still fail closed on a
+ # real storage error.
+ if not ensure and "no such table" in str(exc).lower():
+ return None
+ raise
+
+
+def _validate_transition_identity(
+ *,
+ instance_id: str,
+ instance_kind: str | None,
+) -> tuple[str, str | None]:
+ if not isinstance(instance_id, str) or not instance_id.strip():
+ raise ValueError("instance_id_required")
+ if instance_kind not in {None, "personal", "organization"}:
+ raise ValueError("instance_kind_required")
+ return instance_id.strip(), instance_kind
+
+
+def _binding_payload(
+ *,
+ state: str,
+ instance_id: str,
+ instance_kind: str | None,
+ generation: int,
+) -> tuple[dict[str, Any], str]:
+ now = str(int(time.time()))
+ payload = {
+ "schema_version": 1,
+ "state": state,
+ "instance_id": instance_id,
+ "instance_kind": instance_kind,
+ "generation": int(generation),
+ "updated_at": now,
+ }
+ return payload, now
+
+
+def _write_binding_state(conn, payload: Mapping[str, Any], updated_at: str) -> None:
+ encoded = json.dumps(dict(payload), separators=(",", ":"), sort_keys=True)
+ statement = sqlite_insert(state_meta).values(
+ key=INSTANCE_BINDING_STATE_META_KEY,
+ value_json=encoded,
+ updated_at=updated_at,
+ )
+ conn.execute(
+ statement.on_conflict_do_update(
+ index_elements=[state_meta.c.key],
+ set_={"value_json": encoded, "updated_at": updated_at},
+ )
+ )
+
+
+def _begin_instance_binding_transition_locked(
+ conn,
+ *,
+ instance_id: str,
+ instance_kind: str | None,
+) -> dict[str, Any]:
+ instance_id, instance_kind = _validate_transition_identity(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ )
+ existing = _load_binding_state_from_connection(conn)
+ if (
+ existing is not None
+ and existing["state"] == INSTANCE_BINDING_STATE_READY
+ and existing["instance_id"] == instance_id
+ and existing["instance_kind"] == instance_kind
+ ):
+ return {
+ "generation": existing["generation"],
+ "changed": False,
+ "previous": existing,
+ "state": INSTANCE_BINDING_STATE_READY,
+ }
+ if (
+ existing is not None
+ and existing["state"]
+ in {INSTANCE_BINDING_STATE_RECONCILING, INSTANCE_BINDING_STATE_PENDING_KIND}
+ and existing["instance_id"] == instance_id
+ and existing["instance_kind"] == instance_kind
+ ):
+ return {
+ "generation": existing["generation"],
+ "changed": True,
+ "previous": existing,
+ "state": INSTANCE_BINDING_STATE_RECONCILING,
+ }
+ generation = (int(existing["generation"]) if existing is not None else 0) + 1
+ payload, now = _binding_payload(
+ state=INSTANCE_BINDING_STATE_RECONCILING,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ generation=generation,
+ )
+ _write_binding_state(conn, payload, now)
+ return {
+ "generation": generation,
+ "changed": True,
+ "previous": existing,
+ "state": INSTANCE_BINDING_STATE_RECONCILING,
+ }
+
+
+def begin_instance_binding_transition(
+ *,
+ instance_id: str,
+ instance_kind: str | None,
+) -> dict[str, Any]:
+ """Commit a fail-closed ``reconciling`` epoch before derived work starts."""
+
+ _ensure_sqlite_state()
+ with _binding_file_lock():
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ return _begin_instance_binding_transition_locked(
+ conn,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ )
+
+
+def _invalidate_instance_binding_authorizations_locked(
+ conn,
+ *,
+ instance_id: str,
+ previous_instance_id: str | None = None,
+ preserve_show_page: bool = True,
+ keep_reference_for_revalidation: bool = True,
+) -> int:
+ ids = {
+ value.strip()
+ for value in (instance_id, previous_instance_id or "")
+ if isinstance(value, str) and value.strip()
+ }
+ if not ids:
+ return 0
+ predicate = remote_access_authorizations.c.instance_id.in_(ids)
+ if preserve_show_page:
+ predicate = and_(
+ predicate,
+ or_(
+ remote_access_authorizations.c.scope_kind.is_(None),
+ remote_access_authorizations.c.scope_kind != "show_page",
+ ),
+ )
+ if keep_reference_for_revalidation:
+ result = conn.execute(
+ update(remote_access_authorizations)
+ .where(predicate)
+ .values(authorization_state="stale", updated_at=int(time.time()))
+ )
+ else:
+ result = conn.execute(delete(remote_access_authorizations).where(predicate))
+ return int(result.rowcount or 0)
+
+
+def invalidate_instance_binding_authorizations(
+ *,
+ instance_id: str,
+ previous_instance_id: str | None = None,
+ preserve_show_page: bool = True,
+ keep_reference_for_revalidation: bool = True,
+) -> int:
+ """Invalidate derived instance claims without touching exact Show Page grants."""
+
+ _ensure_sqlite_state()
+ with _binding_file_lock():
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ return _invalidate_instance_binding_authorizations_locked(
+ conn,
+ instance_id=instance_id,
+ previous_instance_id=previous_instance_id,
+ preserve_show_page=preserve_show_page,
+ keep_reference_for_revalidation=keep_reference_for_revalidation,
+ )
+
+
+def _complete_instance_binding_transition_locked(
+ conn,
+ *,
+ instance_id: str,
+ instance_kind: str,
+ generation: int,
+) -> bool:
+ if instance_kind not in {"personal", "organization"}:
+ return False
+ existing = _load_binding_state_from_connection(conn)
+ if (
+ existing is None
+ or existing["state"] != INSTANCE_BINDING_STATE_RECONCILING
+ or existing["instance_id"] != instance_id
+ or existing["instance_kind"] not in {None, instance_kind}
+ or existing["generation"] != int(generation)
+ ):
+ return False
+ # Publishing ready is itself a binding event: bump generation so any
+ # in-flight authorization write that captured the reconciling generation
+ # CAS-fails instead of landing under the new ready binding.
+ payload, now = _binding_payload(
+ state=INSTANCE_BINDING_STATE_READY,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ generation=int(generation) + 1,
+ )
+ _write_binding_state(conn, payload, now)
+ return True
+
+
+def complete_instance_binding_transition(
+ *,
+ instance_id: str,
+ instance_kind: str,
+ generation: int,
+) -> bool:
+ """Publish a reconciled binding epoch after all derived work succeeds."""
+
+ _ensure_sqlite_state()
+ with _binding_file_lock():
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ return _complete_instance_binding_transition_locked(
+ conn,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ generation=generation,
+ )
+
+
+def reconcile_instance_binding(
+ *,
+ instance_id: str,
+ instance_kind: str | None,
+ reconcile: Callable[[], Any] | None = None,
+ previous_instance_id: str | None = None,
+ preserve_show_page: bool = True,
+ hold_config_lock: bool = True,
+) -> dict[str, Any]:
+ """Run one serialized identity transition and publish ``ready`` last.
+
+ A callback failure deliberately leaves the committed ``reconciling`` row
+ in place. Callers must treat the returned ``ok=False`` as fail-closed and
+ retry from the next heartbeat.
+ """
+
+ instance_id, instance_kind = _validate_transition_identity(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ )
+ # Canonical lock order (C2): SQLite initialization FIRST, then the
+ # cross-process config lock. Never acquire config_file_lock while
+ # ensure_sqlite_state / migration.lock may still be needed.
+ _ensure_sqlite_state()
+
+ def run() -> dict[str, Any]:
+ engine = get_cached_sqlite_engine()
+ with _binding_file_lock():
+ return _reconcile_instance_binding_locked(
+ engine,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ reconcile=reconcile,
+ previous_instance_id=previous_instance_id,
+ preserve_show_page=preserve_show_page,
+ )
+
+ if not hold_config_lock:
+ return run()
+ from config.v2_config import config_file_lock
+
+ with config_file_lock():
+ return run()
+
+
+def _reconcile_instance_binding_locked(
+ engine,
+ *,
+ instance_id: str,
+ instance_kind: str | None,
+ reconcile: Callable[[], Any] | None,
+ previous_instance_id: str | None,
+ preserve_show_page: bool,
+) -> dict[str, Any]:
+ with engine.begin() as conn:
+ transition = _begin_instance_binding_transition_locked(
+ conn,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ )
+ previous = transition.get("previous")
+ previous_id = previous.get("instance_id") if isinstance(previous, Mapping) else None
+ if previous_instance_id and previous_instance_id != instance_id:
+ previous_id = previous_instance_id
+ preserve = preserve_show_page and previous_id in {None, instance_id}
+ invalidated = (
+ _invalidate_instance_binding_authorizations_locked(
+ conn,
+ instance_id=instance_id,
+ previous_instance_id=previous_id,
+ preserve_show_page=preserve,
+ )
+ if transition["changed"]
+ else 0
+ )
+
+ if not transition["changed"]:
+ return {
+ **transition,
+ "ok": True,
+ "ready": True,
+ "invalidated": 0,
+ }
+
+ try:
+ if reconcile is not None:
+ reconcile()
+ except Exception as exc:
+ return {
+ **transition,
+ "ok": False,
+ "ready": False,
+ "invalidated": invalidated,
+ "error": str(exc),
+ }
+
+ if instance_kind is None:
+ # A supported legacy no-kind pairing must stay USABLE: publish the
+ # durable pending_kind state instead of parking in fail-closed
+ # reconciling. A later authoritative backfill runs a new transition.
+ with engine.begin() as conn:
+ existing = _load_binding_state_from_connection(conn)
+ if (
+ existing is not None
+ and existing["state"] == INSTANCE_BINDING_STATE_RECONCILING
+ and existing["instance_id"] == instance_id
+ and existing["generation"] == int(transition["generation"])
+ ):
+ payload, now = _binding_payload(
+ state=INSTANCE_BINDING_STATE_PENDING_KIND,
+ instance_id=instance_id,
+ instance_kind=None,
+ generation=transition["generation"],
+ )
+ _write_binding_state(conn, payload, now)
+ return {
+ **transition,
+ "ok": True,
+ "ready": False,
+ "invalidated": invalidated,
+ "pending": True,
+ }
+
+ with engine.begin() as conn:
+ completed = _complete_instance_binding_transition_locked(
+ conn,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ generation=transition["generation"],
+ )
+ if not completed:
+ return {
+ **transition,
+ "ok": False,
+ "ready": False,
+ "invalidated": invalidated,
+ "error": "binding_generation_changed",
+ }
+ return {
+ **transition,
+ "generation": int(transition["generation"]) + 1,
+ "ok": True,
+ "ready": True,
+ "invalidated": invalidated,
+ }
+
+
+def instance_binding_generation(
+ *,
+ instance_id: str,
+ instance_kind: str,
+) -> int | None:
+ state = load_instance_binding_state()
+ if (
+ state is None
+ or state["state"] != INSTANCE_BINDING_STATE_READY
+ or state["instance_id"] != instance_id
+ or state["instance_kind"] != instance_kind
+ ):
+ return None
+ return int(state["generation"])
+
+
+def current_instance_binding_generation(*, ensure: bool = True) -> int:
+ """Return the durable generation any process can compare against.
+
+ Missing state is generation 0 (a never-initialized install). A corrupt
+ or reconciling row still exposes its generation so a stale writer can
+ refuse to reverse a newer transition.
+ """
+
+ state = load_instance_binding_state(ensure=ensure)
+ if state is None:
+ return 0
+ try:
+ return int(state.get("generation") or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _bootstrap_deferred_migration() -> None:
+ """Run the deferred-context migration for one bootstrap transition."""
+
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.resource_access_service import (
+ RESOURCE_BINDING_STATE_UNAVAILABLE,
+ RESOURCE_BINDING_STATUS_KEY,
+ migrate_legacy_deferred_resource_contexts,
+ )
+
+ ensure_sqlite_state()
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ result = migrate_legacy_deferred_resource_contexts(connection)
+ if result.get(RESOURCE_BINDING_STATUS_KEY) == RESOURCE_BINDING_STATE_UNAVAILABLE:
+ raise RuntimeError("legacy_deferred_context_provenance_unavailable")
+
+
+def binding_is_ready_for_pairing(
+ *,
+ instance_id: str | None,
+ instance_kind: str | None,
+ ensure: bool = False,
+ bootstrap: bool = False,
+) -> bool:
+ """True only when the durable binding is ready for this pairing.
+
+ A missing row is compatible ONLY for a no-kind legacy pairing. A known
+ configured kind without a validated durable row is an upgrade artifact:
+ with ``bootstrap=True`` (authorization consumers) it earns a validated
+ row through one real transition; otherwise it fails closed.
+ ``pending_kind`` is the durable usable legacy state; once a row exists,
+ ``reconciling`` / ``invalid`` / mismatched identity means the kind is
+ unavailable to every consumer until reconciliation succeeds.
+ """
+
+ current_id = (instance_id or "").strip()
+ current_kind = instance_kind if instance_kind in {"personal", "organization"} else None
+ state = load_instance_binding_state(ensure=ensure)
+ if state is None:
+ # Stay compatible for the legacy no-kind pairing; a known kind with
+ # no validated binding row (the server may have reclassified while
+ # this install was offline) is bootstrapped or fails closed.
+ if current_kind is None:
+ return True
+ if not bootstrap or not current_id:
+ return False
+ try:
+ result = reconcile_instance_binding(
+ instance_id=current_id,
+ instance_kind=current_kind,
+ reconcile=_bootstrap_deferred_migration,
+ )
+ except Exception:
+ return False
+ return bool(result.get("ok") and result.get("ready"))
+ if state.get("state") == INSTANCE_BINDING_STATE_PENDING_KIND:
+ # Usable legacy state: no kind bypass is claimable anyway.
+ return current_kind is None and (
+ not current_id or state.get("instance_id") == current_id
+ )
+ if state.get("state") in {INSTANCE_BINDING_STATE_RECONCILING, INSTANCE_BINDING_STATE_INVALID}:
+ return False
+ if state.get("state") != INSTANCE_BINDING_STATE_READY:
+ return False
+ if current_kind is None:
+ # Legacy/invalid no-kind pairing stays usable (fail-open).
+ return True
+ return (
+ bool(current_id)
+ and state.get("instance_id") == current_id
+ and state.get("instance_kind") == current_kind
+ )
diff --git a/storage/resource_access_service.py b/storage/resource_access_service.py
index 7ec54763a..7aae19f56 100644
--- a/storage/resource_access_service.py
+++ b/storage/resource_access_service.py
@@ -7,18 +7,28 @@ content, prompts, paths, outputs, or secret values.
from __future__ import annotations
+import hashlib
import json
import time
from collections.abc import Mapping, Sequence
from contextlib import contextmanager
+from dataclasses import dataclass, replace
from datetime import datetime, timezone
from typing import Any, Iterator
-from sqlalchemy import select
+from sqlalchemy import select, update
+from sqlalchemy import text as sqlalchemy_text
from sqlalchemy.engine import Connection
from storage.db import get_cached_sqlite_engine
-from storage.models import resource_access_groups, resource_access_policies, state_meta
+from storage.models import (
+ agent_runs,
+ message_deliveries,
+ resource_access_groups,
+ resource_access_policies,
+ run_definitions,
+ state_meta,
+)
from vibe.authorization import (
AuthorizationContext,
context_from_session_payload,
@@ -30,8 +40,26 @@ RESOURCE_KINDS = frozenset({"agent", "vault_secret", "skill"})
ACCESS_LEVELS = frozenset({"public", "scope", "private"})
ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
RESOURCE_USER_CONTEXT_METADATA_KEY = "resource_user_context"
+LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY = "migrations.legacy_deferred_resource_contexts.v1"
RESOURCE_ORGANIZATIONS_META_KEY = "resource_access_organizations"
HARNESS_ACCESS_FORBIDDEN_CODE = "harness_access_forbidden"
+RESOURCE_BINDING_STATE_UNAVAILABLE = "unavailable"
+RESOURCE_BINDING_STATE_UNPAIRED = "unpaired"
+RESOURCE_BINDING_STATE_PARTIAL = "partial"
+RESOURCE_BINDING_STATE_READY = "ready"
+RESOURCE_BINDING_STATE_SEALED = "sealed"
+RESOURCE_BINDING_STATUS_KEY = "binding_status"
+_CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE = object()
+
+
+@dataclass(frozen=True)
+class ConfiguredResourceState:
+ """One coherent read of the pairing identity used by deferred resources."""
+
+ status: str
+ instance_id: str | None
+ instance_kind: str | None
+ runtime_ready: bool
class ResourceAccessError(ValueError):
@@ -250,8 +278,10 @@ def metadata_with_resource_user_context(
"vibe_organization_role": context.organization_role,
"vibe_group_ids": sorted(context.group_ids) if context.group_ids is not None else None,
"vibe_membership_version": context.membership_version,
+ "vibe_instance_id": context.instance_id,
"vibe_instance_role": context.instance_role,
"vibe_instance_access_source": context.instance_access_source,
+ "vibe_instance_kind": context.instance_kind,
"vibe_show_page_id": context.show_page_id,
"claims_issued_at": context.claims_issued_at,
"vibe_instance_authorization_revision": context.authorization_revision,
@@ -290,7 +320,93 @@ def resource_user_context_from_metadata(
snapshot = metadata.get(RESOURCE_USER_CONTEXT_METADATA_KEY)
if not isinstance(snapshot, Mapping):
return None
- return current_resource_context(snapshot, is_remote=True)
+ context = current_resource_context(snapshot, is_remote=True)
+
+ # A persisted context is durable across re-pairing, so a Personal snapshot
+ # must not authorize work after this installation moves to another
+ # instance. Compare the server-owned binding whenever the current pairing
+ # exposes one; legacy snapshots without an instance id remain unbound.
+ configured = _configured_resource_instance()
+ if context.instance_kind is not None and (
+ configured is _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE or configured is None
+ ):
+ return None
+ if configured is not _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE and configured is not None:
+ paired_instance_id, paired_kind = configured
+ from storage import remote_access_authorization_service
+
+ ready = remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id=paired_instance_id,
+ instance_kind=paired_kind,
+ ensure=False,
+ # Never bootstrap from this call: it can run while a SQLite writer
+ # lock is already held (queued-delivery recheck). Opening a second
+ # write connection here deadlocks; the interactive/UI path hoists
+ # bootstrap via remote_access.binding_is_ready(..., bootstrap=True).
+ bootstrap=False,
+ )
+ # An absent durable row is an upgrade artifact, not evidence the
+ # pairing is wrong. Identity matching below still applies; the
+ # authorization consumers (binding_is_ready) fail closed / bootstrap
+ # on their own path. Only an explicit reconciling/mismatched row
+ # means "do not project a Personal bypass from this snapshot".
+ state = remote_access_authorization_service.load_instance_binding_state(
+ ensure=False
+ )
+ if not ready:
+ # Absent row (upgrade of a known-kind pairing) AND reconciling /
+ # mismatched rows all fail closed for deferred/non-interactive
+ # consumers. Interactive callers hoist bootstrap via
+ # remote_access.binding_is_ready(..., bootstrap=True).
+ return None
+ if context.instance_kind is not None and (
+ not paired_instance_id or not paired_kind
+ ):
+ return None
+ snapshot_instance_id = context.instance_id
+ if (
+ snapshot_instance_id
+ and paired_instance_id
+ and snapshot_instance_id != paired_instance_id
+ ):
+ return None
+ if context.instance_kind and paired_kind and context.instance_kind != paired_kind:
+ return None
+ from vibe.authorization import instance_kind_is_unsupported
+
+ raw_snapshot_kind = snapshot.get("vibe_instance_kind")
+ if instance_kind_is_unsupported(raw_snapshot_kind):
+ # Same class as Web Push: a present-but-unrecognized kind is not a
+ # no-kind legacy snapshot. Fail closed for deferred execution.
+ return None
+ if context.instance_kind is not None or raw_snapshot_kind is not None:
+ return context
+ if context.organization_id or context.instance_access_source == "organization_group":
+ # Organization membership identity does not depend on the local pairing
+ # being ready; an unpaired install must not retire Org deferred work.
+ return context
+
+ # Released snapshots predate the instance-kind field. Recover their kind
+ # only when the snapshot still names the current server-owned instance. An
+ # unbound legacy snapshot cannot be attributed to a re-paired Personal
+ # instance, because doing so would turn old Organization work into a
+ # Personal ACL bypass.
+ pairing_state = _configured_resource_state()
+ if pairing_state.status in {
+ RESOURCE_BINDING_STATE_UNAVAILABLE,
+ RESOURCE_BINDING_STATE_UNPAIRED,
+ }:
+ # Kindless snapshots cannot keep executing as a bare Editor when the
+ # current pairing is unreadable or explicitly unpaired.
+ return None
+ paired_kind = pairing_state.instance_kind
+ if paired_kind not in {"personal", "organization"}:
+ # Preserve the valid legacy no-kind PAIRING path (runtime-ready
+ # credentials, kind not yet backfilled — PARTIAL).
+ return context
+ if not context.instance_id:
+ return None
+ return replace(context, instance_kind=paired_kind)
def _as_context(user_context: ResourceUserContext | Mapping[str, Any] | None) -> ResourceUserContext:
@@ -311,6 +427,648 @@ def _connection(connection: Connection | None) -> Iterator[Connection]:
yield active_connection
+def _configured_show_page_instance() -> tuple[str, str] | None | object:
+ try:
+ from config.v2_config import V2Config
+
+ cloud = V2Config.load().remote_access.vibe_cloud
+ credentials = cloud.runtime_credentials()
+ if credentials is None:
+ return None
+ if not isinstance(credentials, (tuple, list)) or len(credentials) != 3:
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ instance_id = _clean_optional_string(credentials[1])
+ if instance_id is None or cloud.instance_kind not in {"personal", "organization"}:
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ except (
+ AttributeError,
+ FileNotFoundError,
+ IndexError,
+ KeyError,
+ OSError,
+ TypeError,
+ ValueError,
+ ):
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ return instance_id, cloud.instance_kind
+
+
+def _configured_resource_state() -> ConfiguredResourceState:
+ """Return one typed, fail-closed read of the configured pairing state.
+
+ ``UNAVAILABLE`` is intentionally distinct from a successfully read
+ unpaired configuration. Migration provenance must never be sealed because
+ a transient config read failed.
+ """
+
+ try:
+ from config.v2_config import V2Config
+
+ loaded = V2Config.load(persist_migrations=False)
+ # Only pairing/vibe_cloud recovery makes this reader UNAVAILABLE.
+ # Unrelated-section warnings (e.g. Model Hub) must not block an
+ # intact Vibe Cloud pairing or seal snapshots against it.
+ pairing_warnings = tuple(
+ warning
+ for warning in getattr(loaded, "load_warnings", ())
+ if (
+ "remote_access" in warning
+ or "vibe_cloud" in warning
+ or (
+ "using recovery defaults" in warning
+ and "model_hub" not in warning
+ and "Recovered invalid config section" not in warning
+ )
+ or "not valid UTF-8" in warning
+ or "JSON could not be parsed" in warning
+ or "root is not an object" in warning
+ )
+ )
+ if pairing_warnings:
+ return ConfiguredResourceState(
+ status=RESOURCE_BINDING_STATE_UNAVAILABLE,
+ instance_id=None,
+ instance_kind=None,
+ runtime_ready=False,
+ )
+ cloud = loaded.remote_access.vibe_cloud
+ raw_instance_id = cloud.instance_id
+ instance_id = _clean_optional_string(raw_instance_id)
+ if raw_instance_id not in (None, "") and instance_id is None:
+ return ConfiguredResourceState(
+ status=RESOURCE_BINDING_STATE_UNAVAILABLE,
+ instance_id=None,
+ instance_kind=None,
+ runtime_ready=False,
+ )
+ instance_kind = (
+ cloud.instance_kind if cloud.instance_kind in {"personal", "organization"} else None
+ )
+ credentials = cloud.runtime_credentials()
+ except FileNotFoundError:
+ # A missing config file is an authoritative unpaired install, not a
+ # transient read failure. pair() must be allowed to redeem.
+ return ConfiguredResourceState(
+ status=RESOURCE_BINDING_STATE_UNPAIRED,
+ instance_id=None,
+ instance_kind=None,
+ runtime_ready=False,
+ )
+ except Exception:
+ return ConfiguredResourceState(
+ status=RESOURCE_BINDING_STATE_UNAVAILABLE,
+ instance_id=None,
+ instance_kind=None,
+ runtime_ready=False,
+ )
+
+ runtime_ready = False
+ if credentials is not None:
+ if not isinstance(credentials, (tuple, list)) or len(credentials) != 3:
+ return ConfiguredResourceState(
+ status=RESOURCE_BINDING_STATE_UNAVAILABLE,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ runtime_ready=False,
+ )
+ credential_instance_id = _clean_optional_string(credentials[1])
+ runtime_ready = instance_id is not None and credential_instance_id == instance_id
+
+ if instance_id is None:
+ return ConfiguredResourceState(
+ status=RESOURCE_BINDING_STATE_UNPAIRED,
+ instance_id=None,
+ instance_kind=instance_kind,
+ runtime_ready=False,
+ )
+ if runtime_ready and instance_kind in {"personal", "organization"}:
+ status = RESOURCE_BINDING_STATE_READY
+ else:
+ status = RESOURCE_BINDING_STATE_PARTIAL
+ return ConfiguredResourceState(
+ status=status,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ runtime_ready=runtime_ready,
+ )
+
+
+def _configured_resource_instance() -> tuple[str | None, str | None] | None | object:
+ """Return the current complete pairing identity used to fence deferred resources."""
+
+ configured = _configured_resource_state()
+ if configured.status == RESOURCE_BINDING_STATE_UNAVAILABLE:
+ return _CONFIGURED_SHOW_PAGE_INSTANCE_UNAVAILABLE
+ if configured.status != RESOURCE_BINDING_STATE_READY:
+ return None
+ return configured.instance_id, configured.instance_kind
+
+
+def _legacy_snapshot_has_organization_context(
+ context: ResourceUserContext,
+ snapshot: Mapping[str, Any],
+) -> bool:
+ """Detect Organization semantics retained by pre-binding snapshots."""
+
+ return bool(
+ context.organization_id
+ or context.organization_member_id
+ or context.organization_role
+ or context.instance_access_source == "organization_group"
+ or context.group_ids
+ or any(
+ snapshot.get(key)
+ for key in (
+ "vibe_organization_id",
+ "vibe_organization_member_id",
+ "vibe_organization_role",
+ "vibe_group_ids",
+ )
+ )
+ )
+
+
+def _legacy_deferred_context_binding(
+ snapshot: Mapping[str, Any],
+ *,
+ paired_instance_id: str,
+ paired_kind: str,
+) -> dict[str, str] | None:
+ """Return a safe current binding for one pre-instance metadata snapshot."""
+
+ context = current_resource_context(snapshot, is_remote=True)
+ if context.instance_role not in {"owner", "editor", "viewer"}:
+ return None
+
+ raw_instance_id = snapshot.get("vibe_instance_id")
+ snapshot_instance_id = _clean_optional_string(raw_instance_id)
+ if raw_instance_id is not None and snapshot_instance_id is None:
+ return None
+ if snapshot_instance_id and snapshot_instance_id != paired_instance_id:
+ return None
+
+ raw_kind = snapshot.get("vibe_instance_kind")
+ if raw_kind is not None and raw_kind not in {"personal", "organization"}:
+ return None
+ if raw_kind is not None and raw_kind != paired_kind:
+ return None
+
+ # The pairing kind is the only authoritative evidence for a legacy
+ # snapshot that predates both binding fields. Explicit Organization claims
+ # still contradict a Personal pairing, but access sources such as ``email``
+ # are shared by Personal and Organization instances and cannot choose a
+ # kind on their own.
+ if paired_kind == "personal" and _legacy_snapshot_has_organization_context(context, snapshot):
+ return None
+ inferred_kind = raw_kind or paired_kind
+ if inferred_kind != paired_kind:
+ return None
+ return {
+ "vibe_instance_id": paired_instance_id,
+ "vibe_instance_kind": paired_kind,
+ }
+
+
+def _connection_has_table(connection: Connection, table_name: str) -> bool:
+ """True when the table exists on this connection's schema.
+
+ The deferred-context migration also runs while an unversioned legacy
+ schema is being stamped, where newer tables may not exist yet. A missing
+ table simply has no deferred records to migrate.
+ """
+
+ return (
+ connection.execute(
+ sqlalchemy_text(
+ "select 1 from sqlite_master where type = 'table' and name = :name"
+ ),
+ {"name": table_name},
+ ).scalar_one_or_none()
+ is not None
+ )
+
+
+def _metadata_snapshot_lacks_binding(metadata: Any) -> bool:
+ """True when a deferred snapshot exists but carries no complete binding."""
+
+ if not isinstance(metadata, dict):
+ return False
+ snapshot = metadata.get(RESOURCE_USER_CONTEXT_METADATA_KEY)
+ if not isinstance(snapshot, Mapping):
+ return False
+ instance_id = _clean_optional_string(snapshot.get("vibe_instance_id"))
+ kind = snapshot.get("vibe_instance_kind")
+ return instance_id is None or kind not in {"personal", "organization"}
+
+
+def _has_unbound_deferred_snapshots(connection: Connection) -> bool:
+ """True when any released deferred record still lacks an instance binding.
+
+ A fresh install has nothing to protect: sealing or pinning a marker there
+ would only block the first real pairing. Only actual legacy snapshots make
+ the first migration opportunity meaningful.
+ """
+
+ if _connection_has_table(connection, "run_definitions"):
+ definition_rows = connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.definition_type.in_(("scheduled", "watch"))
+ )
+ )
+ for (metadata_json,) in definition_rows:
+ try:
+ metadata = json.loads(metadata_json or "{}")
+ except (TypeError, ValueError):
+ continue
+ if _metadata_snapshot_lacks_binding(metadata):
+ return True
+ if _connection_has_table(connection, "agent_runs"):
+ run_rows = connection.execute(
+ select(agent_runs.c.metadata_json).where(
+ agent_runs.c.status.in_(("pending", "queued", "processing", "running"))
+ )
+ )
+ for (metadata_json,) in run_rows:
+ try:
+ metadata = json.loads(metadata_json or "{}")
+ except (TypeError, ValueError):
+ continue
+ if _metadata_snapshot_lacks_binding(metadata):
+ return True
+ if _connection_has_table(connection, "message_deliveries"):
+ from storage.delivery_states import DELIVERY_STATE_MATRIX
+
+ executable_delivery_states = tuple(
+ state
+ for state, policy in DELIVERY_STATE_MATRIX.items()
+ if policy.ordering != "terminal"
+ )
+ delivery_rows = connection.execute(
+ select(message_deliveries.c.snapshot_json).where(
+ message_deliveries.c.snapshot_json.is_not(None),
+ message_deliveries.c.state.in_(executable_delivery_states),
+ )
+ )
+ for (snapshot_json,) in delivery_rows:
+ try:
+ snapshot = json.loads(snapshot_json or "{}")
+ metadata = json.loads(snapshot.get("metadata_json") or "{}")
+ except (AttributeError, TypeError, ValueError):
+ continue
+ if _metadata_snapshot_lacks_binding(metadata):
+ return True
+ return False
+
+
+def _migrate_deferred_metadata_value(
+ metadata: Any,
+ *,
+ paired_instance_id: str,
+ paired_kind: str,
+) -> dict[str, Any] | None:
+ if not isinstance(metadata, dict):
+ return None
+ snapshot = metadata.get(RESOURCE_USER_CONTEXT_METADATA_KEY)
+ if not isinstance(snapshot, Mapping):
+ return None
+ binding = _legacy_deferred_context_binding(
+ snapshot,
+ paired_instance_id=paired_instance_id,
+ paired_kind=paired_kind,
+ )
+ if binding is None:
+ return None
+ if all(snapshot.get(key) == value for key, value in binding.items()):
+ return None
+ migrated = dict(metadata)
+ migrated_snapshot = dict(snapshot)
+ migrated_snapshot.update(binding)
+ migrated[RESOURCE_USER_CONTEXT_METADATA_KEY] = migrated_snapshot
+ return migrated
+
+
+def migrate_legacy_deferred_resource_contexts(connection: Connection) -> dict[str, int]:
+ """Bind released deferred metadata to the still-current runtime pairing.
+
+ The migration is deliberately conservative and one-shot. It needs complete
+ runtime credentials and a known server-owned instance kind, and it only
+ updates a legacy snapshot when its existing instance evidence or explicit
+ Organization claims agree with that pairing. A transient configuration read
+ is not an unpaired state: it leaves the marker untouched so the same
+ pairing can retry later. A successfully observed unpaired state is sealed,
+ while a known instance with an unknown kind remains pending until that same
+ instance is authoritatively classified.
+ """
+
+ def _counts(
+ *,
+ binding_status: str,
+ definitions: int = 0,
+ runs: int = 0,
+ deliveries: int = 0,
+ ) -> dict[str, int | str]:
+ return {
+ "legacy_deferred_definitions": definitions,
+ "legacy_deferred_runs": runs,
+ "legacy_deferred_deliveries": deliveries,
+ RESOURCE_BINDING_STATUS_KEY: binding_status,
+ }
+
+ empty_unavailable = _counts(binding_status=RESOURCE_BINDING_STATE_UNAVAILABLE)
+ marker_value = connection.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key == LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY
+ )
+ ).scalar_one_or_none()
+ marker: dict[str, Any] | None = None
+ if marker_value is not None:
+ try:
+ parsed_marker = json.loads(marker_value)
+ except (TypeError, ValueError):
+ parsed_marker = None
+ if not isinstance(parsed_marker, dict):
+ # A corrupt marker cannot prove which pairing created the rows.
+ # Preserve fail-closed behavior instead of trying to insert a
+ # duplicate key or guessing a new binding.
+ return _counts(binding_status=RESOURCE_BINDING_STATE_UNAVAILABLE)
+ marker = parsed_marker
+ marker_state = marker.get("state")
+ if marker_state not in {"pending", "completed", "sealed_unattributed"}:
+ marker_state = "completed" if marker.get("completed_at") else "pending"
+ # Markers written by e64/d667 used ``completed`` with no instance ID
+ # for an unpaired first opportunity. Preserve that terminal meaning;
+ # never reinterpret it as a fresh migration opportunity.
+ if marker_state == "completed" and marker.get("instance_id") is None:
+ marker_state = "sealed_unattributed"
+ marker = {**marker, "state": marker_state}
+
+ configured = _configured_resource_state()
+ if configured.status == RESOURCE_BINDING_STATE_UNAVAILABLE:
+ # A read failure must not create ``pending(instance_id=None)`` or
+ # rewrite a known marker. Startup/heartbeat will retry this operation.
+ return empty_unavailable
+ current_instance_id = configured.instance_id
+ current_kind = (
+ configured.instance_kind
+ if configured.status == RESOURCE_BINDING_STATE_READY
+ else None
+ )
+ # PARTIAL still carries a known instance ID; heartbeat/backfill uses it to
+ # keep snapshots pending instead of sealing them as unattributed.
+
+ def write_marker(
+ *,
+ state: str,
+ instance_id: str | None,
+ instance_kind: str | None = None,
+ ) -> None:
+ now = _utc_now_iso()
+ payload: dict[str, Any] = {
+ "schema_version": 2,
+ "state": state,
+ "instance_id": instance_id,
+ "updated_at": now,
+ }
+ if instance_kind in {"personal", "organization"}:
+ payload["instance_kind"] = instance_kind
+ if state == "completed":
+ payload["completed_at"] = now
+ values = {
+ "value_json": json.dumps(payload, sort_keys=True, separators=(",", ":")),
+ "updated_at": now,
+ }
+ if marker is None:
+ connection.execute(
+ state_meta.insert().values(
+ key=LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,
+ **values,
+ )
+ )
+ else:
+ connection.execute(
+ update(state_meta)
+ .where(state_meta.c.key == LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY)
+ .values(**values)
+ )
+
+ if marker is not None and marker.get("state") in {"completed", "sealed_unattributed"}:
+ return _counts(binding_status=RESOURCE_BINDING_STATE_SEALED)
+
+ raw_marker_instance_id = marker.get("instance_id") if marker else None
+ marker_instance_id = (
+ _clean_optional_string(raw_marker_instance_id) if marker else None
+ )
+ if marker and raw_marker_instance_id is not None and marker_instance_id is None:
+ # A malformed marker cannot prove ownership. Keep the existing value
+ # intact and fail closed rather than guessing a new pairing.
+ return _counts(binding_status=RESOURCE_BINDING_STATE_UNAVAILABLE)
+ if marker is not None:
+ if marker_instance_id is None:
+ # No first pairing was available to prove ownership. A later
+ # pairing must not be allowed to claim these records.
+ write_marker(state="sealed_unattributed", instance_id=None)
+ return _counts(binding_status=RESOURCE_BINDING_STATE_SEALED)
+ if current_instance_id is None:
+ if configured.status == RESOURCE_BINDING_STATE_UNPAIRED:
+ write_marker(state="sealed_unattributed", instance_id=marker_instance_id)
+ return _counts(binding_status=RESOURCE_BINDING_STATE_SEALED)
+ return _counts(binding_status=configured.status)
+ if current_instance_id != marker_instance_id:
+ write_marker(state="sealed_unattributed", instance_id=marker_instance_id)
+ return _counts(binding_status=RESOURCE_BINDING_STATE_SEALED)
+
+ if configured.status == RESOURCE_BINDING_STATE_UNPAIRED:
+ if marker is None and not _has_unbound_deferred_snapshots(connection):
+ # A fresh install has no legacy snapshots to protect. Writing a
+ # sealed marker here would only block the first real pairing.
+ return _counts(binding_status=RESOURCE_BINDING_STATE_UNPAIRED)
+ write_marker(state="sealed_unattributed", instance_id=current_instance_id)
+ return _counts(binding_status=RESOURCE_BINDING_STATE_SEALED)
+ if configured.status != RESOURCE_BINDING_STATE_READY:
+ # A PARTIAL pairing still records its identity: the pending marker is
+ # what lets the SAME instance complete after credential repair while a
+ # DIFFERENT instance stays sealed out.
+ write_marker(state="pending", instance_id=current_instance_id)
+ return _counts(binding_status=configured.status)
+ if current_instance_id is None or current_kind not in {"personal", "organization"}:
+ # Defensive guard for a future state-reader change. This branch is
+ # never authoritative enough to complete a migration.
+ return _counts(binding_status=RESOURCE_BINDING_STATE_PARTIAL)
+ # C2 fence: this migration can run from a bare ensure_sqlite_state()
+ # without config_file_lock (taking it here would invert the canonical
+ # lock order against a peer holding config lock -> migration lock).
+ # Instead, refuse to bind snapshots when the durable binding row exists
+ # and disagrees with the pairing snapshot just read: a peer is mid-
+ # reclassification and owns this migration through its own transition.
+ from storage.remote_access_authorization_service import (
+ INSTANCE_BINDING_STATE_RECONCILING as _BINDING_RECONCILING,
+ _load_binding_state_from_connection as _load_binding_row,
+ )
+
+ try:
+ binding_row = _load_binding_row(connection)
+ except Exception:
+ binding_row = None
+ if binding_row is not None:
+ row_id = binding_row.get("instance_id")
+ row_kind = binding_row.get("instance_kind")
+ row_state = binding_row.get("state")
+ identity_matches = row_id == current_instance_id and (
+ row_kind == current_kind
+ or (row_state == _BINDING_RECONCILING and row_kind in {None, current_kind})
+ )
+ if not identity_matches:
+ write_marker(state="pending", instance_id=current_instance_id)
+ return _counts(binding_status=RESOURCE_BINDING_STATE_PARTIAL)
+ else:
+ # Known-kind config with no durable binding row is an upgrade
+ # artifact, not a validated pairing. Leave the opportunity pending
+ # so a later heartbeat/bootstrap can attribute snapshots after the
+ # server-owned kind is confirmed.
+ write_marker(state="pending", instance_id=current_instance_id)
+ return _counts(binding_status=RESOURCE_BINDING_STATE_PARTIAL)
+ paired_instance_id = current_instance_id
+ paired_kind = current_kind
+
+ counts = {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ RESOURCE_BINDING_STATUS_KEY: RESOURCE_BINDING_STATE_READY,
+ }
+ definition_rows = (
+ connection.execute(
+ select(run_definitions.c.id, run_definitions.c.metadata_json).where(
+ run_definitions.c.definition_type.in_(("scheduled", "watch"))
+ )
+ ).mappings()
+ if _connection_has_table(connection, "run_definitions")
+ else ()
+ )
+ for row in definition_rows:
+ try:
+ metadata = json.loads(row["metadata_json"] or "{}")
+ except (TypeError, ValueError):
+ continue
+ migrated = _migrate_deferred_metadata_value(
+ metadata,
+ paired_instance_id=paired_instance_id,
+ paired_kind=paired_kind,
+ )
+ if migrated is None:
+ continue
+ connection.execute(
+ update(run_definitions)
+ .where(run_definitions.c.id == row["id"])
+ .values(
+ metadata_json=json.dumps(
+ migrated,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ )
+ )
+ counts["legacy_deferred_definitions"] += 1
+
+ run_rows = (
+ connection.execute(
+ select(agent_runs.c.id, agent_runs.c.metadata_json)
+ .where(agent_runs.c.status.in_(("pending", "queued", "processing", "running")))
+ ).mappings()
+ if _connection_has_table(connection, "agent_runs")
+ else ()
+ )
+ for row in run_rows:
+ try:
+ metadata = json.loads(row["metadata_json"] or "{}")
+ except (TypeError, ValueError):
+ continue
+ migrated = _migrate_deferred_metadata_value(
+ metadata,
+ paired_instance_id=paired_instance_id,
+ paired_kind=paired_kind,
+ )
+ if migrated is None:
+ continue
+ connection.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == row["id"])
+ .values(
+ metadata_json=json.dumps(
+ migrated,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ ),
+ updated_at=_utc_now_iso(),
+ )
+ )
+ counts["legacy_deferred_runs"] += 1
+
+ from storage.delivery_states import DELIVERY_STATE_MATRIX
+
+ executable_delivery_states = tuple(
+ state
+ for state, policy in DELIVERY_STATE_MATRIX.items()
+ if policy.ordering != "terminal"
+ )
+ delivery_rows = (
+ connection.execute(
+ select(
+ message_deliveries.c.id,
+ message_deliveries.c.snapshot_json,
+ ).where(
+ message_deliveries.c.snapshot_json.is_not(None),
+ message_deliveries.c.state.in_(executable_delivery_states),
+ )
+ ).mappings()
+ if _connection_has_table(connection, "message_deliveries")
+ else ()
+ )
+ for row in delivery_rows:
+ try:
+ snapshot = json.loads(row["snapshot_json"] or "{}")
+ metadata = json.loads(snapshot.get("metadata_json") or "{}")
+ except (AttributeError, TypeError, ValueError):
+ continue
+ migrated_metadata = _migrate_deferred_metadata_value(
+ metadata,
+ paired_instance_id=paired_instance_id,
+ paired_kind=paired_kind,
+ )
+ if migrated_metadata is None:
+ continue
+ snapshot["metadata_json"] = json.dumps(
+ migrated_metadata,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ snapshot_json = json.dumps(
+ snapshot,
+ ensure_ascii=False,
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ snapshot_sha256 = hashlib.sha256(snapshot_json.encode("utf-8")).hexdigest()
+ connection.execute(
+ update(message_deliveries)
+ .where(message_deliveries.c.id == row["id"])
+ .values(
+ snapshot_json=snapshot_json,
+ snapshot_sha256=snapshot_sha256,
+ updated_at=_utc_now_iso(),
+ )
+ )
+ counts["legacy_deferred_deliveries"] += 1
+ write_marker(
+ state="completed",
+ instance_id=paired_instance_id,
+ instance_kind=paired_kind,
+ )
+ return counts
+
def _stored_resource_organizations(connection: Connection) -> set[str]:
raw_value = connection.execute(
select(state_meta.c.value_json).where(state_meta.c.key == RESOURCE_ORGANIZATIONS_META_KEY)
@@ -568,6 +1326,8 @@ def _policy_allows(
) -> bool:
if context.is_instance_owner:
return True
+ if resource_kind == "agent" and context.is_personal_instance:
+ return context.can_use_resource(resource_kind)
# Skill and Vault ACL rows remain persisted for compatibility, but Editor
# runtime access intentionally ignores them for validated remote sessions.
# Direct non-remote contexts still use the stored policy so service-level
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 6cf739a8f..1183bcfed 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -60,6 +60,7 @@ def test_context_from_session_payload_keeps_role_and_acl_claims() -> None:
"sub": "user-1",
"vibe_instance_role": "editor",
"vibe_instance_access_source": "organization_group",
+ "vibe_instance_kind": "organization",
"vibe_organization_id": "org-1",
"vibe_organization_member_id": "membership-1",
"vibe_organization_role": "member",
@@ -68,10 +69,27 @@ def test_context_from_session_payload_keeps_role_and_acl_claims() -> None:
)
assert context.instance_role == "editor"
assert context.group_ids == frozenset({"group-a"})
+ assert context.is_organization_instance
assert context.can_chat
assert not context.can_manage_instance
+def test_context_from_session_payload_only_recognizes_known_instance_kinds() -> None:
+ base = {
+ "sub": "user-1",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "owner",
+ }
+ personal = context_from_session_payload({**base, "vibe_instance_kind": "personal"})
+ unknown = context_from_session_payload({**base, "vibe_instance_kind": "workspace"})
+
+ assert personal.is_personal_instance
+ assert not personal.is_organization_instance
+ assert personal.instance_kind == "personal"
+ assert unknown.instance_kind is None
+ assert not unknown.is_personal_instance
+
+
def test_show_page_email_context_is_exactly_page_scoped() -> None:
context = context_from_session_payload(
{
@@ -161,11 +179,13 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("POST", "/api/sessions/session-1/messages"),
("POST", "/api/sessions/session-1/attachments"),
("POST", "/api/sessions/session-1/cancel"),
- ("GET", "/api/show-pages/session-1"),
("POST", "/api/show-pages/session-1/ensure"),
("POST", "/api/show-pages/session-1/availability"),
("POST", "/api/show-pages/session-1/access-settings/read"),
("POST", "/api/show-pages/session-1/access-settings/apply"),
+ # The Web UI's ShowPageShareControl reads the page it can mutate;
+ # editors must keep GET access (regression: PR #1606 round 1).
+ ("GET", "/api/show-pages/session-1"),
)
for method, path in editor_examples:
assert http_authorization_policy(method, path).minimum_role == "editor", path
diff --git a/tests/test_project_access_service.py b/tests/test_project_access_service.py
index 01f9ad89d..626c250a3 100644
--- a/tests/test_project_access_service.py
+++ b/tests/test_project_access_service.py
@@ -15,6 +15,7 @@ def _context(
email: str = "[email protected]",
organization_id: str | None = None,
group_ids: tuple[str, ...] = (),
+ instance_kind: str | None = None,
) -> AuthorizationContext:
return AuthorizationContext(
instance_role=role,
@@ -22,6 +23,7 @@ def _context(
organization_id=organization_id,
group_ids=frozenset(group_ids),
is_remote=True,
+ instance_kind=instance_kind,
)
@@ -128,6 +130,44 @@ def test_restricted_policy_matches_email_domain_and_group(tmp_path) -> None:
)
+def test_personal_editor_ignores_project_organization_acl(tmp_path) -> None:
+ engine, project = _engine_with_project(tmp_path)
+ intent = _intent(
+ project["id"],
+ 1,
+ bindings=[
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "viewer",
+ }
+ ],
+ )
+ personal_editor = _context(
+ "editor",
+ instance_kind="personal",
+ )
+ personal_viewer = _context(
+ "viewer",
+ instance_kind="personal",
+ )
+ organization_editor = _context("editor", email="[email protected]")
+
+ with engine.begin() as conn:
+ assert project_access_service.apply_project_access_intent(conn, intent).outcome == "applied"
+ assert project_access_service.get_effective_project_role(
+ conn, personal_editor, project["id"]
+ ) == "editor"
+ assert project_access_service.get_effective_project_role(
+ conn, personal_viewer, project["id"]
+ ) is None
+ assert project_access_service.get_effective_project_role(
+ conn, organization_editor, project["id"]
+ ) is None
+
+
def test_highest_match_is_capped_by_instance_role(tmp_path) -> None:
engine, project = _engine_with_project(tmp_path)
intent = _intent(
diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.py
index 2375dcdcb..639eba273 100644
--- a/tests/test_remote_access_vibe_cloud.py
+++ b/tests/test_remote_access_vibe_cloud.py
@@ -1474,6 +1474,12 @@ def test_report_runtime_status_backfills_instance_kind_once(monkeypatch, tmp_pat
"_json_request",
lambda *args, **kwargs: {"ok": True, "instance_kind": "organization"},
)
+ migration_calls = []
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: migration_calls.append(True),
+ )
real_save_config = remote_access.api.save_config
saves = []
@@ -1486,11 +1492,115 @@ def test_report_runtime_status_backfills_instance_kind_once(monkeypatch, tmp_pat
assert remote_access.report_runtime_status(config)["ok"] is True
assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
assert remote_access.report_runtime_status(V2Config.load())["ok"] is True
+ assert migration_calls == [True]
assert saves == [
{"remote_access": {"vibe_cloud": {"instance_kind": "organization"}}}
]
+def test_report_runtime_status_binds_pending_deferred_contexts_through_the_real_path(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """A long-running upgraded service must not need another initialization.
+
+ The heartbeat is the only place the authoritative kind arrives, so it owns
+ rerunning the pending migration itself rather than relying on a later
+ ``ensure_sqlite_state()`` call.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_secret = "instance-secret"
+ cloud.instance_kind = ""
+ config.save()
+
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import _run_sqlite_data_migrations, ensure_sqlite_state
+ from storage.models import run_definitions, state_meta
+ from storage.resource_access_service import (
+ LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,
+ RESOURCE_USER_CONTEXT_METADATA_KEY,
+ resource_user_context_from_metadata,
+ )
+
+ legacy_metadata = {
+ RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-editor",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ ensure_sqlite_state()
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ connection.execute(
+ run_definitions.insert().values(
+ id="legacy-task",
+ definition_type="scheduled",
+ name="legacy task",
+ message="run",
+ schedule_type="interval",
+ enabled=1,
+ created_at="2026-08-20T00:00:00Z",
+ updated_at="2026-08-20T00:00:00Z",
+ metadata_json=json.dumps(legacy_metadata),
+ )
+ )
+ counts = _run_sqlite_data_migrations(connection)
+ assert {
+ key: counts[key]
+ for key in (
+ "legacy_deferred_definitions",
+ "legacy_deferred_runs",
+ "legacy_deferred_deliveries",
+ )
+ } == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ marker = json.loads(
+ connection.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key == LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY
+ )
+ ).scalar_one()
+ )
+ assert marker["state"] == "pending"
+ assert marker["instance_id"] == "inst_123"
+
+ monkeypatch.setattr(
+ remote_access,
+ "runtime_status_payload",
+ lambda *args, **kwargs: {"event": "heartbeat"},
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_json_request",
+ lambda *args, **kwargs: {"ok": True, "instance_kind": "personal"},
+ )
+
+ assert remote_access.report_runtime_status(config)["ok"] is True
+
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "personal"
+ with engine.connect() as connection:
+ metadata = json.loads(
+ connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.id == "legacy-task"
+ )
+ ).scalar_one()
+ )
+ snapshot = metadata[RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert snapshot["vibe_instance_id"] == "inst_123"
+ assert snapshot["vibe_instance_kind"] == "personal"
+ assert resource_user_context_from_metadata(metadata) is not None
+
+
@pytest.mark.parametrize("reported_kind", [None, "enterprise", "", 7])
def test_report_runtime_status_ignores_invalid_instance_kind(
monkeypatch,
@@ -1642,6 +1752,11 @@ def test_pair_persists_with_locked_incremental_config_save(monkeypatch) -> None:
},
)
monkeypatch.setattr(remote_access.api, "save_config", lambda payload: save_payloads.append(payload) or config)
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},
+ )
monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True, "running": True})
monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True, "running": True, "paired": True})
monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})
@@ -1677,7 +1792,20 @@ def test_pair_accepts_legacy_or_invalid_instance_kind_as_unknown(monkeypatch, re
if reported_kind is not None:
response["instance_kind"] = reported_kind
monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: response)
- monkeypatch.setattr(remote_access.api, "save_config", lambda payload: save_payloads.append(payload) or config)
+
+ def fake_save_config(payload, **kwargs):
+ save_payloads.append(payload)
+ # Mirror the real save: the returned config carries the persisted
+ # pairing identity, which pair() verifies before publishing a binding.
+ config.remote_access.vibe_cloud.instance_id = payload["remote_access"]["vibe_cloud"]["instance_id"]
+ return config
+
+ monkeypatch.setattr(remote_access.api, "save_config", fake_save_config)
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},
+ )
monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True})
monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True})
monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})
@@ -1756,6 +1884,170 @@ def test_pair_reports_success_when_connector_start_fails(monkeypatch, tmp_path)
assert saved_payload["remote_access"]["vibe_cloud"]["tunnel_token"] == "tunnel-token"
+def _pair_redeem_response(*, instance_id: str = "inst_new") -> dict[str, str]:
+ return {
+ "instance_id": instance_id,
+ "instance_kind": "personal",
+ "client_id": "vr_client_new",
+ "issuer": "https://backend.test",
+ "authorization_endpoint": "https://backend.test/oauth/authorize",
+ "token_endpoint": "https://backend.test/oauth/token",
+ "jwks_uri": "https://backend.test/oauth/jwks.json",
+ "public_url": "https://new.avibe.bot",
+ "redirect_uri": "https://new.avibe.bot/auth/callback",
+ "tunnel_token": "new-tunnel-token",
+ "instance_secret": "new-instance-secret",
+ }
+
+
+def test_pair_aborts_when_legacy_provenance_cannot_be_read(monkeypatch, tmp_path) -> None:
+ """An unavailable pre-pair config read must not replace the pairing."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.enabled = False
+ config.remote_access.vibe_cloud.instance_id = ""
+ config.remote_access.vibe_cloud.instance_secret = ""
+ config.save()
+ original = json.loads((tmp_path / "config" / "config.json").read_text(encoding="utf-8"))
+
+ redeem_calls: list[str] = []
+
+ def fake_request(url: str, payload: dict, timeout: float = 20.0, **kwargs):
+ redeem_calls.append(url)
+ return _pair_redeem_response()
+
+ monkeypatch.setattr(remote_access, "_json_request", fake_request)
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: (_ for _ in ()).throw(RuntimeError("legacy_deferred_context_provenance_unavailable")),
+ )
+ saves: list[dict] = []
+ monkeypatch.setattr(
+ remote_access.api,
+ "save_config",
+ lambda payload, **kwargs: saves.append(payload) or config,
+ )
+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True})
+
+ result = remote_access.pair("vrp_test", "https://backend.test")
+
+ assert result["ok"] is False
+ assert result["error"] == "pairing_provenance_unavailable"
+ assert saves == []
+ assert redeem_calls == []
+ assert json.loads((tmp_path / "config" / "config.json").read_text(encoding="utf-8")) == original
+
+
+def test_pair_aborts_when_pending_migration_fails(monkeypatch, tmp_path) -> None:
+ """A failing deferred migration must not let pair() stamp a new identity."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ config.remote_access.vibe_cloud.enabled = False
+ config.remote_access.vibe_cloud.instance_id = ""
+ config.save()
+ original = json.loads((tmp_path / "config" / "config.json").read_text(encoding="utf-8"))
+
+ redeem_calls: list[str] = []
+
+ def fake_request(url: str, payload: dict, timeout: float = 20.0, **kwargs):
+ redeem_calls.append(url)
+ return _pair_redeem_response()
+
+ monkeypatch.setattr(remote_access, "_json_request", fake_request)
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: (_ for _ in ()).throw(RuntimeError("sqlite locked")),
+ )
+ saves: list[dict] = []
+ monkeypatch.setattr(
+ remote_access.api,
+ "save_config",
+ lambda payload, **kwargs: saves.append(payload) or config,
+ )
+
+ result = remote_access.pair("vrp_test", "https://backend.test")
+
+ assert result["ok"] is False
+ assert result["error"] == "pairing_provenance_unavailable"
+ assert saves == []
+ assert redeem_calls == []
+ assert json.loads((tmp_path / "config" / "config.json").read_text(encoding="utf-8")) == original
+
+
+def test_pair_redeems_when_config_file_is_absent(monkeypatch, tmp_path) -> None:
+ """A fresh install with no config is authoritative unpaired, not unavailable."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config_path = tmp_path / "config" / "config.json"
+ if config_path.exists():
+ config_path.unlink()
+
+ redeem_calls: list[str] = []
+
+ def fake_request(url: str, payload: dict, timeout: float = 20.0, **kwargs):
+ redeem_calls.append(url)
+ return _pair_redeem_response()
+
+ monkeypatch.setattr(remote_access, "_json_request", fake_request)
+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True, "running": True})
+ monkeypatch.setattr(
+ remote_access,
+ "status",
+ lambda next_config=None: {"ok": True, "running": True, "paired": True},
+ )
+ monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})
+ monkeypatch.setattr(remote_access, "_transition_instance_binding", lambda **kwargs: {"ok": True, "ready": True})
+
+ result = remote_access.pair("vrp_test", "https://backend.test")
+
+ assert result["ok"] is True
+ assert redeem_calls
+ assert "/pairing/redeem" in redeem_calls[0]
+
+
+def test_binding_transition_initializes_sqlite_before_taking_config_lock(monkeypatch, tmp_path) -> None:
+ """Lock order: ensure_sqlite_state must complete before config_file_lock."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _config().save()
+ order: list[str] = []
+ real_ensure = __import__("storage.importer", fromlist=["ensure_sqlite_state"]).ensure_sqlite_state
+ real_lock = __import__("config.v2_config", fromlist=["config_file_lock"]).config_file_lock
+
+ def tracking_ensure(*args, **kwargs):
+ order.append("sqlite")
+ return real_ensure(*args, **kwargs)
+
+ from contextlib import contextmanager
+
+ @contextmanager
+ def tracking_lock(*args, **kwargs):
+ order.append("config")
+ with real_lock(*args, **kwargs):
+ yield
+
+ monkeypatch.setattr("storage.importer.ensure_sqlite_state", tracking_ensure)
+ monkeypatch.setattr("config.v2_config.config_file_lock", tracking_lock)
+ monkeypatch.setattr(
+ "storage.remote_access_authorization_service._ensure_sqlite_state",
+ lambda: tracking_ensure(),
+ )
+
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+
+ assert "sqlite" in order
+ assert "config" in order
+ assert order.index("sqlite") < order.index("config")
+
+
+
def test_pair_rejects_origin_update_failure_before_saving_config(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _config()
@@ -1799,6 +2091,11 @@ def test_pair_rejects_origin_update_failure_before_saving_config(monkeypatch, tm
def test_pair_returns_structured_error_when_backend_request_fails(monkeypatch) -> None:
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},
+ )
monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: (_ for _ in ()).throw(OSError("offline")))
result = remote_access.pair("vrp_test", "https://backend.test")
@@ -1812,6 +2109,11 @@ def test_pair_preserves_backend_error_response(monkeypatch) -> None:
def fake_request(*args, **kwargs):
raise remote_access.BackendRequestError(400, {"error": "invalid_pairing_key"})
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},
+ )
monkeypatch.setattr(remote_access, "_json_request", fake_request)
result = remote_access.pair("vrp_test", "https://backend.test")
@@ -1841,6 +2143,11 @@ def test_pair_queues_lifecycle_status_for_drain(monkeypatch, tmp_path) -> None:
},
)
monkeypatch.setattr(remote_access.api, "save_config", lambda payload: config)
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},
+ )
monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": False, "error": "cloudflared_spawn_failed"})
monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True, "running": False, "paired": True})
monkeypatch.setattr(
@@ -3056,3 +3363,146 @@ def test_ra_tq_030_connectivity_diagnostics_filters_dns_by_selected_family(
assert result["dns"]["status"] == "unavailable"
assert result["http2"]["status"] == "unknown"
+
+
+def test_unknown_kind_pairing_stays_usable_after_pair(monkeypatch, tmp_path) -> None:
+ """Regression PR #1606 r1: no-kind pairings must not park in reconciling."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ response = {
+ "instance_id": "inst_456",
+ "client_id": "vr_client_456",
+ "issuer": "https://backend.test",
+ "authorization_endpoint": "https://backend.test/oauth/authorize",
+ "token_endpoint": "https://backend.test/oauth/token",
+ "jwks_uri": "https://backend.test/oauth/jwks.json",
+ "public_url": "https://new.avibe.bot",
+ "redirect_uri": "https://new.avibe.bot/auth/callback",
+ "tunnel_token": "tunnel-token",
+ "instance_secret": "instance-secret",
+ }
+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: response)
+
+ def fake_save_config(payload, **kwargs):
+ config.remote_access.vibe_cloud.instance_id = payload["remote_access"]["vibe_cloud"]["instance_id"]
+ return config
+
+ monkeypatch.setattr(remote_access.api, "save_config", fake_save_config)
+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True})
+ monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True})
+ monkeypatch.setattr(remote_access, "report_runtime_status", lambda *args, **kwargs: {"ok": True})
+
+ assert remote_access.pair("vrp_test", "https://backend.test")["ok"] is True
+
+ from storage import remote_access_authorization_service
+
+ state = remote_access_authorization_service.load_instance_binding_state(ensure=False)
+ assert state is not None
+ assert state["state"] == remote_access_authorization_service.INSTANCE_BINDING_STATE_PENDING_KIND
+ assert state["instance_id"] == "inst_456"
+ # The legacy no-kind path stays usable for every authorization consumer.
+ assert remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id="inst_456",
+ instance_kind=None,
+ ensure=False,
+ ) is True
+ # A kind-specific bypass is still not claimable from this state.
+ assert remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id="inst_456",
+ instance_kind="personal",
+ ensure=False,
+ ) is False
+
+
+def test_pair_refuses_to_publish_binding_for_a_replaced_instance(monkeypatch, tmp_path) -> None:
+ """Regression PR #1606 r1: pairing save + transition are one critical section."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ monkeypatch.setattr(remote_access, "_json_request", lambda *args, **kwargs: _pair_redeem_response())
+
+ def racing_save_config(payload, **kwargs):
+ # Simulate a peer's pairing landing between our save and verification:
+ # the persisted config no longer names the instance we redeemed.
+ config.remote_access.vibe_cloud.instance_id = "inst_other"
+ return config
+
+ monkeypatch.setattr(remote_access.api, "save_config", racing_save_config)
+ monkeypatch.setattr(
+ remote_access,
+ "_run_pending_deferred_context_migration",
+ lambda: {"legacy_deferred_definitions": 0, "legacy_deferred_runs": 0, "legacy_deferred_deliveries": 0, "binding_status": "sealed"},
+ )
+ monkeypatch.setattr(remote_access, "start", lambda next_config: {"ok": True})
+ monkeypatch.setattr(remote_access, "status", lambda next_config=None: {"ok": True})
+
+ result = remote_access.pair("vrp_test", "https://backend.test")
+
+ assert result["ok"] is False
+ assert result["error"] == "pairing_reconciliation_failed"
+ assert result["detail"] == "persisted_instance_mismatch"
+
+ from storage import remote_access_authorization_service
+
+ state = remote_access_authorization_service.load_instance_binding_state(ensure=False)
+ redeemed = _pair_redeem_response()["instance_id"]
+ assert state is None or state.get("instance_id") != redeemed
+
+
+def test_overlapping_heartbeat_refuses_stale_personal_kind(monkeypatch, tmp_path) -> None:
+ """Regression PR #1606 r4: capture generation BEFORE the network call.
+
+ Two overlapping runtime-status requests: the newer Organization response
+ lands first; the older Personal response must CAS-fail and leave the
+ binding Organization.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _config()
+ cloud = config.remote_access.vibe_cloud
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_secret = "instance-secret"
+ cloud.instance_kind = "personal"
+ config.save()
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+ monkeypatch.setattr(
+ remote_access,
+ "_json_request",
+ lambda *args, **kwargs: {"ok": True, "instance_kind": "organization"},
+ )
+
+ from storage import remote_access_authorization_service
+
+ captured = remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ # Newer Organization heartbeat lands first.
+ assert remote_access.report_runtime_status(config)["ok"] is True
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
+ # Older in-flight Personal response, captured before the Org persist,
+ # must CAS-fail against the newer generation.
+ refused = remote_access._persist_instance_kind(
+ "inst_123",
+ "personal",
+ reconcile=True,
+ expected_binding_generation=captured,
+ )
+ assert refused is False
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
+ state = remote_access_authorization_service.load_instance_binding_state(ensure=False)
+ assert state is not None
+ assert state["instance_kind"] == "organization"
+ assert state["generation"] > captured
+ monkeypatch.setattr(remote_access, "runtime_status_payload", lambda *args, **kwargs: {"event": "heartbeat"})
+ monkeypatch.setattr(
+ remote_access,
+ "_json_request",
+ lambda *args, **kwargs: {"ok": True, "instance_kind": "organization"},
+ )
+ assert remote_access.report_runtime_status(V2Config.load())["ok"] is True
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
diff --git a/tests/test_remote_authorization_revision.py b/tests/test_remote_authorization_revision.py
index e785bb8d7..122d81b38 100644
--- a/tests/test_remote_authorization_revision.py
+++ b/tests/test_remote_authorization_revision.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import asyncio
from concurrent.futures import ThreadPoolExecutor
+import itertools
+import json
import threading
import time
from typing import Any
@@ -43,6 +45,9 @@ def _clear_authorization_refresh_process_state():
def _paired_config(tmp_path, *, revision: int = 41) -> V2Config:
+ import os
+
+ os.environ["AVIBE_HOME"] = str(tmp_path)
config = V2Config(
mode="self_host",
version="v2",
@@ -69,6 +74,8 @@ def _paired_config(tmp_path, *, revision: int = 41) -> V2Config:
remote_access._clear_authorization_revision_cache()
remote_access._replace_authorization_revision(config, revision)
return config
+ # Binding-row seeding is the CALLER's job: some tests need an absent
+ # row (upgrade path), others need a ready row (concurrent resolvers).
def _organization_claims(
@@ -169,150 +176,229 @@ def test_personal_session_slides_past_claim_and_original_identity_deadlines(
assert result.payload["claims_issued_at"] == base
-def test_personal_revision_hint_refreshes_in_background_without_blocking(
+def test_validated_remote_payload_projects_paired_instance_kind(tmp_path):
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ payload = remote_access._validated_authorization_payload(
+ config,
+ {
+ "sub": "personal-user",
+ "email": "[email protected]",
+ "instance_id": "inst_123",
+ },
+ {
+ "id": "authorization-1",
+ "claims": {**_organization_claims(config), "vibe_instance_kind": "personal"},
+ },
+ )
+
+ assert payload is not None
+ assert context_from_session_payload(payload).is_personal_instance
+
+
+def test_cached_authorization_from_previous_instance_kind_refreshes_before_personal_bypass(
monkeypatch,
tmp_path,
):
config = _paired_config(tmp_path)
- config.remote_access.vibe_cloud.instance_kind = "personal"
cookie = _organization_cookie(config)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- entered = threading.Event()
- release = threading.Event()
- finished = threading.Event()
+ calls = []
- def unavailable(*args, **kwargs):
- entered.set()
- release.wait(timeout=1)
- finished.set()
- raise remote_access.BackendRequestError(503, {"error": "unavailable"})
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ calls.append(payload)
+ return _authorization_context_response(
+ config,
+ payload,
+ revision=41,
+ instance_kind="personal",
+ )
- monkeypatch.setattr(remote_access, "_device_json_request", unavailable)
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
result = remote_access.resolve_current_authorization(config, identity)
assert result.current is True
+ assert result.refreshed is True
assert result.policy == "personal"
- assert entered.wait(timeout=1)
- assert finished.is_set() is False
- release.set()
- assert finished.wait(timeout=1)
+ assert len(calls) == 1
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=int(time.time()),
+ )
+ assert record is not None
+ assert record["claims"]["vibe_instance_kind"] == "personal"
-def test_organization_scheduled_refresh_does_not_block_when_revision_matches(
- monkeypatch,
- tmp_path,
-):
+def test_partial_pairing_cannot_restore_cached_personal_authorization(tmp_path):
config = _paired_config(tmp_path)
- base = int(time.time())
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = ""
+ config.save()
+
+ payload = remote_access._validated_authorization_payload(
+ config,
+ {
+ "sub": "personal-user",
+ "email": "[email protected]",
+ "instance_id": "inst_123",
+ },
+ {
+ "id": "authorization-1",
+ "claims": {**_organization_claims(config), "vibe_instance_kind": "organization"},
+ },
+ )
+
+ assert payload is None
cookie = _organization_cookie(config)
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- refresh_at = base + remote_access.ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS + 1
- assert remote_access_authorization_service.mark_matching_revision_checked(
- instance_id="inst_123",
- authorization_revision=41,
- checked_at=refresh_at,
- ) == 1
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 41)
- scheduled = []
- monkeypatch.setattr(
- remote_access,
- "_schedule_authorization_refresh",
- lambda *args, **kwargs: scheduled.append((args, kwargs)),
+ resolution = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ allow_refresh=False,
)
- monkeypatch.setattr(
- remote_access,
- "_refresh_authorization_context",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- AssertionError("routine matching-revision refresh blocked the request")
- ),
+ assert resolution.state == "unavailable"
+ assert resolution.reason == "pairing_unavailable"
+
+
+def test_partial_pairing_preserves_exact_show_page_email_grant(tmp_path):
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = ""
+ config.save()
+ cookie = remote_access.make_session_cookie(
+ config,
+ "viewer-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "show-1",
+ "vibe_instance_authorization_revision": 41,
+ },
)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
- result = remote_access.resolve_current_authorization(
+ resolution = remote_access.resolve_current_authorization(
config,
identity,
- now=refresh_at,
+ allow_refresh=False,
)
- assert result.current is True
- assert result.policy == "organization"
- assert result.reason == "authorization_refresh_scheduled"
- assert len(scheduled) == 1
+ assert resolution.current is True
+ assert resolution.payload is not None
+ assert resolution.payload["vibe_show_page_id"] == "show-1"
-def test_organization_refresh_grace_expiry_and_recovery(monkeypatch, tmp_path):
- """Scenario: AUTH-SETUP-403."""
+def test_organization_to_personal_reclassification_revalidates_before_the_bypass(
+ monkeypatch,
+ tmp_path,
+):
+ """A reclassified pairing must re-earn every instance-scoped authorization."""
config = _paired_config(tmp_path)
- base = int(time.time())
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
cookie = _organization_cookie(config)
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- checked_at = base + remote_access.ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS
- assert remote_access_authorization_service.mark_matching_revision_checked(
+ reference = identity["authorization_ref"]
+ now = int(time.time())
+ admitted = remote_access_authorization_service.load_reference_record(
+ reference=reference,
instance_id="inst_123",
- authorization_revision=41,
- checked_at=checked_at,
- ) == 1
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- remote_access.BackendRequestError(503, {"error": "unavailable"})
- ),
+ subject="user-1",
+ now=now,
)
+ assert admitted is not None
+ assert admitted["authorization_state"] == "current"
- within_grace = remote_access.resolve_current_authorization(
- config,
- identity,
- now=checked_at + 1,
+ assert remote_access._persist_instance_kind("inst_123", "personal", reconcile=True)
+
+ reclassified = V2Config.load()
+ assert reclassified.remote_access.vibe_cloud.instance_kind == "personal"
+ invalidated = remote_access_authorization_service.load_reference_record(
+ reference=reference,
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
- assert within_grace.current is True
- assert within_grace.reason == "authorization_grace"
+ assert invalidated is not None
+ assert invalidated["authorization_state"] == "stale"
- remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
- after_grace = remote_access.resolve_current_authorization(
- config,
+ # The cached Organization claims must not be re-projected as Personal.
+ blocked = remote_access.resolve_current_authorization(
+ reclassified,
identity,
- now=checked_at + remote_access.ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS + 1,
+ allow_refresh=False,
)
- assert after_grace.state == "unavailable"
- assert after_grace.reason == "authorization_grace_expired"
+ assert blocked.current is False
+ assert blocked.reason == "authorization_context_missing"
- remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ calls = []
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ calls.append(payload)
+ return _authorization_context_response(
config,
payload,
- revision=42,
- ),
- )
- recovered = remote_access.resolve_current_authorization(
- config,
- identity,
- now=checked_at + remote_access.ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS + 2,
+ revision=41,
+ instance_kind="personal",
+ )
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+
+ result = remote_access.resolve_current_authorization(reclassified, identity)
+
+ assert result.current is True
+ assert result.refreshed is True
+ assert result.policy == "personal"
+ # Synchronous revalidation, not a background hint that would let the
+ # Personal bypass answer this very request from the stale row.
+ assert len(calls) == 1
+ revalidated = remote_access_authorization_service.load_reference_record(
+ reference=reference,
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
- assert recovered.current is True
- assert recovered.refreshed is True
- assert recovered.payload["vibe_instance_authorization_revision"] == 42
+ assert revalidated is not None
+ assert revalidated["authorization_state"] == "current"
+ assert revalidated["claims"]["vibe_instance_kind"] == "personal"
-def test_unknown_instance_kind_backfills_without_failing_valid_access(
+def test_instance_kind_persistence_failure_leaves_no_kind_tagged_current_row(
monkeypatch,
tmp_path,
):
+ """A failed kind write must not leave a usable Personal projection behind."""
+
config = _paired_config(tmp_path)
config.remote_access.vibe_cloud.instance_kind = ""
+ config.save()
cookie = _organization_cookie(config)
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ reference = identity["authorization_ref"]
+ now = int(time.time())
+ # Collapse the failure backoff so the retry below exercises the network
+ # path instead of the short-circuit that protects the backend.
+ monkeypatch.setattr(remote_access, "AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS", 0.0)
+ monkeypatch.setattr(
+ remote_access,
+ "current_authorization_revision",
+ lambda *args, **kwargs: 42,
+ )
monkeypatch.setattr(
remote_access,
"_device_json_request",
@@ -320,1339 +406,2506 @@ def test_unknown_instance_kind_backfills_without_failing_valid_access(
config,
payload,
revision=42,
+ instance_kind="personal",
),
)
- monkeypatch.setattr(
- remote_access,
- "_persist_instance_kind",
- lambda *args, **kwargs: (_ for _ in ()).throw(OSError("read-only config")),
- )
+ real_save_config = remote_access.api.save_config
+ attempted: list[dict[str, Any]] = []
- result = remote_access.resolve_current_authorization(config, identity)
+ def failing_save_config(payload, **kwargs):
+ attempted.append(payload)
+ raise OSError("read-only config")
- assert result.current is True
- assert result.policy == "organization"
- assert config.remote_access.vibe_cloud.instance_kind == "organization"
+ monkeypatch.setattr(remote_access.api, "save_config", failing_save_config)
+ blocked = remote_access.resolve_current_authorization(config, identity)
-def test_scoped_authorization_promotes_legacy_rows_and_isolates_show_pages(tmp_path):
- now = int(time.time())
- remote_access_authorization_service.store(
- reference="legacy-reference-12345678",
+ assert blocked.state == "unavailable"
+ assert blocked.reason == "instance_kind_persistence_failed"
+ assert attempted
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == ""
+ stored = remote_access_authorization_service.load_reference_record(
+ reference=reference,
instance_id="inst_123",
subject="user-1",
- claims={"vibe_instance_id": "inst_123"},
- expires_at=now + 60,
- created_at=now,
+ now=now,
)
-
- instance_reference = remote_access_authorization_service.upsert_scoped(
- reference="legacy-reference-12345678",
- instance_id="inst_123",
- subject="user-1",
- scope_kind="instance",
- scope_ref="inst_123",
- authorization_state="current",
- claims={"scope": "instance"},
- last_checked_at=now + 1,
- updated_at=now + 1,
+ assert stored is not None
+ assert "vibe_instance_kind" not in stored["claims"]
+ kindless_payload = remote_access._validated_authorization_payload(
+ config,
+ identity,
+ stored,
)
- show_reference = remote_access_authorization_service.upsert_scoped(
- reference=None,
+ assert kindless_payload is not None
+ assert context_from_session_payload(kindless_payload).is_personal_instance is False
+
+ monkeypatch.setattr(remote_access.api, "save_config", real_save_config)
+
+ retried = remote_access.resolve_current_authorization(config, identity)
+
+ assert retried.current is True
+ assert retried.policy == "personal"
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "personal"
+ repaired = remote_access_authorization_service.load_reference_record(
+ reference=reference,
instance_id="inst_123",
subject="user-1",
- scope_kind="show_page",
- scope_ref="show-1",
- authorization_state="current",
- claims={"scope": "show_page"},
- last_checked_at=now + 2,
- updated_at=now + 2,
+ now=now,
)
+ assert repaired is not None
+ assert repaired["claims"]["vibe_instance_kind"] == "personal"
- instance = remote_access_authorization_service.load_scoped(
+
+def test_refresh_from_a_previous_binding_generation_is_discarded(monkeypatch, tmp_path):
+ """An in-flight response that outlived its binding must not be cached."""
+
+ config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
instance_id="inst_123",
- subject="user-1",
- scope_kind="instance",
- scope_ref="inst_123",
+ instance_kind="organization",
)
- show_page = remote_access_authorization_service.load_scoped(
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
instance_id="inst_123",
subject="user-1",
- scope_kind="show_page",
- scope_ref="show-1",
+ now=now,
)
- assert instance_reference == "legacy-reference-12345678"
- assert show_reference != instance_reference
- assert instance is not None and instance["claims"] == {"scope": "instance"}
- assert instance["expires_at"] is None
- assert show_page is not None and show_page["claims"] == {"scope": "show_page"}
+ assert record is not None
+ binding_before = remote_access_authorization_service.load_instance_binding_state()
+ assert binding_before is not None
+
+ def repair_while_in_flight(_config, _method, _suffix, payload, **kwargs):
+ # A re-pair lands while this authorization response is in flight.
+ remote_access._transition_instance_binding(
+ instance_id="inst_repair",
+ instance_kind="personal",
+ )
+ return _authorization_context_response(config, payload, revision=41)
+ monkeypatch.setattr(remote_access, "_device_json_request", repair_while_in_flight)
-def test_referenced_identity_does_not_guess_scope_when_record_is_missing(
+ result = remote_access._refresh_authorization_context(
+ config,
+ identity,
+ record,
+ now=now,
+ force=True,
+ )
+
+ assert result.state == "unavailable"
+ assert result.reason == "instance_binding_changed"
+ binding_after = remote_access_authorization_service.load_instance_binding_state()
+ assert binding_after is not None
+ assert binding_after["generation"] > binding_before["generation"]
+ assert binding_after["instance_id"] == "inst_repair"
+ with remote_access._AUTHORIZATION_REFRESH_LOCK:
+ assert remote_access._AUTHORIZATION_REFRESH_RESULTS == {}
+ assert remote_access._AUTHORIZATION_REFRESH_FAILURES == {}
+ # The discarded generation must not be answerable from cache either.
+ assert (
+ remote_access.resolve_current_authorization(
+ config,
+ identity,
+ allow_refresh=False,
+ ).current
+ is False
+ )
+
+
+def test_stale_cross_process_kind_response_cannot_reverse_durable_generation(
monkeypatch,
tmp_path,
):
+ """A UI-process in-flight Personal response must not undo a controller reclass.
+
+ The controller and UI server are separate processes; the in-memory
+ binding epoch cannot fence this. The durable generation in state_meta
+ is the compare-and-swap token both processes share.
+ """
+
config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
cookie = remote_access.make_session_cookie(
config,
- "viewer-1",
+ "user-1",
session_claims={
"vibe_instance_id": "inst_123",
- "vibe_instance_role": "viewer",
- "vibe_instance_access_source": "show_page_email",
- "vibe_show_page_id": "show-1",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
"vibe_instance_authorization_revision": 41,
},
)
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- assert isinstance(identity.get("authorization_ref"), str)
- assert remote_access_authorization_service.delete_for_instance("inst_123") == 1
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- AssertionError("missing referenced records must not guess a refresh scope")
- ),
+ now = int(time.time())
+ observed_generation = remote_access_authorization_service.current_instance_binding_generation()
+ # Controller heartbeat in another process: Personal -> Organization.
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
)
+ config.remote_access.vibe_cloud.instance_kind = "organization"
+ config.save()
+ newer = remote_access_authorization_service.load_instance_binding_state()
+ assert newer is not None
+ assert newer["generation"] > observed_generation
+ assert newer["instance_kind"] == "organization"
- result = remote_access.resolve_current_authorization(config, identity)
-
- assert result.state == "invalid_identity"
- assert result.reason == "authorization_record_missing"
+ # Stale UI-process in-flight epoch is unchanged; durable generation is not.
+ monkeypatch.setattr(remote_access, "_authorization_binding_epoch", lambda: 0)
+ persisted = remote_access._persist_instance_kind(
+ "inst_123",
+ "personal",
+ expected_binding_generation=observed_generation,
+ expected_binding_epoch=0,
+ )
+ assert persisted is False
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
+ after = remote_access_authorization_service.load_instance_binding_state()
+ assert after is not None
+ assert after["generation"] == newer["generation"]
+ assert after["instance_kind"] == "organization"
-def test_authorization_record_read_failure_is_unavailable(monkeypatch, tmp_path):
- config = _paired_config(tmp_path)
- identity = remote_access.parse_session_identity(config, _organization_cookie(config))
- assert identity is not None
- monkeypatch.setattr(
- remote_access_authorization_service,
- "load_reference_record",
- lambda **kwargs: (_ for _ in ()).throw(OSError("database unavailable")),
- )
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- AssertionError("storage failure must not trigger an unscoped refresh")
- ),
- )
- result = remote_access.resolve_current_authorization(config, identity)
+def test_stale_write_is_refused_under_cross_process_config_lock(tmp_path):
+ """Two threads contend on config_file_lock; the stale writer must abort.
- assert result.state == "unavailable"
- assert result.reason == "authorization_record_unavailable"
+ This is the real cross-process lock boundary (the same lock V2Config.save
+ uses), not the in-process epoch.
+ """
+ from config.v2_config import config_file_lock
-def test_revision_poll_touches_every_matching_current_context_only(tmp_path):
- now = int(time.time())
- rows = (
- ("user-match", 7, "current"),
- ("user-other", 8, "current"),
- ("user-revoked", 7, "revoked"),
+ config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
)
- for subject, revision, state in rows:
- remote_access_authorization_service.upsert_scoped(
- reference=None,
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+ observed = remote_access_authorization_service.current_instance_binding_generation()
+ # flock is process-level, so two threads in one process cannot actually
+ # block each other on config_file_lock. Model the cross-process race as:
+ # snapshot generation, then a controller advance under that lock, then a
+ # stale persist that must CAS-fail against the durable generation.
+ with config_file_lock():
+ remote_access._transition_instance_binding(
instance_id="inst_123",
- subject=subject,
- email=f"{subject}@example.com",
- scope_kind="instance",
- scope_ref="inst_123",
- authorization_state=state,
- claims={"vibe_instance_authorization_revision": revision},
- last_checked_at=now,
- updated_at=now,
+ instance_kind="organization",
)
+ config.remote_access.vibe_cloud.instance_kind = "organization"
+ config.save()
+ controller_generation = (
+ remote_access_authorization_service.current_instance_binding_generation()
+ )
+ stale_ok = remote_access._persist_instance_kind(
+ "inst_123",
+ "personal",
+ expected_binding_generation=observed,
+ )
- assert remote_access_authorization_service.mark_matching_revision_checked(
- instance_id="inst_123",
- authorization_revision=7,
- checked_at=now + 30,
- ) == 1
- checked = {
- subject: remote_access_authorization_service.load_scoped(
- instance_id="inst_123",
- subject=subject,
- scope_kind="instance",
- scope_ref="inst_123",
- )["last_checked_at"]
- for subject, _revision, _state in rows
- }
- assert checked == {
- "user-match": now + 30,
- "user-other": now,
- "user-revoked": now,
- }
+ assert stale_ok is False
+ assert controller_generation > observed
+ assert V2Config.load().remote_access.vibe_cloud.instance_kind == "organization"
+ after = remote_access_authorization_service.load_instance_binding_state()
+ assert after is not None
+ assert after["instance_kind"] == "organization"
+ assert after["generation"] == controller_generation
-def test_concurrent_resolvers_share_one_authorization_context_refresh(
- monkeypatch,
- tmp_path,
-):
+def test_stale_denied_response_does_not_recreate_revoked_row(monkeypatch, tmp_path):
+ """A 403 captured before a transition must not recreate a revoked row."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
+ started = remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
+ assert remote_access_authorization_service.complete_instance_binding_transition(
+ instance_id="inst_123",
+ instance_kind="organization",
+ generation=started["generation"],
+ )
cookie = _organization_cookie(config)
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- calls = 0
- calls_lock = threading.Lock()
-
- def refresh(_config, _method, _suffix, payload, **kwargs):
- nonlocal calls
- with calls_lock:
- calls += 1
- time.sleep(0.05)
- return _authorization_context_response(config, payload, revision=42)
-
- monkeypatch.setattr(remote_access, "_device_json_request", refresh)
- with ThreadPoolExecutor(max_workers=2) as executor:
- results = list(executor.map(
- lambda _index: remote_access.resolve_current_authorization(config, identity),
- range(2),
- ))
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert record is not None
+ observed = remote_access_authorization_service.current_instance_binding_generation()
+ real_generation = remote_access_authorization_service.current_instance_binding_generation
+ calls = {"n": 0}
- assert calls == 1
- assert all(result.current and result.refreshed for result in results)
+ def deny_after_transition(_config, _method, _suffix, payload, **kwargs):
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ raise remote_access.BackendRequestError(403, {"error": "access_denied"})
+ def generation(*, ensure: bool = True) -> int:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return observed
+ return real_generation(ensure=ensure)
-def test_authorization_context_refreshes_for_different_subjects_run_concurrently(
- monkeypatch,
- tmp_path,
-):
- config = _paired_config(tmp_path)
- identities = []
- for subject in ("user-1", "user-2"):
- identity = remote_access.parse_session_identity(
- config,
- _organization_cookie(config, subject=subject),
- )
- assert identity is not None
- identities.append(identity)
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- entered = threading.Barrier(2)
- refreshed_subjects = []
- calls_lock = threading.Lock()
+ monkeypatch.setattr(remote_access, "_device_json_request", deny_after_transition)
+ monkeypatch.setattr(
+ remote_access_authorization_service,
+ "current_instance_binding_generation",
+ generation,
+ )
- def refresh(_config, _method, _suffix, payload, **kwargs):
- with calls_lock:
- refreshed_subjects.append(payload["sub"])
- entered.wait(timeout=2)
- return _authorization_context_response(config, payload, revision=42)
+ result = remote_access._fetch_authorization_context(
+ config,
+ identity,
+ record,
+ now=now,
+ observed_revision=41,
+ )
- monkeypatch.setattr(remote_access, "_device_json_request", refresh)
- with ThreadPoolExecutor(max_workers=2) as executor:
- results = list(executor.map(
- lambda identity: remote_access.resolve_current_authorization(config, identity),
- identities,
- ))
+ assert result.state == "unavailable"
+ assert result.reason == "instance_binding_changed"
+ stored = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ if stored is not None:
+ assert stored.get("authorization_state") != "revoked"
- assert set(refreshed_subjects) == {"user-1", "user-2"}
- assert all(result.current and result.refreshed for result in results)
+def test_exact_show_page_grants_survive_a_kind_transition_but_not_a_repair(tmp_path):
+ """Show Page grants are their own scope, bound to the instance that issued them."""
-def test_concurrent_revocation_refresh_is_reused_and_persisted(
- monkeypatch,
- tmp_path,
-):
config = _paired_config(tmp_path)
- identity = remote_access.parse_session_identity(config, _organization_cookie(config))
- assert identity is not None
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- calls = 0
- calls_lock = threading.Lock()
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
+ now = int(time.time())
+ show_page_claims = {
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "show-1",
+ "vibe_instance_authorization_revision": 41,
+ }
+ show_page_cookie = remote_access.make_session_cookie(
+ config,
+ "viewer-1",
+ session_claims=show_page_claims,
+ )
+ show_page_identity = remote_access.parse_session_identity(config, show_page_cookie)
+ assert show_page_identity is not None
+ instance_identity = remote_access.parse_session_identity(
+ config,
+ _organization_cookie(config),
+ )
+ assert instance_identity is not None
- def revoke(*args, **kwargs):
- nonlocal calls
- with calls_lock:
- calls += 1
- time.sleep(0.05)
- raise remote_access.BackendRequestError(403, {"error": "access_denied"})
+ assert remote_access._persist_instance_kind("inst_123", "personal", reconcile=True)
- monkeypatch.setattr(remote_access, "_device_json_request", revoke)
- with ThreadPoolExecutor(max_workers=2) as executor:
- results = list(executor.map(
- lambda _index: remote_access.resolve_current_authorization(config, identity),
- range(2),
- ))
+ reclassified = V2Config.load()
+ show_page = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="viewer-1",
+ scope_kind="show_page",
+ scope_ref="show-1",
+ )
+ instance = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ )
+ assert show_page is not None
+ assert show_page["authorization_state"] == "current"
+ assert show_page["claims"]["vibe_show_page_id"] == "show-1"
+ assert instance is not None
+ assert instance["authorization_state"] == "stale"
- assert calls == 1
- assert all(result.state == "revoked" for result in results)
- with remote_access._AUTHORIZATION_REFRESH_LOCK:
- remote_access._AUTHORIZATION_REFRESH_RESULTS.clear()
+ resolved = remote_access.resolve_current_authorization(
+ reclassified,
+ show_page_identity,
+ allow_refresh=False,
+ )
+ assert resolved.current is True
+ assert resolved.payload is not None
+ assert resolved.payload["vibe_show_page_id"] == "show-1"
- persisted = remote_access.resolve_current_authorization(config, identity)
+ # Mid-transition the exact grant still reads, while the instance-scoped
+ # cache stays fail-closed.
+ reconciling = remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst_repair",
+ instance_kind="personal",
+ )
+ assert (
+ reconciling["state"]
+ == remote_access_authorization_service.INSTANCE_BINDING_STATE_RECONCILING
+ )
+ assert (
+ remote_access.binding_is_ready(reclassified, show_page_identity)
+ is True
+ )
+ assert (
+ remote_access.binding_is_ready(reclassified, instance_identity)
+ is False
+ )
- assert persisted.state == "revoked"
- assert calls == 1
+ # Re-pairing to a different instance is not a reclassification: those
+ # grants were issued by the previous instance and must not survive it.
+ remote_access._transition_instance_binding(
+ instance_id="inst_repair",
+ instance_kind="personal",
+ previous_instance_id="inst_123",
+ )
+ repaired = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="viewer-1",
+ scope_kind="show_page",
+ scope_ref="show-1",
+ )
+ assert repaired is not None
+ assert repaired["authorization_state"] == "stale"
-def test_refresh_backoff_starts_when_the_network_request_finishes(
+def test_personal_revision_hint_refreshes_in_background_without_blocking(
monkeypatch,
tmp_path,
):
config = _paired_config(tmp_path)
- identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- monotonic_values = iter((100.0, 110.0, 110.1))
- monkeypatch.setattr(remote_access.time, "monotonic", lambda: next(monotonic_values))
- calls = 0
+ entered = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
def unavailable(*args, **kwargs):
- nonlocal calls
- calls += 1
+ entered.set()
+ release.wait(timeout=1)
+ finished.set()
raise remote_access.BackendRequestError(503, {"error": "unavailable"})
monkeypatch.setattr(remote_access, "_device_json_request", unavailable)
- remote_access.resolve_current_authorization(config, identity)
- remote_access.resolve_current_authorization(config, identity)
+ result = remote_access.resolve_current_authorization(config, identity)
- assert calls == 1
+ assert result.current is True
+ assert result.policy == "personal"
+ assert entered.wait(timeout=1)
+ assert finished.is_set() is False
+ release.set()
+ assert finished.wait(timeout=1)
-def test_revoked_authorization_recovers_after_revision_change(monkeypatch, tmp_path):
+def test_organization_scheduled_refresh_does_not_block_when_revision_matches(
+ monkeypatch,
+ tmp_path,
+):
config = _paired_config(tmp_path)
- identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ base = int(time.time())
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- remote_access.BackendRequestError(403, {"error": "access_denied"})
- ),
+ refresh_at = base + remote_access.ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS + 1
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=41,
+ checked_at=refresh_at,
+ ) == 1
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 41)
+ scheduled = []
+ monkeypatch.setattr(
+ remote_access,
+ "_schedule_authorization_refresh",
+ lambda *args, **kwargs: scheduled.append((args, kwargs)),
)
- assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
-
- monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 43)
monkeypatch.setattr(
remote_access,
- "_device_json_request",
- lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
- config,
- payload,
- revision=43,
+ "_refresh_authorization_context",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("routine matching-revision refresh blocked the request")
),
)
- recovered = remote_access.resolve_current_authorization(config, identity)
+ result = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=refresh_at,
+ )
- assert recovered.current is True
- assert recovered.refreshed is True
- assert recovered.payload["vibe_instance_authorization_revision"] == 43
+ assert result.current is True
+ assert result.policy == "organization"
+ assert result.reason == "authorization_refresh_scheduled"
+ assert len(scheduled) == 1
-def test_explicit_login_can_revalidate_revoked_authorization(monkeypatch, tmp_path):
+def test_organization_refresh_grace_expiry_and_recovery(monkeypatch, tmp_path):
+ """Scenario: AUTH-SETUP-403."""
+
config = _paired_config(tmp_path)
- identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ base = int(time.time())
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- observed_revision = 42
- monkeypatch.setattr(
- remote_access,
- "current_authorization_revision",
- lambda *args, **kwargs: observed_revision,
- )
+ checked_at = base + remote_access.ORGANIZATION_AUTHORIZATION_REFRESH_SECONDS
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=41,
+ checked_at=checked_at,
+ ) == 1
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
monkeypatch.setattr(
remote_access,
"_device_json_request",
lambda *args, **kwargs: (_ for _ in ()).throw(
- remote_access.BackendRequestError(403, {"error": "access_denied"})
+ remote_access.BackendRequestError(503, {"error": "unavailable"})
),
)
- assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
- refresh_calls = 0
-
- def refresh(_config, _method, _suffix, payload, **kwargs):
- nonlocal refresh_calls
- refresh_calls += 1
- return _authorization_context_response(config, payload, revision=42)
+ within_grace = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=checked_at + 1,
+ )
+ assert within_grace.current is True
+ assert within_grace.reason == "authorization_grace"
- monkeypatch.setattr(remote_access, "_device_json_request", refresh)
- assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ after_grace = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ now=checked_at + remote_access.ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS + 1,
+ )
+ assert after_grace.state == "unavailable"
+ assert after_grace.reason == "authorization_grace_expired"
+ remote_access._AUTHORIZATION_REFRESH_FAILURES.clear()
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ config,
+ payload,
+ revision=42,
+ ),
+ )
recovered = remote_access.resolve_current_authorization(
config,
identity,
- refresh_revoked=True,
+ now=checked_at + remote_access.ORGANIZATION_AUTHORIZATION_OUTAGE_GRACE_SECONDS + 2,
)
-
assert recovered.current is True
assert recovered.refreshed is True
- assert refresh_calls == 1
+ assert recovered.payload["vibe_instance_authorization_revision"] == 42
-def test_remote_login_forces_revoked_authorization_revalidation(monkeypatch, tmp_path):
+def test_unknown_instance_kind_requires_durable_backfill_before_access(
+ monkeypatch,
+ tmp_path,
+):
config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = ""
cookie = _organization_cookie(config)
- refresh_flags = []
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ config,
+ payload,
+ revision=42,
+ ),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_persist_instance_kind",
+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("read-only config")),
+ )
- def resolve(_config, identity, **kwargs):
- refresh_flags.append(kwargs.get("refresh_revoked"))
- return remote_access.AuthorizationResolution("current", payload=identity)
+ result = remote_access.resolve_current_authorization(config, identity)
- monkeypatch.setattr(remote_access, "resolve_current_authorization", resolve)
- client = app.test_client()
- client.set_cookie(
- remote_access.SESSION_COOKIE_NAME,
- cookie,
- domain="alex.avibe.bot",
+ assert result.state == "unavailable"
+ assert result.reason == "instance_kind_persistence_failed"
+ assert config.remote_access.vibe_cloud.instance_kind == ""
+
+
+def test_scoped_authorization_promotes_legacy_rows_and_isolates_show_pages(tmp_path):
+ now = int(time.time())
+ remote_access_authorization_service.store(
+ reference="legacy-reference-12345678",
+ instance_id="inst_123",
+ subject="user-1",
+ claims={"vibe_instance_id": "inst_123"},
+ expires_at=now + 60,
+ created_at=now,
)
- response = client.get(
- "/auth/login?next=/inbox",
- base_url="https://alex.avibe.bot",
- follow_redirects=False,
+ instance_reference = remote_access_authorization_service.upsert_scoped(
+ reference="legacy-reference-12345678",
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ authorization_state="current",
+ claims={"scope": "instance"},
+ last_checked_at=now + 1,
+ updated_at=now + 1,
+ )
+ show_reference = remote_access_authorization_service.upsert_scoped(
+ reference=None,
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="show_page",
+ scope_ref="show-1",
+ authorization_state="current",
+ claims={"scope": "show_page"},
+ last_checked_at=now + 2,
+ updated_at=now + 2,
)
- assert response.status_code == 302
- assert response.headers["Location"] == "/inbox"
- assert refresh_flags[-1] is True
- assert refresh_flags.count(True) == 1
+ instance = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ )
+ show_page = remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind="show_page",
+ scope_ref="show-1",
+ )
+ assert instance_reference == "legacy-reference-12345678"
+ assert show_reference != instance_reference
+ assert instance is not None and instance["claims"] == {"scope": "instance"}
+ assert instance["expires_at"] is None
+ assert show_page is not None and show_page["claims"] == {"scope": "show_page"}
-def test_browser_logout_invalidates_http_sse_and_websocket(monkeypatch, tmp_path):
+def test_referenced_identity_does_not_guess_scope_when_record_is_missing(
+ monkeypatch,
+ tmp_path,
+):
config = _paired_config(tmp_path)
- cookie = _organization_cookie(config)
+ cookie = remote_access.make_session_cookie(
+ config,
+ "viewer-1",
+ session_claims={
+ "vibe_instance_id": "inst_123",
+ "vibe_instance_role": "viewer",
+ "vibe_instance_access_source": "show_page_email",
+ "vibe_show_page_id": "show-1",
+ "vibe_instance_authorization_revision": 41,
+ },
+ )
identity = remote_access.parse_session_identity(config, cookie)
- payload = remote_access.parse_session_cookie(config, cookie)
assert identity is not None
- assert payload is not None
- assert remote_access.revoke_browser_session(identity) is True
+ assert isinstance(identity.get("authorization_ref"), str)
+ assert remote_access_authorization_service.delete_for_instance("inst_123") == 1
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("missing referenced records must not guess a refresh scope")
+ ),
+ )
- client = app.test_client()
- client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
- assert client.get(
- "/api/session",
- base_url="https://alex.avibe.bot",
- ).get_json()["authenticated"] is False
+ result = remote_access.resolve_current_authorization(config, identity)
- monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)
+ assert result.state == "invalid_identity"
+ assert result.reason == "authorization_record_missing"
- async def exercise() -> None:
- with app.test_request_context(
- "/api/events",
- base_url="https://alex.avibe.bot",
- headers={"Cookie": f"{remote_access.SESSION_COOKIE_NAME}={cookie}"},
- ):
- g.authorization_context = context_from_session_payload(payload)
- g.remote_session_identity = identity
- g.remote_session_payload = payload
- response = await ui_server.workbench_events()
- iterator = response.body_iterator.__aiter__()
- try:
- terminal = await asyncio.wait_for(iterator.__anext__(), timeout=1)
- assert '"state":"invalid_identity"' in terminal
- with pytest.raises(StopAsyncIteration):
- await iterator.__anext__()
- finally:
- await iterator.aclose()
- outcome = await asyncio.wait_for(
- ui_server._wait_for_remote_session_authorization_loss(
- config,
- identity,
- payload,
- session_cookie=cookie,
- request_host="alex.avibe.bot",
+
+def test_authorization_record_read_failure_is_unavailable(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(
+ remote_access_authorization_service,
+ "load_reference_record",
+ lambda **kwargs: (_ for _ in ()).throw(OSError("database unavailable")),
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("storage failure must not trigger an unscoped refresh")
+ ),
+ )
+
+ result = remote_access.resolve_current_authorization(config, identity)
+
+ assert result.state == "unavailable"
+ assert result.reason == "authorization_record_unavailable"
+
+
+def test_revision_poll_touches_every_matching_current_context_only(tmp_path):
+ now = int(time.time())
+ rows = (
+ ("user-match", 7, "current"),
+ ("user-other", 8, "current"),
+ ("user-revoked", 7, "revoked"),
+ )
+ for subject, revision, state in rows:
+ remote_access_authorization_service.upsert_scoped(
+ reference=None,
+ instance_id="inst_123",
+ subject=subject,
+ email=f"{subject}@example.com",
+ scope_kind="instance",
+ scope_ref="inst_123",
+ authorization_state=state,
+ claims={"vibe_instance_authorization_revision": revision},
+ last_checked_at=now,
+ updated_at=now,
+ )
+
+ assert remote_access_authorization_service.mark_matching_revision_checked(
+ instance_id="inst_123",
+ authorization_revision=7,
+ checked_at=now + 30,
+ ) == 1
+ checked = {
+ subject: remote_access_authorization_service.load_scoped(
+ instance_id="inst_123",
+ subject=subject,
+ scope_kind="instance",
+ scope_ref="inst_123",
+ )["last_checked_at"]
+ for subject, _revision, _state in rows
+ }
+ assert checked == {
+ "user-match": now + 30,
+ "user-other": now,
+ "user-revoked": now,
+ }
+
+
+def test_concurrent_resolvers_share_one_authorization_context_refresh(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ calls = 0
+ calls_lock = threading.Lock()
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ nonlocal calls
+ with calls_lock:
+ calls += 1
+ time.sleep(0.05)
+ return _authorization_context_response(config, payload, revision=42)
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(
+ lambda _index: remote_access.resolve_current_authorization(config, identity),
+ range(2),
+ ))
+
+ assert calls == 1
+ assert all(result.current and result.refreshed for result in results)
+
+
+def test_authorization_context_refreshes_for_different_subjects_run_concurrently(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
+ identities = []
+ for subject in ("user-1", "user-2"):
+ identity = remote_access.parse_session_identity(
+ config,
+ _organization_cookie(config, subject=subject),
+ )
+ assert identity is not None
+ identities.append(identity)
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ entered = threading.Barrier(2)
+ refreshed_subjects = []
+ calls_lock = threading.Lock()
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ with calls_lock:
+ refreshed_subjects.append(payload["sub"])
+ entered.wait(timeout=2)
+ return _authorization_context_response(config, payload, revision=42)
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(
+ lambda identity: remote_access.resolve_current_authorization(config, identity),
+ identities,
+ ))
+
+ assert set(refreshed_subjects) == {"user-1", "user-2"}
+ assert all(result.current and result.refreshed for result in results)
+
+
+def test_concurrent_revocation_refresh_is_reused_and_persisted(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ calls = 0
+ calls_lock = threading.Lock()
+
+ def revoke(*args, **kwargs):
+ nonlocal calls
+ with calls_lock:
+ calls += 1
+ time.sleep(0.05)
+ raise remote_access.BackendRequestError(403, {"error": "access_denied"})
+
+ monkeypatch.setattr(remote_access, "_device_json_request", revoke)
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ results = list(executor.map(
+ lambda _index: remote_access.resolve_current_authorization(config, identity),
+ range(2),
+ ))
+
+ assert calls == 1
+ assert all(result.state == "revoked" for result in results)
+ with remote_access._AUTHORIZATION_REFRESH_LOCK:
+ remote_access._AUTHORIZATION_REFRESH_RESULTS.clear()
+
+ persisted = remote_access.resolve_current_authorization(config, identity)
+
+ assert persisted.state == "revoked"
+ assert calls == 1
+
+
+def test_refresh_backoff_starts_when_the_network_request_finishes(
+ monkeypatch,
+ tmp_path,
+):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monotonic_values = itertools.chain(
+ (100.0, 110.0, 110.05, 110.1, 110.15),
+ itertools.repeat(110.2),
+ )
+ monkeypatch.setattr(remote_access.time, "monotonic", lambda: next(monotonic_values))
+ calls = 0
+
+ def unavailable(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ raise remote_access.BackendRequestError(503, {"error": "unavailable"})
+
+ monkeypatch.setattr(remote_access, "_device_json_request", unavailable)
+
+ remote_access.resolve_current_authorization(config, identity)
+ remote_access.resolve_current_authorization(config, identity)
+
+ assert calls == 1
+
+
+def test_revoked_authorization_recovers_after_revision_change(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 42)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
+ assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+
+ monkeypatch.setattr(remote_access, "current_authorization_revision", lambda *args, **kwargs: 43)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _config, _method, _suffix, payload, **kwargs: _authorization_context_response(
+ config,
+ payload,
+ revision=43,
+ ),
+ )
+
+ recovered = remote_access.resolve_current_authorization(config, identity)
+
+ assert recovered.current is True
+ assert recovered.refreshed is True
+ assert recovered.payload["vibe_instance_authorization_revision"] == 43
+
+
+def test_explicit_login_can_revalidate_revoked_authorization(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ identity = remote_access.parse_session_identity(config, _organization_cookie(config))
+ assert identity is not None
+ observed_revision = 42
+ monkeypatch.setattr(
+ remote_access,
+ "current_authorization_revision",
+ lambda *args, **kwargs: observed_revision,
+ )
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
+ )
+ assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+
+ refresh_calls = 0
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ nonlocal refresh_calls
+ refresh_calls += 1
+ return _authorization_context_response(config, payload, revision=42)
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ assert remote_access.resolve_current_authorization(config, identity).state == "revoked"
+
+ recovered = remote_access.resolve_current_authorization(
+ config,
+ identity,
+ refresh_revoked=True,
+ )
+
+ assert recovered.current is True
+ assert recovered.refreshed is True
+ assert refresh_calls == 1
+
+
+def test_remote_login_forces_revoked_authorization_revalidation(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ refresh_flags = []
+
+ def resolve(_config, identity, **kwargs):
+ refresh_flags.append(kwargs.get("refresh_revoked"))
+ return remote_access.AuthorizationResolution("current", payload=identity)
+
+ monkeypatch.setattr(remote_access, "resolve_current_authorization", resolve)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ cookie,
+ domain="alex.avibe.bot",
+ )
+
+ response = client.get(
+ "/auth/login?next=/inbox",
+ base_url="https://alex.avibe.bot",
+ follow_redirects=False,
+ )
+
+ assert response.status_code == 302
+ assert response.headers["Location"] == "/inbox"
+ assert refresh_flags[-1] is True
+ assert refresh_flags.count(True) == 1
+
+
+def test_browser_logout_invalidates_http_sse_and_websocket(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ payload = remote_access.parse_session_cookie(config, cookie)
+ assert identity is not None
+ assert payload is not None
+ assert remote_access.revoke_browser_session(identity) is True
+
+ client = app.test_client()
+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
+ assert client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()["authenticated"] is False
+
+ monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)
+
+ async def exercise() -> None:
+ with app.test_request_context(
+ "/api/events",
+ base_url="https://alex.avibe.bot",
+ headers={"Cookie": f"{remote_access.SESSION_COOKIE_NAME}={cookie}"},
+ ):
+ g.authorization_context = context_from_session_payload(payload)
+ g.remote_session_identity = identity
+ g.remote_session_payload = payload
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ terminal = await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ assert '"state":"invalid_identity"' in terminal
+ with pytest.raises(StopAsyncIteration):
+ await iterator.__anext__()
+ finally:
+ await iterator.aclose()
+ outcome = await asyncio.wait_for(
+ ui_server._wait_for_remote_session_authorization_loss(
+ config,
+ identity,
+ payload,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
),
timeout=1,
)
- assert outcome == "invalid_identity"
+ assert outcome == "invalid_identity"
+
+ asyncio.run(exercise())
+
+
+def test_legacy_browser_logout_derives_a_stable_revocation_identity(tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ legacy_payload = remote_access.parse_session_identity(config, cookie)
+ assert legacy_payload is not None
+ legacy_payload.pop("browser_session_id")
+ legacy_cookie = remote_access._encode_session_cookie(
+ config.remote_access.vibe_cloud.session_secret,
+ legacy_payload,
+ )
+ accepted_identity = remote_access.parse_session_identity(config, legacy_cookie)
+ assert accepted_identity is not None
+ assert accepted_identity["browser_session_id"] == remote_access.parse_session_identity(
+ config,
+ legacy_cookie,
+ )["browser_session_id"]
+
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ legacy_cookie,
+ domain="alex.avibe.bot",
+ )
+ response = client.post(
+ "/auth/logout",
+ base_url="https://alex.avibe.bot",
+ json={},
+ headers=csrf_headers(client, "https://alex.avibe.bot"),
+ )
+
+ assert response.status_code == 200
+ assert remote_access.parse_session_identity(config, legacy_cookie) is None
+ assert remote_access.session_identity_is_current(accepted_identity) is False
+
+
+ ("state", "status_code", "error"),
+ [
+ ("revoked", 403, "remote_access_revoked"),
+ ("unavailable", 503, "remote_access_authorization_unavailable"),
+ ],
+)
+def test_remote_authorization_failure_serves_spa_shell_but_rejects_api(
+ monkeypatch,
+ tmp_path,
+ state,
+ status_code,
+ error,
+):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ monkeypatch.setattr(
+ remote_access,
+ "resolve_current_authorization",
+ lambda *args, **kwargs: remote_access.AuthorizationResolution(state),
+ )
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ cookie,
+ domain="alex.avibe.bot",
+ )
+
+ shell = client.get(
+ "/",
+ base_url="https://alex.avibe.bot",
+ headers={"Accept": "text/html"},
+ )
+ protected = client.get(
+ "/api/config",
+ base_url="https://alex.avibe.bot",
+ headers={"Accept": "application/json"},
+ )
+
+ assert shell.status_code == 200
+ assert shell.headers["content-type"].startswith("text/html")
+ assert protected.status_code == status_code
+ assert protected.get_json()["error"] == error
+
+
+def _delayed_authorization_revision_sync_writer(
+ home: str,
+ entered: Any,
+ release: Any,
+ result_queue: Any,
+) -> None:
+ import os as _os
+
+ _os.environ["AVIBE_HOME"] = home
+ from config.v2_config import V2Config as _V2Config
+ from vibe import remote_access as _remote_access
+
+ config = _V2Config.load()
+ state_path = _remote_access._authorization_revision_state_path()
+ original_read_json = _remote_access.runtime.read_json
+ paused = False
+
+ def delayed_read_json(path):
+ nonlocal paused
+
+ payload = original_read_json(path)
+ if path == state_path and not paused:
+ paused = True
+ entered.set()
+ if not release.wait(timeout=15):
+ raise AssertionError("delayed revision writer was never released")
+ return payload
+
+ _remote_access.runtime.read_json = delayed_read_json
+ try:
+ result_queue.put(("ok", _remote_access._replace_authorization_revision(config, 42)))
+ except Exception as exc:
+ result_queue.put(("error", repr(exc)))
+
+
+def _authorization_revision_acknowledgement_writer(
+ home: str,
+ attempted: Any,
+ done: Any,
+ result_queue: Any,
+) -> None:
+ import os as _os
+
+ _os.environ["AVIBE_HOME"] = home
+ from config.v2_config import V2Config as _V2Config
+ from vibe import remote_access as _remote_access
+
+ config = _V2Config.load()
+ attempted.set()
+ try:
+ result_queue.put(("ok", _remote_access.acknowledge_authorization_revision(config, 43)))
+ except Exception as exc:
+ result_queue.put(("error", repr(exc)))
+ finally:
+ done.set()
+
+
+def test_authorization_revision_device_contract_is_monotonic(monkeypatch, tmp_path):
+ """I1057-AC2/AC3: one paired-device watermark drives every hostname."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ calls = []
+
+ def request(cfg, method, suffix, payload=None, *, timeout=8.0):
+ calls.append((cfg, method, suffix, payload, timeout))
+ return {"authorization_revision": 42}
+
+ monkeypatch.setattr(remote_access, "_device_json_request", request)
+
+ assert remote_access.sync_authorization_revision_once(config) == {
+ "ok": True,
+ "authorization_revision": 42,
+ }
+ assert calls == [(config, "GET", "authorization-revision", None, 8.0)]
+ assert remote_access.current_authorization_revision(config) == 42
+
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: {"authorization_revision": 41},
+ )
+ assert remote_access.sync_authorization_revision_once(config) == {
+ "ok": False,
+ "error": "authorization_revision_regressed",
+ }
+ assert remote_access.current_authorization_revision(config) == 42
+
+
+def test_authorization_revision_writes_are_monotonic_across_processes(
+ monkeypatch,
+ tmp_path,
+):
+ """A delayed synchronization write cannot replace a newer acknowledgement."""
+
+ import multiprocessing as mp
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_config(tmp_path, revision=41)
+ ctx = mp.get_context("spawn")
+ sync_entered = ctx.Event()
+ release_sync = ctx.Event()
+ acknowledgement_attempted = ctx.Event()
+ acknowledgement_done = ctx.Event()
+ sync_result = ctx.Queue()
+ acknowledgement_result = ctx.Queue()
+ sync_writer = ctx.Process(
+ target=_delayed_authorization_revision_sync_writer,
+ args=(str(tmp_path), sync_entered, release_sync, sync_result),
+ )
+ acknowledgement_writer = ctx.Process(
+ target=_authorization_revision_acknowledgement_writer,
+ args=(
+ str(tmp_path),
+ acknowledgement_attempted,
+ acknowledgement_done,
+ acknowledgement_result,
+ ),
+ )
+
+ sync_writer.start()
+ assert sync_entered.wait(timeout=15), "sync writer never entered its transaction"
+ acknowledgement_writer.start()
+ assert acknowledgement_attempted.wait(timeout=15), "acknowledgement writer never attempted"
+ assert not acknowledgement_done.wait(timeout=1), (
+ "acknowledgement writer bypassed the synchronization transaction"
+ )
+ release_sync.set()
+ sync_writer.join(timeout=15)
+ acknowledgement_writer.join(timeout=15)
+
+ assert sync_writer.exitcode == 0, f"sync writer failed: {sync_writer.exitcode}"
+ assert acknowledgement_writer.exitcode == 0, (
+ f"acknowledgement writer failed: {acknowledgement_writer.exitcode}"
+ )
+ assert sync_result.get(timeout=5) == ("ok", 42)
+ assert acknowledgement_result.get(timeout=5) == ("ok", 43)
+ persisted = remote_access.runtime.read_json(
+ remote_access._authorization_revision_state_path()
+ )
+ assert persisted["authorization_revision"] == 43
+
+
+def test_authorization_revision_cache_observes_another_process_watermark(
+ monkeypatch,
+ tmp_path,
+):
+ """A controller cache must observe a mutation persisted by the UI server."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path, revision=41)
+ claims = _organization_claims(config, revision=41)
+ source_updated_at = time.time()
+
+ assert remote_access.session_authorization_revision_state(
+ config,
+ claims,
+ now=source_updated_at,
+ ) == "current"
+
+ remote_access.runtime.write_json(
+ remote_access._authorization_revision_state_path(), # noqa: SLF001
+ {
+ "schema_version": 1,
+ "instance_id": "inst_123",
+ "authorization_revision": 42,
+ "source_updated_at": source_updated_at,
+ },
+ )
+
+ assert remote_access.session_authorization_revision_state(
+ config,
+ claims,
+ now=source_updated_at,
+ ) == "mismatch"
+
+
+ ("changed_field", "replacement"),
+ (
+ ("backend_url", "https://other-backend.test"),
+ ("instance_id", "inst_new"),
+ ("instance_secret", "other-secret"),
+ ),
+)
+def test_authorization_revision_acknowledgement_rejects_a_stale_pairing(
+ monkeypatch,
+ tmp_path,
+ changed_field,
+ replacement,
+):
+ """A mutation from instance A cannot replace the watermark after pairing B."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path, revision=41)
+ current = V2Config.load()
+ setattr(current.remote_access.vibe_cloud, changed_field, replacement)
+ current.save()
+
+ with pytest.raises(
+ remote_access.AuthorizationRevisionPairingChangedError,
+ match="authorization_revision_pairing_changed",
+ ):
+ remote_access.acknowledge_authorization_revision(config, 42)
+
+ persisted = remote_access.runtime.read_json(
+ remote_access._authorization_revision_state_path()
+ )
+ assert persisted["instance_id"] == "inst_123"
+ assert persisted["authorization_revision"] == 41
+
+
+def test_authorization_revision_acknowledgement_rechecks_pairing_at_locked_write(
+ monkeypatch,
+ tmp_path,
+):
+ """A pairing switch at the watermark lock cannot let the old write through."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path, revision=41)
+ original_lock = remote_access._authorization_revision_file_lock # noqa: SLF001
+ switched = False
+
+ def switch_before_locked_read(path):
+ nonlocal switched
+ if not switched:
+ switched = True
+ current = V2Config.load()
+ current.remote_access.vibe_cloud.instance_id = "inst_new"
+ current.save()
+ return original_lock(path)
+
+ monkeypatch.setattr(
+ remote_access,
+ "_authorization_revision_file_lock",
+ switch_before_locked_read,
+ )
+
+ with pytest.raises(
+ remote_access.AuthorizationRevisionPairingChangedError,
+ match="authorization_revision_pairing_changed",
+ ):
+ remote_access.acknowledge_authorization_revision(config, 42)
+
+ persisted = remote_access.runtime.read_json(
+ remote_access._authorization_revision_state_path()
+ )
+ assert persisted["instance_id"] == "inst_123"
+ assert persisted["authorization_revision"] == 41
+
+
[email protected]("persistence_failure", ("write_error", "lock_timeout"))
+def test_authorization_revision_sync_rejects_an_unpersisted_watermark(
+ monkeypatch,
+ tmp_path,
+ persistence_failure,
+):
+ config = _paired_config(tmp_path)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *_args, **_kwargs: {"authorization_revision": 42},
+ )
+ if persistence_failure == "write_error":
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+ )
+ else:
+ def timed_out_lock(_path):
+ raise MigrationLockTimeout("watermark lock timed out")
+
+ monkeypatch.setattr(
+ remote_access,
+ "_authorization_revision_file_lock",
+ timed_out_lock,
+ )
+
+ assert remote_access.sync_authorization_revision_once(config) == {
+ "ok": False,
+ "error": "authorization_revision_sync_failed",
+ }
+ assert remote_access.current_authorization_revision(config) == 41
+
+
+ "malformed",
+ (
+ b"\xff",
+ b"{not-json",
+ b'{"schema_version":1,"instance_id":"inst_123","authorization_revision":"bad","source_updated_at":0}',
+ ),
+)
+def test_authorization_revision_read_treats_malformed_content_as_absent(
+ monkeypatch,
+ tmp_path,
+ malformed,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ remote_access._authorization_revision_state_path().write_bytes(malformed) # noqa: SLF001
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
- asyncio.run(exercise())
+ assert remote_access.current_authorization_revision(config) is None
-def test_legacy_browser_logout_derives_a_stable_revocation_identity(tmp_path):
+ "malformed",
+ (
+ b"\xff",
+ b"{not-json",
+ b'{"schema_version":1,"instance_id":"inst_123","authorization_revision":"bad","source_updated_at":0}',
+ ),
+)
+def test_authorization_acknowledgement_keeps_memory_revision_when_rewrite_fails(
+ monkeypatch,
+ tmp_path,
+ malformed,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- cookie = _organization_cookie(config)
- legacy_payload = remote_access.parse_session_identity(config, cookie)
- assert legacy_payload is not None
- legacy_payload.pop("browser_session_id")
- legacy_cookie = remote_access._encode_session_cookie(
- config.remote_access.vibe_cloud.session_secret,
- legacy_payload,
+ state_path = remote_access._authorization_revision_state_path() # noqa: SLF001
+ state_path.write_bytes(malformed)
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
+ published = []
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
)
- accepted_identity = remote_access.parse_session_identity(config, legacy_cookie)
- assert accepted_identity is not None
- assert accepted_identity["browser_session_id"] == remote_access.parse_session_identity(
- config,
- legacy_cookie,
- )["browser_session_id"]
-
- client = app.test_client()
- client.set_cookie(
- remote_access.SESSION_COOKIE_NAME,
- legacy_cookie,
- domain="alex.avibe.bot",
+ monkeypatch.setattr(
+ broker,
+ "publish",
+ lambda event_type, data: published.append((event_type, data)),
)
- response = client.post(
- "/auth/logout",
- base_url="https://alex.avibe.bot",
- json={},
- headers=csrf_headers(client, "https://alex.avibe.bot"),
+
+ assert remote_access.acknowledge_authorization_revision(config, 42) == 42
+ assert remote_access.current_authorization_revision(config) == 42
+ assert published == [
+ ("authorization.changed", {"instance_authorization_revision": 42})
+ ]
+
+
+def test_authorization_revision_sync_keeps_strict_write_after_malformed_read(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ remote_access._authorization_revision_state_path().write_bytes(b"\xff") # noqa: SLF001
+ remote_access._clear_authorization_revision_cache() # noqa: SLF001
+ monkeypatch.setattr(
+ remote_access.runtime,
+ "write_json",
+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
)
- assert response.status_code == 200
- assert remote_access.parse_session_identity(config, legacy_cookie) is None
- assert remote_access.session_identity_is_current(accepted_identity) is False
+ with pytest.raises(OSError, match="read-only state"):
+ remote_access._replace_authorization_revision(config, 42) # noqa: SLF001
+
+
+def test_paired_session_requires_signed_current_revision(monkeypatch, tmp_path):
+ """I1057-AC4: unsigned, missing, and stale authorization versions fail closed."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ missing = _organization_claims(config)
+ missing.pop("vibe_instance_authorization_revision")
+
+ with pytest.raises(
+ remote_access.OAuthCodeExchangeError,
+ match="invalid_authorization_revision",
+ ):
+ remote_access.make_session_cookie(
+ config,
+ "user-1",
+ session_claims=missing,
+ )
+
+ with pytest.raises(
+ remote_access.OAuthCodeExchangeError,
+ match="stale_authorization_revision",
+ ):
+ _organization_cookie(config, revision=40)
@pytest.mark.parametrize(
- ("state", "status_code", "error"),
+ "hosted_change",
[
- ("revoked", 403, "remote_access_revoked"),
- ("unavailable", 503, "remote_access_authorization_unavailable"),
+ "role_downgrade",
+ "group_membership_removal",
+ "group_archival",
+ "member_removal",
+ "access_binding_removal",
],
)
-def test_remote_authorization_failure_serves_spa_shell_but_rejects_api(
+def test_revision_advance_revokes_active_editor_http_session(
monkeypatch,
tmp_path,
- state,
- status_code,
- error,
+ hosted_change,
):
+ """I1057-AC1/AC2: narrowing invalidates a remote session with chat enabled."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
cookie = _organization_cookie(config)
- monkeypatch.setattr(
- remote_access,
- "resolve_current_authorization",
- lambda *args, **kwargs: remote_access.AuthorizationResolution(state),
- )
+ payload = remote_access.parse_session_cookie(config, cookie)
+ assert payload is not None
+ assert context_from_session_payload(payload).can_chat is True
+
client = app.test_client()
- client.set_cookie(
- remote_access.SESSION_COOKIE_NAME,
- cookie,
- domain="alex.avibe.bot",
+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
+ headers = csrf_headers(client, "https://alex.avibe.bot")
+ before = client.post(
+ "/api/sessions",
+ base_url="https://alex.avibe.bot",
+ headers=headers,
+ json={},
)
+ assert before.status_code == 400
- shell = client.get(
- "/",
- base_url="https://alex.avibe.bot",
- headers={"Accept": "text/html"},
+ assert hosted_change
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
)
- protected = client.get(
- "/api/config",
+ remote_access._replace_authorization_revision(config, 42)
+ after = client.post(
+ "/api/sessions",
base_url="https://alex.avibe.bot",
- headers={"Accept": "application/json"},
+ headers=headers,
+ json={},
)
- assert shell.status_code == 200
- assert shell.headers["content-type"].startswith("text/html")
- assert protected.status_code == status_code
- assert protected.get_json()["error"] == error
+ assert after.status_code == 403
+ assert after.get_json()["error"] == "remote_access_revoked"
-def _delayed_authorization_revision_sync_writer(
- home: str,
- entered: Any,
- release: Any,
- result_queue: Any,
-) -> None:
- import os as _os
+def test_default_and_custom_hostname_sessions_share_revision(monkeypatch, tmp_path):
+ """I1057-AC3: host-scoped cookies cannot retain divergent authorization."""
- _os.environ["AVIBE_HOME"] = home
- from config.v2_config import V2Config as _V2Config
- from vibe import remote_access as _remote_access
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
+ default_client = app.test_client()
+ custom_client = app.test_client()
+ default_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(config, subject="default-user"),
+ domain="alex.avibe.bot",
+ )
+ custom_client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _organization_cookie(config, subject="custom-user"),
+ domain="max.fileguard.io",
+ )
- config = _V2Config.load()
- state_path = _remote_access._authorization_revision_state_path()
- original_read_json = _remote_access.runtime.read_json
- paused = False
+ assert default_client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()["authenticated"] is True
+ assert custom_client.get(
+ "/api/session",
+ base_url="https://max.fileguard.io",
+ ).get_json()["authenticated"] is True
- def delayed_read_json(path):
- nonlocal paused
+ refreshed_subjects = []
- payload = original_read_json(path)
- if path == state_path and not paused:
- paused = True
- entered.set()
- if not release.wait(timeout=15):
- raise AssertionError("delayed revision writer was never released")
- return payload
+ def refresh(_config, method, suffix, payload=None, *, timeout=8.0):
+ assert (method, suffix, timeout) == ("POST", "authorization-context", 8.0)
+ refreshed_subjects.append(payload["sub"])
+ return {
+ "sub": payload["sub"],
+ "email": payload["email"],
+ "instance_kind": "organization",
+ **_organization_claims(config, revision=42),
+ }
+
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ remote_access._replace_authorization_revision(config, 42)
+
+ default_session = default_client.get(
+ "/api/session",
+ base_url="https://alex.avibe.bot",
+ ).get_json()
+ custom_session = custom_client.get(
+ "/api/session",
+ base_url="https://max.fileguard.io",
+ ).get_json()
+
+ assert default_session["authenticated"] is True
+ assert default_session["authorization_state"] == "current"
+ assert custom_session["authenticated"] is True
+ assert custom_session["authorization_state"] == "current"
+ assert refreshed_subjects == ["default-user", "custom-user"]
- _remote_access.runtime.read_json = delayed_read_json
- try:
- result_queue.put(("ok", _remote_access._replace_authorization_revision(config, 42)))
- except Exception as exc:
- result_queue.put(("error", repr(exc)))
+def test_revision_snapshot_expiry_and_renewal_fail_closed(monkeypatch, tmp_path):
+ """I1057-AC4: offline snapshots and renewal races cannot extend old claims."""
-def _authorization_revision_acknowledgement_writer(
- home: str,
- attempted: Any,
- done: Any,
- result_queue: Any,
-) -> None:
- import os as _os
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ payload = remote_access.parse_session_cookie(config, cookie)
+ assert payload is not None
- _os.environ["AVIBE_HOME"] = home
- from config.v2_config import V2Config as _V2Config
- from vibe import remote_access as _remote_access
+ remote_access._replace_authorization_revision(config, 42)
+ with pytest.raises(
+ remote_access.OAuthCodeExchangeError,
+ match="stale_authorization_revision",
+ ):
+ remote_access.make_session_cookie(
+ config,
+ "user-1",
+ session_claims=payload,
+ )
- config = _V2Config.load()
- attempted.set()
- try:
- result_queue.put(("ok", _remote_access.acknowledge_authorization_revision(config, 43)))
- except Exception as exc:
- result_queue.put(("error", repr(exc)))
- finally:
- done.set()
+ remote_access._replace_authorization_revision(config, 42)
+ snapshot = remote_access._load_authorization_revision_snapshot(config)
+ assert snapshot is not None
+ _, updated_at = snapshot
+ assert remote_access.session_authorization_is_current(
+ config,
+ {"vibe_instance_authorization_revision": 42},
+ now=updated_at + remote_access.AUTHORIZATION_REVISION_MAX_AGE_SECONDS + 1,
+ ) is False
-def test_authorization_revision_device_contract_is_monotonic(monkeypatch, tmp_path):
- """I1057-AC2/AC3: one paired-device watermark drives every hostname."""
+def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path):
+ """I1057-AC4/AC6: active and resumed SSE streams converge on the watermark."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- calls = []
-
- def request(cfg, method, suffix, payload=None, *, timeout=8.0):
- calls.append((cfg, method, suffix, payload, timeout))
- return {"authorization_revision": 42}
+ cookie = _organization_cookie(config)
+ payload = remote_access.parse_session_cookie(config, cookie)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert payload is not None
+ assert identity is not None
+ context = context_from_session_payload(payload)
- monkeypatch.setattr(remote_access, "_device_json_request", request)
+ class EmptyShowEventStore:
+ def list(self, *args, **kwargs):
+ return {"events": [], "next_after_id": None}
- assert remote_access.sync_authorization_revision_once(config) == {
- "ok": True,
- "authorization_revision": 42,
- }
- assert calls == [(config, "GET", "authorization-revision", None, 8.0)]
- assert remote_access.current_authorization_revision(config) == 42
+ def close(self):
+ return None
+ monkeypatch.setattr(ui_server, "_show_session_event_store", EmptyShowEventStore)
monkeypatch.setattr(
remote_access,
"_device_json_request",
- lambda *args, **kwargs: {"authorization_revision": 41},
- )
- assert remote_access.sync_authorization_revision_once(config) == {
- "ok": False,
- "error": "authorization_revision_regressed",
- }
- assert remote_access.current_authorization_revision(config) == 42
-
-
-def test_authorization_revision_writes_are_monotonic_across_processes(
- monkeypatch,
- tmp_path,
-):
- """A delayed synchronization write cannot replace a newer acknowledgement."""
-
- import multiprocessing as mp
-
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- _paired_config(tmp_path, revision=41)
- ctx = mp.get_context("spawn")
- sync_entered = ctx.Event()
- release_sync = ctx.Event()
- acknowledgement_attempted = ctx.Event()
- acknowledgement_done = ctx.Event()
- sync_result = ctx.Queue()
- acknowledgement_result = ctx.Queue()
- sync_writer = ctx.Process(
- target=_delayed_authorization_revision_sync_writer,
- args=(str(tmp_path), sync_entered, release_sync, sync_result),
- )
- acknowledgement_writer = ctx.Process(
- target=_authorization_revision_acknowledgement_writer,
- args=(
- str(tmp_path),
- acknowledgement_attempted,
- acknowledgement_done,
- acknowledgement_result,
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
),
)
- sync_writer.start()
- assert sync_entered.wait(timeout=15), "sync writer never entered its transaction"
- acknowledgement_writer.start()
- assert acknowledgement_attempted.wait(timeout=15), "acknowledgement writer never attempted"
- assert not acknowledgement_done.wait(timeout=1), (
- "acknowledgement writer bypassed the synchronization transaction"
- )
- release_sync.set()
- sync_writer.join(timeout=15)
- acknowledgement_writer.join(timeout=15)
-
- assert sync_writer.exitcode == 0, f"sync writer failed: {sync_writer.exitcode}"
- assert acknowledgement_writer.exitcode == 0, (
- f"acknowledgement writer failed: {acknowledgement_writer.exitcode}"
- )
- assert sync_result.get(timeout=5) == ("ok", 42)
- assert acknowledgement_result.get(timeout=5) == ("ok", 43)
- persisted = remote_access.runtime.read_json(
- remote_access._authorization_revision_state_path()
- )
- assert persisted["authorization_revision"] == 43
-
-
-def test_authorization_revision_cache_observes_another_process_watermark(
- monkeypatch,
- tmp_path,
-):
- """A controller cache must observe a mutation persisted by the UI server."""
-
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_config(tmp_path, revision=41)
- claims = _organization_claims(config, revision=41)
- source_updated_at = time.time()
-
- assert remote_access.session_authorization_revision_state(
- config,
- claims,
- now=source_updated_at,
- ) == "current"
+ async def exercise() -> None:
+ with app.test_request_context(
+ "/api/events",
+ base_url="https://alex.avibe.bot",
+ headers={"Cookie": f"{remote_access.SESSION_COOKIE_NAME}={cookie}"},
+ ):
+ g.authorization_context = context
+ g.remote_session_identity = identity
+ g.remote_session_payload = payload
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ for _ in range(3):
+ await iterator.__anext__()
+ remote_access._replace_authorization_revision(config, 42)
+ terminal = await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ assert '"state":"revoked"' in terminal
+ with pytest.raises(StopAsyncIteration):
+ await asyncio.wait_for(iterator.__anext__(), timeout=1)
+ finally:
+ await iterator.aclose()
- remote_access.runtime.write_json(
- remote_access._authorization_revision_state_path(), # noqa: SLF001
- {
- "schema_version": 1,
- "instance_id": "inst_123",
- "authorization_revision": 42,
- "source_updated_at": source_updated_at,
- },
- )
+ remote_access._replace_authorization_revision(config, 42)
+ show_response = await ui_server._show_events_stream(
+ "ses123",
+ after_id="show_evt_resume",
+ authorization_context=context,
+ remote_session_identity=identity,
+ remote_session_payload=payload,
+ remote_session_cookie=cookie,
+ remote_request_host="alex.avibe.bot",
+ remote_config=config,
+ )
+ show_iterator = show_response.body_iterator.__aiter__()
+ try:
+ terminal = await asyncio.wait_for(show_iterator.__anext__(), timeout=1)
+ assert '"state":"revoked"' in terminal
+ with pytest.raises(StopAsyncIteration):
+ await asyncio.wait_for(show_iterator.__anext__(), timeout=1)
+ finally:
+ await show_iterator.aclose()
- assert remote_access.session_authorization_revision_state(
- config,
- claims,
- now=source_updated_at,
- ) == "mismatch"
+ asyncio.run(exercise())
- ("changed_field", "replacement"),
- (
- ("backend_url", "https://other-backend.test"),
- ("instance_id", "inst_new"),
- ("instance_secret", "other-secret"),
- ),
-)
-def test_authorization_revision_acknowledgement_rejects_a_stale_pairing(
- monkeypatch,
- tmp_path,
- changed_field,
- replacement,
-):
- """A mutation from instance A cannot replace the watermark after pairing B."""
+def test_websocket_reconnect_and_active_waiter_recheck_revision(monkeypatch, tmp_path):
+ """I1057-AC4/AC6: active sockets close and stale reconnects are rejected."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_config(tmp_path, revision=41)
- current = V2Config.load()
- setattr(current.remote_access.vibe_cloud, changed_field, replacement)
- current.save()
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
- with pytest.raises(
- remote_access.AuthorizationRevisionPairingChangedError,
- match="authorization_revision_pairing_changed",
- ):
- remote_access.acknowledge_authorization_revision(config, 42)
+ class Socket:
+ cookies = {remote_access.SESSION_COOKIE_NAME: cookie}
- persisted = remote_access.runtime.read_json(
- remote_access._authorization_revision_state_path()
+ websocket = Socket()
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
+ monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)
+ monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")
+ monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ remote_access.BackendRequestError(403, {"error": "access_denied"})
+ ),
)
- assert persisted["instance_id"] == "inst_123"
- assert persisted["authorization_revision"] == 41
+ payload = ui_server._remote_access_websocket_session_payload(websocket, config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert payload is not None
+ assert identity is not None
+
+ async def exercise() -> None:
+ waiter = asyncio.create_task(
+ ui_server._wait_for_remote_session_authorization_loss(
+ config,
+ identity,
+ payload,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ )
+ )
+ await asyncio.sleep(0)
+ remote_access._replace_authorization_revision(config, 42)
+ assert await asyncio.wait_for(waiter, timeout=1) == "revoked"
-def test_authorization_revision_acknowledgement_rechecks_pairing_at_locked_write(
- monkeypatch,
- tmp_path,
-):
- """A pairing switch at the watermark lock cannot let the old write through."""
+ asyncio.run(exercise())
+ assert ui_server._remote_access_websocket_session_payload(websocket, config) is None
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_config(tmp_path, revision=41)
- original_lock = remote_access._authorization_revision_file_lock # noqa: SLF001
- switched = False
- def switch_before_locked_read(path):
- nonlocal switched
- if not switched:
- switched = True
- current = V2Config.load()
- current.remote_access.vibe_cloud.instance_id = "inst_new"
- current.save()
- return original_lock(path)
+def test_remote_websocket_authorization_rejects_disabled_cloud(monkeypatch, tmp_path):
+ config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ config.remote_access.vibe_cloud.enabled = False
+ class Socket:
+ cookies = {remote_access.SESSION_COOKIE_NAME: cookie}
+
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
+ monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)
+ monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")
monkeypatch.setattr(
remote_access,
- "_authorization_revision_file_lock",
- switch_before_locked_read,
+ "resolve_current_authorization_async",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("disabled remote socket reached the authorization resolver")
+ ),
)
- with pytest.raises(
- remote_access.AuthorizationRevisionPairingChangedError,
- match="authorization_revision_pairing_changed",
- ):
- remote_access.acknowledge_authorization_revision(config, 42)
-
- persisted = remote_access.runtime.read_json(
- remote_access._authorization_revision_state_path()
+ identity, resolution = asyncio.run(
+ ui_server._remote_access_websocket_authorization(Socket(), config)
)
- assert persisted["instance_id"] == "inst_123"
- assert persisted["authorization_revision"] == 41
+ assert identity is None
+ assert resolution.state == "invalid_identity"
+ assert resolution.reason == "remote_access_disabled"
[email protected]("persistence_failure", ("write_error", "lock_timeout"))
-def test_authorization_revision_sync_rejects_an_unpersisted_watermark(
+
+def test_live_remote_authorization_rechecks_the_remote_entry_gate(
monkeypatch,
tmp_path,
- persistence_failure,
):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
monkeypatch.setattr(
remote_access,
- "_device_json_request",
- lambda *_args, **_kwargs: {"authorization_revision": 42},
+ "resolve_current_authorization_async",
+ lambda *args, **kwargs: (_ for _ in ()).throw(
+ AssertionError("invalid live session reached the authorization resolver")
+ ),
)
- if persistence_failure == "write_error":
- monkeypatch.setattr(
- remote_access.runtime,
- "write_json",
- lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ disabled = asyncio.run(
+ ui_server._live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
)
- else:
- def timed_out_lock(_path):
- raise MigrationLockTimeout("watermark lock timed out")
+ )
+ assert disabled.state == "invalid_identity"
+ assert disabled.reason == "remote_access_disabled"
- monkeypatch.setattr(
- remote_access,
- "_authorization_revision_file_lock",
- timed_out_lock,
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.session_secret = "rotated-session-secret"
+ config.save()
+ rotated = asyncio.run(
+ ui_server._live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
)
+ )
+ assert rotated.state == "invalid_identity"
+ assert rotated.reason == "identity_invalid"
- assert remote_access.sync_authorization_revision_once(config) == {
- "ok": False,
- "error": "authorization_revision_sync_failed",
- }
- assert remote_access.current_authorization_revision(config) == 41
+ config.remote_access.vibe_cloud.session_secret = "session-secret"
+ config.remote_access.vibe_cloud.public_url = "https://other.avibe.bot"
+ config.save()
+ moved = asyncio.run(
+ ui_server._live_remote_authorization_resolution(
+ config,
+ identity,
+ session_cookie=cookie,
+ request_host="alex.avibe.bot",
+ )
+ )
+ assert moved.state == "invalid_identity"
+ assert moved.reason == "remote_access_host_mismatch"
- "malformed",
- (
- b"\xff",
- b"{not-json",
- b'{"schema_version":1,"instance_id":"inst_123","authorization_revision":"bad","source_updated_at":0}',
- ),
-)
-def test_authorization_revision_read_treats_malformed_content_as_absent(
+def test_terminal_websocket_reports_stale_remote_session_after_accept(
monkeypatch,
tmp_path,
- malformed,
):
+ """I1057-AC4: no terminal service starts before a state-specific close."""
+
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- remote_access._authorization_revision_state_path().write_bytes(malformed) # noqa: SLF001
- remote_access._clear_authorization_revision_cache() # noqa: SLF001
- assert remote_access.current_authorization_revision(config) is None
+ class RecordingWebSocket:
+ client = None
+ headers = {"host": "alex.avibe.bot"}
+ query_params = {}
+ def __init__(self):
+ self.calls = []
- "malformed",
- (
- b"\xff",
- b"{not-json",
- b'{"schema_version":1,"instance_id":"inst_123","authorization_revision":"bad","source_updated_at":0}',
- ),
-)
-def test_authorization_acknowledgement_keeps_memory_revision_when_rewrite_fails(
- monkeypatch,
- tmp_path,
- malformed,
-):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_config(tmp_path)
- state_path = remote_access._authorization_revision_state_path() # noqa: SLF001
- state_path.write_bytes(malformed)
- remote_access._clear_authorization_revision_cache() # noqa: SLF001
- published = []
+ async def accept(self):
+ self.calls.append(("accept", None))
+
+ async def close(self, code=1000):
+ self.calls.append(("close", code))
+
+ websocket = RecordingWebSocket()
+ monkeypatch.setattr(ui_server, "_terminal_enabled", lambda: True)
+ monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)
+ monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda socket: True)
+ monkeypatch.setattr(ui_server, "_load_remote_access_config", lambda: config)
+ monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *a: False)
monkeypatch.setattr(
- remote_access.runtime,
- "write_json",
- lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
+ ui_server,
+ "_remote_access_websocket_authorization",
+ lambda *args, **kwargs: asyncio.sleep(
+ 0,
+ result=(None, remote_access.AuthorizationResolution("unavailable")),
+ ),
)
monkeypatch.setattr(
- broker,
- "publish",
- lambda event_type, data: published.append((event_type, data)),
+ ui_server,
+ "get_terminal_service",
+ lambda: (_ for _ in ()).throw(AssertionError("stale socket reached terminal")),
)
- assert remote_access.acknowledge_authorization_revision(config, 42) == 42
- assert remote_access.current_authorization_revision(config) == 42
- assert published == [
- ("authorization.changed", {"instance_authorization_revision": 42})
- ]
-
-
-def test_authorization_revision_sync_keeps_strict_write_after_malformed_read(
- monkeypatch,
- tmp_path,
-):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_config(tmp_path)
- remote_access._authorization_revision_state_path().write_bytes(b"\xff") # noqa: SLF001
- remote_access._clear_authorization_revision_cache() # noqa: SLF001
- monkeypatch.setattr(
- remote_access.runtime,
- "write_json",
- lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("read-only state")),
- )
+ asyncio.run(ui_server.terminal_websocket(websocket, "test"))
- with pytest.raises(OSError, match="read-only state"):
- remote_access._replace_authorization_revision(config, 42) # noqa: SLF001
+ assert websocket.calls == [
+ ("accept", None),
+ ("close", ui_server._AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE),
+ ]
-def test_paired_session_requires_signed_current_revision(monkeypatch, tmp_path):
- """I1057-AC4: unsigned, missing, and stale authorization versions fail closed."""
+def test_trusted_local_access_ignores_hosted_revision_state(monkeypatch, tmp_path):
+ """I1057-AC5: trusted local access stays owner-equivalent while sync is offline."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- missing = _organization_claims(config)
- missing.pop("vibe_instance_authorization_revision")
-
- with pytest.raises(
- remote_access.OAuthCodeExchangeError,
- match="invalid_authorization_revision",
- ):
- remote_access.make_session_cookie(
- config,
- "user-1",
- session_claims=missing,
- )
+ state_path = remote_access._authorization_revision_state_path()
+ state_path.unlink()
+ remote_access._clear_authorization_revision_cache()
+ assert remote_access.current_authorization_revision(config) is None
- with pytest.raises(
- remote_access.OAuthCodeExchangeError,
- match="stale_authorization_revision",
- ):
- _organization_cookie(config, revision=40)
+ response = app.test_client().get(
+ "/api/config",
+ base_url="http://127.0.0.1:5123",
+ )
+ assert response.status_code == 200
+ assert response.get_json()["runtime"]["default_cwd"] == "."
- "hosted_change",
- [
- "role_downgrade",
- "group_membership_removal",
- "group_archival",
- "member_removal",
- "access_binding_removal",
- ],
-)
-def test_revision_advance_revokes_active_editor_http_session(
+
+def test_denied_response_during_reconciliation_does_not_persist_revoked(
monkeypatch,
tmp_path,
- hosted_change,
):
- """I1057-AC1/AC2: narrowing invalidates a remote session with chat enabled."""
+ """Regression PR #1606 r1: a 403 racing a same-generation reconciliation
+ must not persist a revoked row the completed binding then trips over."""
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
cookie = _organization_cookie(config)
- payload = remote_access.parse_session_cookie(config, cookie)
- assert payload is not None
- assert context_from_session_payload(payload).can_chat is True
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert record is not None
+ # A reconciliation begins BEFORE the refresh starts: same generation is
+ # captured, and completing a transition does not increment it.
+ started = remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ assert (
+ started["state"]
+ == remote_access_authorization_service.INSTANCE_BINDING_STATE_RECONCILING
+ )
- client = app.test_client()
- client.set_cookie(remote_access.SESSION_COOKIE_NAME, cookie, domain="alex.avibe.bot")
- headers = csrf_headers(client, "https://alex.avibe.bot")
- before = client.post(
- "/api/sessions",
- base_url="https://alex.avibe.bot",
- headers=headers,
- json={},
+ def deny(*args, **kwargs):
+ raise remote_access.BackendRequestError(403, {"error": "access_denied"})
+
+ monkeypatch.setattr(remote_access, "_device_json_request", deny)
+
+ result = remote_access._fetch_authorization_context(
+ config,
+ identity,
+ record,
+ now=now,
+ observed_revision=41,
)
- assert before.status_code == 400
- assert hosted_change
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- remote_access.BackendRequestError(403, {"error": "access_denied"})
- ),
+ assert result.state == "unavailable"
+ assert result.reason == "instance_binding_changed"
+ stored = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
- remote_access._replace_authorization_revision(config, 42)
- after = client.post(
- "/api/sessions",
- base_url="https://alex.avibe.bot",
- headers=headers,
- json={},
+ if stored is not None:
+ assert stored.get("authorization_state") != "revoked"
+
+
+def test_known_kind_without_binding_row_bootstraps_a_durable_transition(tmp_path):
+ """Regression PR #1606 r1: upgrade path — config carries a kind but the
+ state_meta binding row is absent; the gate must earn a validated row
+ through one real transition instead of trusting the config value."""
+
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+ # Simulate an upgrade: config has a known kind, the new state_meta row
+ # has not been written yet.
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import state_meta
+ from sqlalchemy import delete as sa_delete
+
+ ensure_sqlite_state()
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ conn.execute(
+ sa_delete(state_meta).where(
+ state_meta.c.key == remote_access_authorization_service.INSTANCE_BINDING_STATE_META_KEY
+ )
+ )
+ assert (
+ remote_access_authorization_service.load_instance_binding_state(ensure=False)
+ is None
)
+ # The storage gate alone fails closed for a known kind with no row.
+ assert remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id="inst_123",
+ instance_kind="personal",
+ ensure=False,
+ ) is False
- assert after.status_code == 403
- assert after.get_json()["error"] == "remote_access_revoked"
+ # The consumer gate bootstraps one durable transition, then admits.
+ assert remote_access.binding_is_ready(config) is True
+ state = remote_access_authorization_service.load_instance_binding_state(ensure=False)
+ assert state is not None
+ assert state["state"] == remote_access_authorization_service.INSTANCE_BINDING_STATE_READY
+ assert state["instance_id"] == "inst_123"
+ assert state["instance_kind"] == "personal"
+ assert state["generation"] >= 1
-def test_default_and_custom_hostname_sessions_share_revision(monkeypatch, tmp_path):
- """I1057-AC3: host-scoped cookies cannot retain divergent authorization."""
+def test_personal_to_organization_reclassification_rejects_stale_personal_row(
+ monkeypatch,
+ tmp_path,
+):
+ """Regression PR #1606 r2: the kind-mismatch refresh must run before the
+ Organization branch too — a stale personal-tagged row must not be served
+ as current under the reclassified Organization policy."""
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- remote_access._replace_active_hostnames(config, ["max.fileguard.io"])
- default_client = app.test_client()
- custom_client = app.test_client()
- default_client.set_cookie(
- remote_access.SESSION_COOKIE_NAME,
- _organization_cookie(config, subject="default-user"),
- domain="alex.avibe.bot",
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
)
- custom_client.set_cookie(
- remote_access.SESSION_COOKIE_NAME,
- _organization_cookie(config, subject="custom-user"),
- domain="max.fileguard.io",
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ now = int(time.time())
+ stored = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
+ assert stored is not None
+ assert stored["claims"]["vibe_instance_kind"] == "personal"
- assert default_client.get(
- "/api/session",
- base_url="https://alex.avibe.bot",
- ).get_json()["authenticated"] is True
- assert custom_client.get(
- "/api/session",
- base_url="https://max.fileguard.io",
- ).get_json()["authenticated"] is True
+ # Controller heartbeat reclassifies Personal -> Organization.
+ assert remote_access._persist_instance_kind("inst_123", "organization", reconcile=True)
+ reclassified = V2Config.load()
+ assert reclassified.remote_access.vibe_cloud.instance_kind == "organization"
- refreshed_subjects = []
+ # The old personal-tagged row must not answer under the Organization policy.
+ blocked = remote_access.resolve_current_authorization(
+ reclassified,
+ identity,
+ allow_refresh=False,
+ )
+ assert blocked.current is False
- def refresh(_config, method, suffix, payload=None, *, timeout=8.0):
- assert (method, suffix, timeout) == ("POST", "authorization-context", 8.0)
- refreshed_subjects.append(payload["sub"])
- return {
- "sub": payload["sub"],
- "email": payload["email"],
- "instance_kind": "organization",
- **_organization_claims(config, revision=42),
- }
+ calls = []
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ calls.append(payload)
+ return _authorization_context_response(
+ config,
+ payload,
+ revision=41,
+ instance_kind="organization",
+ )
monkeypatch.setattr(remote_access, "_device_json_request", refresh)
- remote_access._replace_authorization_revision(config, 42)
- default_session = default_client.get(
- "/api/session",
- base_url="https://alex.avibe.bot",
- ).get_json()
- custom_session = custom_client.get(
- "/api/session",
- base_url="https://max.fileguard.io",
- ).get_json()
+ result = remote_access.resolve_current_authorization(reclassified, identity)
- assert default_session["authenticated"] is True
- assert default_session["authorization_state"] == "current"
- assert custom_session["authenticated"] is True
- assert custom_session["authorization_state"] == "current"
- assert refreshed_subjects == ["default-user", "custom-user"]
+ assert result.current is True
+ assert result.refreshed is True
+ assert result.policy == "organization"
+ assert len(calls) == 1
+ revalidated = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert revalidated is not None
+ assert revalidated["claims"]["vibe_instance_kind"] == "organization"
-def test_revision_snapshot_expiry_and_renewal_fail_closed(monkeypatch, tmp_path):
- """I1057-AC4: offline snapshots and renewal races cannot extend old claims."""
+def test_revoked_write_refused_when_transition_completes_between_check_and_write(
+ monkeypatch,
+ tmp_path,
+):
+ """Regression PR #1606 r3: the compare and the authorization-row write
+ are one atomic CAS under the binding lock. Completing a transition
+ between a TOCTOU-style check and the write must refuse the revoked upsert.
+ """
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
cookie = _organization_cookie(config)
- payload = remote_access.parse_session_cookie(config, cookie)
- assert payload is not None
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert record is not None
+ started = remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ captured = remote_access_authorization_service.current_instance_binding_generation()
- remote_access._replace_authorization_revision(config, 42)
- with pytest.raises(
- remote_access.OAuthCodeExchangeError,
- match="stale_authorization_revision",
- ):
- remote_access.make_session_cookie(
- config,
- "user-1",
- session_claims=payload,
+ def deny(*args, **kwargs):
+ # Completes AFTER _fetch captured the reconciling generation and
+ # BEFORE the revoked upsert — the atomic CAS must refuse the write.
+ remote_access_authorization_service.complete_instance_binding_transition(
+ instance_id="inst_123",
+ instance_kind="personal",
+ generation=started["generation"],
)
+ raise remote_access.BackendRequestError(403, {"error": "access_denied"})
- remote_access._replace_authorization_revision(config, 42)
- snapshot = remote_access._load_authorization_revision_snapshot(config)
- assert snapshot is not None
- _, updated_at = snapshot
- assert remote_access.session_authorization_is_current(
+ monkeypatch.setattr(remote_access, "_device_json_request", deny)
+
+ result = remote_access._fetch_authorization_context(
config,
- {"vibe_instance_authorization_revision": 42},
- now=updated_at + remote_access.AUTHORIZATION_REVISION_MAX_AGE_SECONDS + 1,
- ) is False
+ identity,
+ record,
+ now=now,
+ observed_revision=41,
+ )
+ stored = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert result.reason == "instance_binding_changed" or (
+ stored is not None and stored.get("authorization_state") != "revoked"
+ )
+ if stored is not None:
+ assert stored.get("authorization_state") != "revoked"
+ # The captured generation is no longer current.
+ assert remote_access_authorization_service.current_instance_binding_generation() >= captured
-def test_workbench_and_show_sse_end_after_revision_change(monkeypatch, tmp_path):
- """I1057-AC4/AC6: active and resumed SSE streams converge on the watermark."""
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+def test_kindless_current_row_revalidates_after_known_kind_bootstrap(
+ monkeypatch,
+ tmp_path,
+):
+ """Regression PR #1606 r4: a released current row with no vibe_instance_kind
+ must refresh on the first request after a known-kind Personal pairing
+ bootstraps, instead of returning a kindless payload.
+ """
+
config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
cookie = _organization_cookie(config)
- payload = remote_access.parse_session_cookie(config, cookie)
identity = remote_access.parse_session_identity(config, cookie)
- assert payload is not None
assert identity is not None
- context = context_from_session_payload(payload)
-
- class EmptyShowEventStore:
- def list(self, *args, **kwargs):
- return {"events": [], "next_after_id": None}
-
- def close(self):
- return None
-
- monkeypatch.setattr(ui_server, "_show_session_event_store", EmptyShowEventStore)
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- remote_access.BackendRequestError(403, {"error": "access_denied"})
- ),
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
-
- async def exercise() -> None:
- with app.test_request_context(
- "/api/events",
- base_url="https://alex.avibe.bot",
- headers={"Cookie": f"{remote_access.SESSION_COOKIE_NAME}={cookie}"},
- ):
- g.authorization_context = context
- g.remote_session_identity = identity
- g.remote_session_payload = payload
- response = await ui_server.workbench_events()
- iterator = response.body_iterator.__aiter__()
- try:
- for _ in range(3):
- await iterator.__anext__()
- remote_access._replace_authorization_revision(config, 42)
- terminal = await asyncio.wait_for(iterator.__anext__(), timeout=1)
- assert '"state":"revoked"' in terminal
- with pytest.raises(StopAsyncIteration):
- await asyncio.wait_for(iterator.__anext__(), timeout=1)
- finally:
- await iterator.aclose()
-
- remote_access._replace_authorization_revision(config, 42)
- show_response = await ui_server._show_events_stream(
- "ses123",
- after_id="show_evt_resume",
- authorization_context=context,
- remote_session_identity=identity,
- remote_session_payload=payload,
- remote_session_cookie=cookie,
- remote_request_host="alex.avibe.bot",
- remote_config=config,
+ assert record is not None
+ claims = dict(record["claims"])
+ claims.pop("vibe_instance_kind", None)
+ remote_access_authorization_service.upsert_scoped(
+ reference=record["id"],
+ instance_id="inst_123",
+ subject="user-1",
+ email=record["email"],
+ scope_kind=record["scope_kind"],
+ scope_ref=record["scope_ref"],
+ authorization_state="current",
+ claims=claims,
+ last_checked_at=now,
+ updated_at=now,
+ )
+ calls = []
+
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ calls.append(payload)
+ return _authorization_context_response(
+ config,
+ payload,
+ revision=41,
+ instance_kind="personal",
)
- show_iterator = show_response.body_iterator.__aiter__()
- try:
- terminal = await asyncio.wait_for(show_iterator.__anext__(), timeout=1)
- assert '"state":"revoked"' in terminal
- with pytest.raises(StopAsyncIteration):
- await asyncio.wait_for(show_iterator.__anext__(), timeout=1)
- finally:
- await show_iterator.aclose()
- asyncio.run(exercise())
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ result = remote_access.resolve_current_authorization(config, identity)
-def test_websocket_reconnect_and_active_waiter_recheck_revision(monkeypatch, tmp_path):
- """I1057-AC4/AC6: active sockets close and stale reconnects are rejected."""
+ assert result.current is True
+ assert result.refreshed is True
+ assert result.policy == "personal"
+ assert len(calls) == 1
+ assert result.payload is not None
+ assert result.payload.get("vibe_instance_kind") == "personal"
+
+
+def test_binding_decoder_rejects_explicit_non_v1_schema_versions(tmp_path):
+ """Regression PR #1606 r5: only a genuinely absent schema_version defaults
+ to v1; explicit 0 or 2 must fail closed.
+ """
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- cookie = _organization_cookie(config)
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.models import state_meta
+ from sqlalchemy.dialects.sqlite import insert as sqlite_insert
+
+ ensure_sqlite_state()
+ engine = get_cached_sqlite_engine()
+ for version in (0, 2):
+ payload = json.dumps(
+ {
+ "schema_version": version,
+ "state": "ready",
+ "instance_id": "inst_123",
+ "instance_kind": "personal",
+ "generation": 1,
+ "updated_at": "1",
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ with engine.begin() as conn:
+ statement = sqlite_insert(state_meta).values(
+ key=remote_access_authorization_service.INSTANCE_BINDING_STATE_META_KEY,
+ value_json=payload,
+ updated_at="1",
+ )
+ conn.execute(
+ statement.on_conflict_do_update(
+ index_elements=[state_meta.c.key],
+ set_={"value_json": payload, "updated_at": "1"},
+ )
+ )
+ decoded = remote_access_authorization_service.load_instance_binding_state(
+ ensure=False
+ )
+ assert decoded is None or decoded.get("state") == remote_access_authorization_service.INSTANCE_BINDING_STATE_INVALID
+ assert remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id="inst_123",
+ instance_kind="personal",
+ ensure=False,
+ ) is False
- class Socket:
- cookies = {remote_access.SESSION_COOKIE_NAME: cookie}
- websocket = Socket()
- monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
- monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)
- monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")
- monkeypatch.setattr(ui_server, "_AUTHORIZATION_REVISION_RECHECK_SECONDS", 0.001)
- monkeypatch.setattr(
- remote_access,
- "_device_json_request",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- remote_access.BackendRequestError(403, {"error": "access_denied"})
- ),
- )
+def test_refresh_cache_does_not_serve_personal_payload_after_org_reclassification(
+ monkeypatch,
+ tmp_path,
+):
+ """Class 1: in-memory refresh cache is bound to generation.
- payload = ui_server._remote_access_websocket_session_payload(websocket, config)
+ After a successful Personal refresh, a Personal→Org reclassification
+ within the 5s window must not return the cached Personal payload.
+ """
+
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ cookie = _organization_cookie(config)
identity = remote_access.parse_session_identity(config, cookie)
- assert payload is not None
assert identity is not None
+ calls = []
- async def exercise() -> None:
- waiter = asyncio.create_task(
- ui_server._wait_for_remote_session_authorization_loss(
- config,
- identity,
- payload,
- session_cookie=cookie,
- request_host="alex.avibe.bot",
- )
+ def refresh(_config, _method, _suffix, payload, **kwargs):
+ calls.append(payload)
+ kind = V2Config.load().remote_access.vibe_cloud.instance_kind or "personal"
+ return _authorization_context_response(
+ config,
+ payload,
+ revision=41,
+ instance_kind=kind if kind in {"personal", "organization"} else "personal",
)
- await asyncio.sleep(0)
- remote_access._replace_authorization_revision(config, 42)
- assert await asyncio.wait_for(waiter, timeout=1) == "revoked"
- asyncio.run(exercise())
- assert ui_server._remote_access_websocket_session_payload(websocket, config) is None
+ monkeypatch.setattr(remote_access, "_device_json_request", refresh)
+ first = remote_access.resolve_current_authorization(config, identity)
+ assert first.current is True
+ assert first.policy == "personal"
+ first_calls = len(calls)
+ assert remote_access._persist_instance_kind("inst_123", "organization", reconcile=True)
+ reclassified = V2Config.load()
+ second = remote_access.resolve_current_authorization(reclassified, identity)
+ assert second.policy != "personal" or second.current is False or second.refreshed is True
+ if second.current:
+ assert second.policy == "organization"
+ assert len(calls) > first_calls
+
+
+def test_in_flight_auth_during_same_instance_kind_transition_is_binding_changed(
+ monkeypatch,
+ tmp_path,
+):
+ """Class 3: same-instance generation advance IS instance_binding_changed."""
-def test_remote_websocket_authorization_rejects_disabled_cloud(monkeypatch, tmp_path):
config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
cookie = _organization_cookie(config)
- config.remote_access.vibe_cloud.enabled = False
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert record is not None
+ captured = remote_access_authorization_service.current_instance_binding_generation()
- class Socket:
- cookies = {remote_access.SESSION_COOKIE_NAME: cookie}
+ def flip_then_respond(_config, _method, _suffix, payload, **kwargs):
+ remote_access._persist_instance_kind("inst_123", "personal", reconcile=True)
+ return _authorization_context_response(
+ config, payload, revision=41, instance_kind="organization"
+ )
- monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *args: False)
- monkeypatch.setattr(ui_server, "_remote_access_host_allowed", lambda *args: True)
- monkeypatch.setattr(ui_server, "_websocket_normalized_host", lambda *args: "alex.avibe.bot")
+ monkeypatch.setattr(remote_access, "_device_json_request", flip_then_respond)
+ result = remote_access._fetch_authorization_context(
+ config, identity, record, now=now, observed_revision=41
+ )
+ assert result.reason == "instance_binding_changed"
+ assert result.reason != "instance_kind_persistence_failed"
+ # A subsequent request for the new binding is not 5s-denied by the old failure.
monkeypatch.setattr(
remote_access,
- "resolve_current_authorization_async",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- AssertionError("disabled remote socket reached the authorization resolver")
+ "_device_json_request",
+ lambda _c, _m, _s, payload, **k: _authorization_context_response(
+ config, payload, revision=41, instance_kind="personal"
),
)
-
- identity, resolution = asyncio.run(
- ui_server._remote_access_websocket_authorization(Socket(), config)
- )
-
- assert identity is None
- assert resolution.state == "invalid_identity"
- assert resolution.reason == "remote_access_disabled"
+ later = remote_access.resolve_current_authorization(V2Config.load(), identity)
+ assert later.reason != "authorization_refresh_backoff"
+ assert remote_access_authorization_service.current_instance_binding_generation() > captured
-def test_live_remote_authorization_rechecks_the_remote_entry_gate(
+def test_successful_context_store_refused_when_generation_advances_after_persist_kind(
monkeypatch,
tmp_path,
):
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ """Class close: every authorization-row write carries the REQUEST generation.
+
+ persist-kind CAS succeeds at request gen; a peer then completes a
+ transition (gen advances) before store. Recapturing live generation
+ would let the stale 200 resurrect a current row. Store must refuse.
+ """
+
config = _paired_config(tmp_path)
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="organization",
+ )
cookie = _organization_cookie(config)
identity = remote_access.parse_session_identity(config, cookie)
assert identity is not None
- monkeypatch.setattr(
- remote_access,
- "resolve_current_authorization_async",
- lambda *args, **kwargs: (_ for _ in ()).throw(
- AssertionError("invalid live session reached the authorization resolver")
- ),
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
+ assert record is not None
+ original_state = record.get("authorization_state")
+ captured = remote_access_authorization_service.current_instance_binding_generation()
- config.remote_access.vibe_cloud.enabled = False
- config.save()
- disabled = asyncio.run(
- ui_server._live_remote_authorization_resolution(
- config,
- identity,
- session_cookie=cookie,
- request_host="alex.avibe.bot",
- )
- )
- assert disabled.state == "invalid_identity"
- assert disabled.reason == "remote_access_disabled"
+ original_store = remote_access._store_scoped_authorization
+ advanced = {"done": False}
- config.remote_access.vibe_cloud.enabled = True
- config.remote_access.vibe_cloud.session_secret = "rotated-session-secret"
- config.save()
- rotated = asyncio.run(
- ui_server._live_remote_authorization_resolution(
- config,
- identity,
- session_cookie=cookie,
- request_host="alex.avibe.bot",
- )
- )
- assert rotated.state == "invalid_identity"
- assert rotated.reason == "identity_invalid"
+ def store_after_peer_transition(*args, **kwargs):
+ if not advanced["done"]:
+ advanced["done"] = True
+ remote_access._persist_instance_kind("inst_123", "personal", reconcile=True)
+ return original_store(*args, **kwargs)
- config.remote_access.vibe_cloud.session_secret = "session-secret"
- config.remote_access.vibe_cloud.public_url = "https://other.avibe.bot"
- config.save()
- moved = asyncio.run(
- ui_server._live_remote_authorization_resolution(
- config,
- identity,
- session_cookie=cookie,
- request_host="alex.avibe.bot",
- )
+ monkeypatch.setattr(remote_access, "_store_scoped_authorization", store_after_peer_transition)
+ monkeypatch.setattr(
+ remote_access,
+ "_device_json_request",
+ lambda _c, _m, _s, payload, **k: _authorization_context_response(
+ config, payload, revision=41, instance_kind="organization"
+ ),
)
- assert moved.state == "invalid_identity"
- assert moved.reason == "remote_access_host_mismatch"
+ result = remote_access._fetch_authorization_context(
+ config, identity, record, now=now, observed_revision=41
+ )
+ stored = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
+ )
+ assert result.reason == "instance_binding_changed"
+ assert result.current is False
+ if stored is not None:
+ # Must not resurrect a current Organization row under the new Personal binding.
+ if stored.get("authorization_state") == "current":
+ claims = stored.get("claims") or {}
+ assert claims.get("vibe_instance_kind") != "organization" or (
+ stored.get("authorization_state") == original_state
+ )
+ assert remote_access_authorization_service.current_instance_binding_generation() > captured
-def test_terminal_websocket_reports_stale_remote_session_after_accept(
+def test_interactive_gate_is_read_once_and_failed_gate_never_collapses_to_legacy(
monkeypatch,
tmp_path,
):
- """I1057-AC4: no terminal service starts before a state-specific close."""
+ """Class 2 (interactive path): one binding-gate snapshot per evaluation.
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _paired_config(tmp_path)
+ A reconciling that begins between record admission and the former second
+ gate call must not collapse instance_kind to None and return the old
+ Personal payload through the legacy branch.
+ """
- class RecordingWebSocket:
- client = None
- headers = {"host": "alex.avibe.bot"}
- query_params = {}
+ config = _paired_config(tmp_path)
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+ remote_access._transition_instance_binding(
+ instance_id="inst_123",
+ instance_kind="personal",
+ )
+ cookie = remote_access.make_session_cookie(
+ config,
+ "user-1",
+ session_claims={
+ "vibe_instance_id": config.remote_access.vibe_cloud.instance_id,
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_instance_kind": "personal",
+ "vibe_instance_authorization_revision": 41,
+ },
+ )
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
- def __init__(self):
- self.calls = []
+ calls = {"n": 0}
+ real_gate = remote_access.binding_is_ready
- async def accept(self):
- self.calls.append(("accept", None))
+ def counting_gate(*args, **kwargs):
+ calls["n"] += 1
+ # Simulate a peer entering reconciling right after the first read:
+ # any SECOND read within one evaluation would observe False.
+ if calls["n"] == 1:
+ return real_gate(*args, **kwargs)
+ return False
- async def close(self, code=1000):
- self.calls.append(("close", code))
+ monkeypatch.setattr(remote_access, "binding_is_ready", counting_gate)
+ result = remote_access.resolve_current_authorization(config, identity)
+ # One evaluation = one gate read; the flip value is never consumed.
+ assert calls["n"] == 1
+ # With the single ready snapshot the personal branch ran (not legacy).
+ assert result.current is True
+ assert result.policy == "personal"
- websocket = RecordingWebSocket()
- monkeypatch.setattr(ui_server, "_terminal_enabled", lambda: True)
- monkeypatch.setattr(ui_server, "TERMINAL_SUPPORTED", True)
- monkeypatch.setattr(ui_server, "_terminal_origin_allowed", lambda socket: True)
- monkeypatch.setattr(ui_server, "_load_remote_access_config", lambda: config)
- monkeypatch.setattr(ui_server, "_websocket_is_local_request", lambda *a: False)
- monkeypatch.setattr(
- ui_server,
- "_remote_access_websocket_authorization",
- lambda *args, **kwargs: asyncio.sleep(
- 0,
- result=(None, remote_access.AuthorizationResolution("unavailable")),
- ),
- )
- monkeypatch.setattr(
- ui_server,
- "get_terminal_service",
- lambda: (_ for _ in ()).throw(AssertionError("stale socket reached terminal")),
+ # Failed gate at snapshot time: fail closed (refresh/unavailable), never
+ # legacy-current with the old Personal payload.
+ calls["n"] = 0
+ monkeypatch.setattr(remote_access, "binding_is_ready", lambda *a, **k: False)
+ blocked = remote_access.resolve_current_authorization(
+ config, identity, allow_refresh=False
)
-
- asyncio.run(ui_server.terminal_websocket(websocket, "test"))
-
- assert websocket.calls == [
- ("accept", None),
- ("close", ui_server._AUTHORIZATION_UNAVAILABLE_WEBSOCKET_CLOSE_CODE),
- ]
+ assert blocked.current is False
+ assert blocked.state in {"unavailable", "invalid_identity"}
-def test_trusted_local_access_ignores_hosted_revision_state(monkeypatch, tmp_path):
- """I1057-AC5: trusted local access stays owner-equivalent while sync is offline."""
+def test_unsupported_stored_kind_fails_closed_on_the_interactive_path(
+ monkeypatch,
+ tmp_path,
+):
+ """A persisted scoped row with kind="enterprise" under a legacy no-kind
+ pairing must fail closed instead of falling through legacy-current."""
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config = _paired_config(tmp_path)
- state_path = remote_access._authorization_revision_state_path()
- state_path.unlink()
- remote_access._clear_authorization_revision_cache()
- assert remote_access.current_authorization_revision(config) is None
-
- response = app.test_client().get(
- "/api/config",
- base_url="http://127.0.0.1:5123",
+ config.remote_access.vibe_cloud.instance_kind = ""
+ config.save()
+ cookie = _organization_cookie(config)
+ identity = remote_access.parse_session_identity(config, cookie)
+ assert identity is not None
+ now = int(time.time())
+ record = remote_access_authorization_service.load_reference_record(
+ reference=identity["authorization_ref"],
+ instance_id="inst_123",
+ subject="user-1",
+ now=now,
)
-
- assert response.status_code == 200
- assert response.get_json()["runtime"]["default_cwd"] == "."
+ assert record is not None
+ claims = dict(record.get("claims") or {})
+ claims["vibe_instance_kind"] = "enterprise"
+ remote_access_authorization_service.upsert_scoped(
+ reference=str(record["id"]),
+ instance_id="inst_123",
+ subject="user-1",
+ scope_kind=str(record.get("scope_kind") or "instance"),
+ scope_ref=str(record.get("scope_ref") or "inst_123"),
+ authorization_state="current",
+ claims=claims,
+ last_checked_at=now,
+ updated_at=now,
+ )
+ blocked = remote_access.resolve_current_authorization(
+ config, identity, allow_refresh=False
+ )
+ assert blocked.current is False
+ assert blocked.state == "unavailable"
diff --git a/tests/test_resource_access_service.py b/tests/test_resource_access_service.py
index 2c0b20f95..7a7f777a4 100644
--- a/tests/test_resource_access_service.py
+++ b/tests/test_resource_access_service.py
@@ -1,12 +1,18 @@
from __future__ import annotations
+import hashlib
+import json
+
import pytest
+from sqlalchemy import select
from config.v2_config import V2Config
from storage import resource_access_service
+from storage.background import SQLiteBackgroundTaskStore
from storage.db import create_sqlite_engine
+from storage.message_deliveries import enqueue_queued
from storage.migrations import run_migrations
-from storage.models import resource_access_policies
+from storage.models import agent_runs, agent_sessions, message_deliveries, resource_access_policies, run_definitions, state_meta
from vibe import permissions
@@ -18,6 +24,7 @@ def _context(
role: str | None = "member",
instance_role: str = "editor",
access_source: str = "organization_group",
+ instance_kind: str | None = None,
) -> resource_access_service.ResourceUserContext:
return resource_access_service.ResourceUserContext(
subject=subject,
@@ -28,6 +35,7 @@ def _context(
instance_role=instance_role,
instance_access_source=access_source,
is_remote=True,
+ instance_kind=instance_kind,
)
@@ -87,6 +95,55 @@ def test_resource_acl_is_enforced_for_editors_and_unknown_kinds_fail_closed(tmp_
engine.dispose()
+def test_personal_editor_uses_all_agents_without_organization_acl(tmp_path) -> None:
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ with engine.begin() as connection:
+ _seed_policies(connection)
+ personal_editor = _context(
+ "personal-user",
+ organization_id=None,
+ role=None,
+ access_source="owner",
+ instance_kind="personal",
+ )
+ organization_editor = _context(
+ "organization-user",
+ instance_kind="organization",
+ )
+
+ assert resource_access_service.can_use_resource(
+ personal_editor, "agent", "private-agent", connection=connection
+ )
+ assert resource_access_service.can_use_resource(
+ personal_editor, "agent", "scoped-agent", connection=connection
+ )
+ assert resource_access_service.can_use_resource(
+ personal_editor, "agent", "unmanaged-agent", connection=connection
+ )
+ assert resource_access_service.filter_accessible_resources(
+ personal_editor,
+ "agent",
+ [
+ {"id": "private-agent"},
+ {"id": "scoped-agent"},
+ {"id": "unmanaged-agent"},
+ ],
+ connection=connection,
+ ) == [
+ {"id": "private-agent"},
+ {"id": "scoped-agent"},
+ {"id": "unmanaged-agent"},
+ ]
+ assert not resource_access_service.can_use_resource(
+ organization_editor, "agent", "private-agent", connection=connection
+ )
+ finally:
+ engine.dispose()
+
+
def test_show_page_is_no_longer_a_resource_kind(monkeypatch, tmp_path) -> None:
"""§3.2 retired show_page from the Resource ACL: every entry point fails
closed with ``invalid_resource_kind`` and nothing reads or writes a
@@ -364,9 +421,31 @@ def test_http_resource_services_reuse_the_parsed_authorization_context() -> None
assert resource_access_service.resolve_resource_access_context() is context
-def test_deferred_remote_context_remains_valid_past_authorization_refresh_boundary() -> None:
+def test_deferred_remote_context_remains_valid_past_authorization_refresh_boundary(
+ monkeypatch,
+ tmp_path,
+) -> None:
from vibe import remote_access
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "organization-instance"
+ config.remote_access.vibe_cloud.instance_kind = "organization"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="organization-instance",
+ instance_kind="organization",
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="organization-instance",
+ instance_kind="organization",
+ generation=started["generation"],
+ )
+
issued_at = 1_700_000_000
context = resource_access_service.ResourceUserContext(
subject="member-1",
@@ -377,6 +456,8 @@ def test_deferred_remote_context_remains_valid_past_authorization_refresh_bounda
membership_version="membership-v2",
instance_role="viewer",
instance_access_source="organization_group",
+ instance_kind="organization",
+ instance_id="organization-instance",
claims_issued_at=issued_at,
is_remote=True,
)
@@ -401,20 +482,1717 @@ def test_deferred_remote_context_remains_valid_past_authorization_refresh_bounda
assert after.is_active_organization_member is True
-def test_personal_resources_cannot_use_organization_access_levels(tmp_path) -> None:
+def test_deferred_personal_context_keeps_instance_kind(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "personal-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="personal-instance",
+ instance_kind="personal",
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="personal-instance",
+ instance_kind="personal",
+ generation=started["generation"],
+ )
+
+ context = resource_access_service.ResourceUserContext(
+ subject="personal-user",
+ instance_id="personal-instance",
+ instance_role="editor",
+ instance_access_source="owner",
+ instance_kind="personal",
+ is_remote=True,
+ )
+
+ metadata = resource_access_service.metadata_with_resource_user_context({}, context)
+ restored = resource_access_service.resource_user_context_from_metadata(metadata)
+
+ assert restored is not None
+ assert restored.is_personal_instance
+
+
+def test_deferred_context_from_previous_pairing_is_rejected(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "current-instance"
+ config.remote_access.vibe_cloud.instance_kind = "organization"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ stale_context = resource_access_service.ResourceUserContext(
+ subject="personal-user",
+ instance_id="previous-instance",
+ instance_role="editor",
+ instance_access_source="owner",
+ instance_kind="personal",
+ is_remote=True,
+ )
+ metadata = resource_access_service.metadata_with_resource_user_context({}, stale_context)
+
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ assert not resource_access_service.metadata_allows_harness_runtime(metadata)
+
+
+def test_deferred_context_does_not_project_personal_bypass_while_reconciling(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Non-interactive metadata must fail closed while the binding is reconciling."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "current-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ from storage import remote_access_authorization_service
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="current-instance",
+ instance_kind="personal",
+ )
+
+ personal_context = resource_access_service.ResourceUserContext(
+ subject="personal-user",
+ instance_id="current-instance",
+ instance_role="editor",
+ instance_access_source="owner",
+ instance_kind="personal",
+ is_remote=True,
+ )
+ metadata = resource_access_service.metadata_with_resource_user_context({}, personal_context)
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ assert not resource_access_service.metadata_allows_harness_runtime(metadata)
+
+
[email protected]("pairing_state", ["disabled", "unreadable", "partial"])
+def test_explicit_deferred_context_requires_current_pairing(
+ monkeypatch,
+ tmp_path,
+ pairing_state: str,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = pairing_state != "disabled"
+ config.remote_access.vibe_cloud.instance_id = "personal-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ if pairing_state != "partial":
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+ if pairing_state == "unreadable":
+ def fail_load(_cls, *_args, **_kwargs):
+ raise OSError("config unavailable")
+
+ monkeypatch.setattr(V2Config, "load", classmethod(fail_load))
+
+ context = resource_access_service.ResourceUserContext(
+ subject="personal-user",
+ instance_id="personal-instance",
+ instance_role="editor",
+ instance_access_source="owner",
+ instance_kind="personal",
+ is_remote=True,
+ )
+ metadata = resource_access_service.metadata_with_resource_user_context({}, context)
+
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ assert not resource_access_service.metadata_allows_harness_runtime(metadata)
+
+
+ ("paired_kind", "expected_kind", "should_restore"),
+ [
+ ("personal", "personal", False),
+ ("organization", "organization", False),
+ ("", None, True),
+ ],
+)
+def test_unbound_legacy_deferred_context_cannot_adopt_current_pairing_kind(
+ monkeypatch,
+ tmp_path,
+ paired_kind: str,
+ expected_kind: str | None,
+ should_restore: bool,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_kind = paired_kind
+ config.remote_access.vibe_cloud.instance_id = "paired-instance"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ legacy_metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ restored = resource_access_service.resource_user_context_from_metadata(legacy_metadata)
+
+ assert (restored is not None) is should_restore
+ if restored is not None:
+ assert restored.instance_kind == expected_kind
+
+
+def test_kindless_deferred_context_adopts_matching_validated_pairing(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "paired-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ legacy_metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_id": "paired-instance",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "owner",
+ "vibe_instance_kind": None,
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="paired-instance",
+ instance_kind="personal",
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="paired-instance",
+ instance_kind="personal",
+ generation=started["generation"],
+ )
+ restored = resource_access_service.resource_user_context_from_metadata(legacy_metadata)
+
+ assert restored is not None
+ assert restored.is_personal_instance
+
+
+ ("paired_kind", "access_source", "organization_claims"),
+ [
+ ("personal", "owner", False),
+ ("organization", "organization_group", True),
+ ("organization", "email", False),
+ ],
+)
+def test_migrate_legacy_deferred_contexts_binds_definitions_and_queued_deliveries(
+ monkeypatch,
+ tmp_path,
+ paired_kind: str,
+ access_source: str,
+ organization_claims: bool,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "paired-instance"
+ config.remote_access.vibe_cloud.instance_kind = paired_kind
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ legacy_context = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": access_source,
+ "claims_issued_at": 1_700_000_000,
+ }
+ if organization_claims:
+ legacy_context.update(
+ {
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ "vibe_group_ids": ["group-1"],
+ }
+ )
+ legacy_metadata = {resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: legacy_context}
db = tmp_path / "vibe.sqlite"
run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
engine = create_sqlite_engine(db)
try:
+ assert store.upsert_scheduled_task(
+ {
+ "id": "legacy-task",
+ "name": "legacy task",
+ "message": "run",
+ "schedule_type": "interval",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ )
+ assert store.upsert_watch(
+ {
+ "id": "legacy-watch",
+ "name": "legacy watch",
+ "message": "watch",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ )
+ assert store.enqueue_definition_run(
+ {
+ "id": "run-1",
+ "definition_id": "legacy-task",
+ "run_type": "scheduled",
+ "source_kind": "scheduler",
+ "prompt": "run",
+ "message": "run",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ ) is not None
with engine.begin() as connection:
- with pytest.raises(resource_access_service.ResourceAccessError, match="invalid_resource_acl_intent"):
- resource_access_service.ensure_resource_policy(
- connection,
- resource_kind="agent",
- resource_id="personal-agent",
- organization_id=None,
- owner_user_id="owner-1",
- access_level="public",
+ connection.execute(
+ agent_sessions.insert().values(
+ id="session-1",
+ scope_id=None,
+ agent_id=None,
+ agent_name="default",
+ agent_backend="opencode",
+ agent_variant="default",
+ model=None,
+ reasoning_effort=None,
+ session_anchor="anchor-1",
+ workdir=None,
+ native_session_id="native-1",
+ title=None,
+ status="active",
+ visibility="foreground",
+ pinned=0,
+ agent_status="idle",
+ composer_draft_text=None,
+ composer_draft_updated_at=None,
+ metadata_json="{}",
+ created_at="2026-08-20T00:00:00Z",
+ updated_at="2026-08-20T00:00:00Z",
+ last_active_at=None,
+ )
+ )
+ enqueue_queued(
+ connection,
+ scope_id=None,
+ session_id="session-1",
+ text="queued",
+ metadata=legacy_metadata,
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ _seed_ready_binding(connection, instance_id="paired-instance", instance_kind=paired_kind)
+ counts = _run_sqlite_data_migrations(connection)
+ assert _migration_counts(counts) == {
+ "legacy_deferred_definitions": 2,
+ "legacy_deferred_runs": 1,
+ "legacy_deferred_deliveries": 1,
+ }
+
+ definition_rows = connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.id.in_(("legacy-task", "legacy-watch"))
+ )
+ ).scalars()
+ for raw_metadata in definition_rows:
+ metadata = json.loads(raw_metadata)
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert snapshot["vibe_instance_id"] == "paired-instance"
+ assert snapshot["vibe_instance_kind"] == paired_kind
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="paired-instance",
+ instance_kind=paired_kind,
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="paired-instance",
+ instance_kind=paired_kind,
+ generation=started["generation"],
+ )
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is not None
+
+ run_metadata = connection.execute(
+ select(agent_runs.c.metadata_json).where(agent_runs.c.definition_id == "legacy-task")
+ ).scalar_one()
+ run_snapshot = json.loads(run_metadata)[
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY
+ ]
+ assert run_snapshot["vibe_instance_id"] == "paired-instance"
+ assert run_snapshot["vibe_instance_kind"] == paired_kind
+
+ delivery = connection.execute(
+ select(message_deliveries.c.snapshot_json, message_deliveries.c.snapshot_sha256).where(
+ message_deliveries.c.session_id == "session-1"
+ )
+ ).mappings().one()
+ snapshot = json.loads(delivery["snapshot_json"])
+ metadata = json.loads(snapshot["metadata_json"])
+ assert metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY][
+ "vibe_instance_id"
+ ] == "paired-instance"
+ assert metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY][
+ "vibe_instance_kind"
+ ] == paired_kind
+ assert delivery["snapshot_sha256"] == hashlib.sha256(
+ delivery["snapshot_json"].encode("utf-8")
+ ).hexdigest()
+
+ assert _migration_counts(_run_sqlite_data_migrations(
+ connection
+ )) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_legacy_migration_keeps_opposite_instance_semantics_unbound(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "personal-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+ legacy_metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "organization-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "organization_group",
+ "vibe_organization_id": "org-1",
+ "vibe_organization_member_id": "member-1",
+ "vibe_organization_role": "member",
+ }
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ assert store.upsert_scheduled_task(
+ {
+ "id": "organization-task",
+ "name": "organization task",
+ "message": "run",
+ "schedule_type": "interval",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ raw_metadata = connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.id == "organization-task"
+ )
+ ).scalar_one()
+ metadata = json.loads(raw_metadata)
+ assert "vibe_instance_id" not in metadata[
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY
+ ]
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_legacy_migration_does_not_bind_after_later_pairing(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = False
+ config.save()
+ legacy_metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "owner",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ assert store.upsert_scheduled_task(
+ {
+ "id": "legacy-task",
+ "name": "legacy task",
+ "message": "run",
+ "schedule_type": "interval",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ assert connection.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key
+ == resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY
+ )
+ ).scalar_one_or_none()
+
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "later-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ raw_metadata = connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.id == "legacy-task"
+ )
+ ).scalar_one()
+ metadata = json.loads(raw_metadata)
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert "vibe_instance_id" not in snapshot
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_legacy_migration_retries_when_same_pairing_kind_is_backfilled(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "same-instance"
+ config.remote_access.vibe_cloud.instance_kind = ""
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+ legacy_metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ assert store.upsert_scheduled_task(
+ {
+ "id": "legacy-task",
+ "name": "legacy task",
+ "message": "run",
+ "schedule_type": "interval",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.save()
+
+ with engine.begin() as connection:
+ _seed_ready_binding(connection, instance_id="same-instance", instance_kind="personal")
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 1,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ raw_metadata = connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.id == "legacy-task"
+ )
+ ).scalar_one()
+ snapshot = json.loads(raw_metadata)[
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY
+ ]
+ assert snapshot["vibe_instance_id"] == "same-instance"
+ assert snapshot["vibe_instance_kind"] == "personal"
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_legacy_migration_preserves_instance_id_while_pairing_is_partial(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "same-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = ""
+ config.save()
+ legacy_metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ assert store.upsert_scheduled_task(
+ {
+ "id": "legacy-task",
+ "name": "legacy task",
+ "message": "run",
+ "schedule_type": "interval",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": legacy_metadata,
+ }
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ marker = json.loads(
+ connection.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key
+ == resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY
+ )
+ ).scalar_one()
+ )
+ assert marker["state"] == "pending"
+ assert marker["instance_id"] == "same-instance"
+
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ with engine.begin() as connection:
+ _seed_ready_binding(connection, instance_id="same-instance", instance_kind="personal")
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ "legacy_deferred_definitions": 1,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ raw_metadata = connection.execute(
+ select(run_definitions.c.metadata_json).where(
+ run_definitions.c.id == "legacy-task"
+ )
+ ).scalar_one()
+ snapshot = json.loads(raw_metadata)[
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY
+ ]
+ assert snapshot["vibe_instance_id"] == "same-instance"
+ assert snapshot["vibe_instance_kind"] == "personal"
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_typed_binding_reader_preserves_partial_identity_and_does_not_latch_read_failure(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.instance_id = "same-instance"
+ cloud.instance_kind = "personal"
+ cloud.instance_secret = ""
+ config.save()
+
+ partial = resource_access_service._configured_resource_state()
+ assert partial.status == resource_access_service.RESOURCE_BINDING_STATE_PARTIAL
+ assert partial.instance_id == "same-instance"
+ assert partial.instance_kind == "personal"
+
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ marker = {
+ "schema_version": 2,
+ "state": "pending",
+ "instance_id": "same-instance",
+ "updated_at": "before-read-failure",
+ }
+ try:
+ with engine.begin() as connection:
+ connection.execute(
+ state_meta.insert().values(
+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,
+ value_json=json.dumps(marker),
+ updated_at="before-read-failure",
+ )
+ )
+
+ monkeypatch.setattr(
+ V2Config,
+ "load",
+ classmethod(lambda cls, *args, **kwargs: (_ for _ in ()).throw(OSError("temporary read"))),
+ )
+ unavailable = resource_access_service._configured_resource_state()
+ assert unavailable.status == resource_access_service.RESOURCE_BINDING_STATE_UNAVAILABLE
+
+ with engine.begin() as connection:
+ assert _migration_counts(resource_access_service.migrate_legacy_deferred_resource_contexts(connection)) == {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+ }
+ stored = connection.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key == resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY
)
+ ).scalar_one()
+ assert json.loads(stored) == marker
finally:
engine.dispose()
+
+
+_EMPTY_MIGRATION_COUNTS = {
+ "legacy_deferred_definitions": 0,
+ "legacy_deferred_runs": 0,
+ "legacy_deferred_deliveries": 0,
+}
+
+
+def _migration_counts(result: dict) -> dict[str, int]:
+ """Numeric migration counts, ignoring the typed binding-status field."""
+
+ return {
+ key: int(result[key])
+ for key in (
+ "legacy_deferred_definitions",
+ "legacy_deferred_runs",
+ "legacy_deferred_deliveries",
+ )
+ }
+
+
+def _paired_cloud_config(
+ tmp_path,
+ *,
+ enabled: bool = True,
+ instance_id: str = "same-instance",
+ instance_kind: str = "personal",
+ instance_secret: str = "instance-secret",
+) -> V2Config:
+ config = V2Config.default()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = enabled
+ cloud.instance_id = instance_id
+ cloud.instance_kind = instance_kind
+ cloud.instance_secret = instance_secret
+ config.save()
+ return config
+
+
+def _seed_ready_binding(connection, *, instance_id: str, instance_kind: str, generation: int = 1) -> None:
+ """Write a validated ready binding onto THIS connection's database."""
+
+ payload = json.dumps(
+ {
+ "schema_version": 1,
+ "state": "ready",
+ "instance_id": instance_id,
+ "instance_kind": instance_kind,
+ "generation": generation,
+ "updated_at": "1",
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ connection.execute(
+ state_meta.insert().values(
+ key="remote_access.instance_binding.v1",
+ value_json=payload,
+ updated_at="1",
+ )
+ )
+
+
+def _seed_legacy_scheduled_task(store, *, definition_id: str, snapshot: dict) -> None:
+ assert store.upsert_scheduled_task(
+ {
+ "id": definition_id,
+ "name": definition_id,
+ "message": "run",
+ "schedule_type": "interval",
+ "created_at": "2026-08-20T00:00:00Z",
+ "updated_at": "2026-08-20T00:00:00Z",
+ "metadata": {resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: snapshot},
+ }
+ )
+
+
+def _legacy_definition_metadata(connection, definition_id: str) -> dict:
+ raw = connection.execute(
+ select(run_definitions.c.metadata_json).where(run_definitions.c.id == definition_id)
+ ).scalar_one()
+ return json.loads(raw)
+
+
+def _stored_migration_marker(connection) -> str | None:
+ return connection.execute(
+ select(state_meta.c.value_json).where(
+ state_meta.c.key == resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY
+ )
+ ).scalar_one_or_none()
+
+
+def test_partial_pairing_marker_records_configured_instance_without_claiming_a_kind(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """A deferred opportunity keeps its identity but never a guessed kind."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path, instance_secret="")
+
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ marker = json.loads(_stored_migration_marker(connection))
+
+ assert marker["schema_version"] == 2
+ assert marker["state"] == "pending"
+ assert marker["instance_id"] == "same-instance"
+ # A partial pairing cannot prove its kind, so the marker must not
+ # record one and must not look terminal to a later startup.
+ assert "instance_kind" not in marker
+ assert "completed_at" not in marker
+ finally:
+ engine.dispose()
+
+
+def test_credential_repair_on_the_same_pairing_completes_the_deferred_migration(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = _paired_cloud_config(tmp_path, instance_secret="")
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+
+ with engine.begin() as connection:
+ _seed_ready_binding(connection, instance_id="same-instance", instance_kind="personal")
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ **_EMPTY_MIGRATION_COUNTS,
+ "legacy_deferred_definitions": 1,
+ }
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert snapshot["vibe_instance_id"] == "same-instance"
+ assert snapshot["vibe_instance_kind"] == "personal"
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="same-instance",
+ instance_kind="personal",
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="same-instance",
+ instance_kind="personal",
+ generation=started["generation"],
+ )
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is not None
+ completed = json.loads(_stored_migration_marker(connection))
+
+ assert completed["state"] == "completed"
+ assert completed["instance_id"] == "same-instance"
+ assert completed["instance_kind"] == "personal"
+ assert completed["completed_at"]
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ assert json.loads(_stored_migration_marker(connection)) == completed
+ assert (
+ _legacy_definition_metadata(connection, "legacy-task") == metadata
+ )
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_transient_configuration_failure_leaves_the_migration_retryable(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ from storage.importer import _run_sqlite_data_migrations
+
+ real_load = V2Config.load
+ with monkeypatch.context() as unreadable:
+ unreadable.setattr(
+ V2Config,
+ "load",
+ classmethod(
+ lambda cls, *args, **kwargs: (_ for _ in ()).throw(OSError("temporary read"))
+ ),
+ )
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ # No first migration opportunity may be recorded from a read
+ # failure; otherwise the retry below would be fenced out.
+ assert _stored_migration_marker(connection) is None
+
+ assert V2Config.load.__func__ is real_load.__func__
+
+ with engine.begin() as connection:
+ _seed_ready_binding(connection, instance_id="same-instance", instance_kind="personal")
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ **_EMPTY_MIGRATION_COUNTS,
+ "legacy_deferred_definitions": 1,
+ }
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="same-instance",
+ instance_kind="personal",
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="same-instance",
+ instance_kind="personal",
+ generation=started["generation"],
+ )
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is not None
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_unpaired_first_opportunity_cannot_be_adopted_by_a_later_pairing(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = _paired_cloud_config(
+ tmp_path,
+ enabled=False,
+ instance_id="",
+ instance_kind="",
+ instance_secret="",
+ )
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "owner",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ sealed = json.loads(_stored_migration_marker(connection))
+
+ assert sealed["state"] == "sealed_unattributed"
+ assert sealed["instance_id"] is None
+
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.instance_id = "later-instance"
+ cloud.instance_kind = "personal"
+ cloud.instance_secret = "instance-secret"
+ config.save()
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert "vibe_instance_id" not in snapshot
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ assert json.loads(_stored_migration_marker(connection))["state"] == "sealed_unattributed"
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_pending_marker_for_one_instance_cannot_be_adopted_by_another_instance(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = _paired_cloud_config(tmp_path, instance_id="instance-a", instance_secret="")
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ pending = json.loads(_stored_migration_marker(connection))
+ assert pending["state"] == "pending"
+ assert pending["instance_id"] == "instance-a"
+
+ cloud = config.remote_access.vibe_cloud
+ cloud.instance_id = "instance-b"
+ cloud.instance_secret = "instance-secret"
+ config.save()
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ sealed = json.loads(_stored_migration_marker(connection))
+ assert sealed["state"] == "sealed_unattributed"
+ # The original owner stays recorded so no later pairing, including
+ # instance A itself, can reopen the sealed opportunity.
+ assert sealed["instance_id"] == "instance-a"
+
+ cloud.instance_id = "instance-a"
+ config.save()
+
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert "vibe_instance_id" not in snapshot
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ finally:
+ store.close()
+ engine.dispose()
+
+
[email protected]("paired_kind", ["organization", "personal"])
[email protected]("access_source", ["email", "email_domain", "public_instance"])
+def test_shared_access_source_snapshots_migrate_for_either_pairing_kind(
+ monkeypatch,
+ tmp_path,
+ paired_kind: str,
+ access_source: str,
+) -> None:
+ """``email``/``email_domain``/``public_instance`` are kind-agnostic.
+
+ Neither their presence nor the absence of Organization membership claims
+ is instance-kind evidence, so the still-current pairing decides.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path, instance_id="paired-instance", instance_kind=paired_kind)
+ legacy_snapshot = {
+ "sub": "legacy-editor",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": access_source,
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ _seed_ready_binding(connection, instance_id="paired-instance", instance_kind=paired_kind)
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == {
+ **_EMPTY_MIGRATION_COUNTS,
+ "legacy_deferred_definitions": 1,
+ }
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert snapshot["vibe_instance_id"] == "paired-instance"
+ assert snapshot["vibe_instance_kind"] == paired_kind
+ from storage import remote_access_authorization_service as _auth
+
+ started = _auth.begin_instance_binding_transition(
+ instance_id="paired-instance",
+ instance_kind=paired_kind,
+ )
+ _auth.complete_instance_binding_transition(
+ instance_id="paired-instance",
+ instance_kind=paired_kind,
+ generation=started["generation"],
+ )
+ restored = resource_access_service.resource_user_context_from_metadata(metadata)
+ assert restored is not None
+ assert restored.is_personal_instance is (paired_kind == "personal")
+ # Organization membership is never synthesized by the migration.
+ assert "vibe_organization_id" not in snapshot
+ finally:
+ store.close()
+ engine.dispose()
+
+
+ ("marker_json", "expected_state", "expect_marker_preserved"),
+ [
+ pytest.param(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "state": "completed",
+ "instance_id": None,
+ "completed_at": "2026-08-19T00:00:00Z",
+ "updated_at": "2026-08-19T00:00:00Z",
+ }
+ ),
+ "sealed_unattributed",
+ True,
+ id="released_completed_without_instance",
+ ),
+ pytest.param(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "state": "completed",
+ "instance_id": "same-instance",
+ "completed_at": "2026-08-19T00:00:00Z",
+ "updated_at": "2026-08-19T00:00:00Z",
+ }
+ ),
+ "completed",
+ True,
+ id="released_completed_for_current_instance",
+ ),
+ pytest.param(
+ json.dumps({"instance_id": "same-instance", "completed_at": "2026-08-19T00:00:00Z"}),
+ "completed",
+ True,
+ id="released_marker_without_state_field",
+ ),
+ pytest.param(
+ json.dumps({"instance_id": None}),
+ "sealed_unattributed",
+ False,
+ id="released_marker_without_state_or_instance",
+ ),
+ pytest.param(
+ json.dumps({"state": "pending", "instance_id": " "}),
+ None,
+ True,
+ id="blank_instance_id",
+ ),
+ pytest.param(
+ json.dumps({"state": "sealed_unattributed", "instance_id": "same-instance"}),
+ "sealed_unattributed",
+ True,
+ id="sealed_for_current_instance",
+ ),
+ pytest.param("not-json", None, True, id="corrupt_marker"),
+ pytest.param(json.dumps(["completed"]), None, True, id="non_object_marker"),
+ ],
+)
+def test_released_migration_marker_shapes_stay_idempotent_and_fail_closed(
+ monkeypatch,
+ tmp_path,
+ marker_json: str,
+ expected_state: str | None,
+ expect_marker_preserved: bool,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ with engine.begin() as connection:
+ connection.execute(
+ state_meta.insert().values(
+ key=resource_access_service.LEGACY_DEFERRED_CONTEXT_MIGRATION_KEY,
+ value_json=marker_json,
+ updated_at="2026-08-19T00:00:00Z",
+ )
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ for _ in range(2):
+ with engine.begin() as connection:
+ assert _migration_counts(_run_sqlite_data_migrations(connection)) == _EMPTY_MIGRATION_COUNTS
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert "vibe_instance_id" not in snapshot
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+ stored = _stored_migration_marker(connection)
+ if expect_marker_preserved:
+ # A terminal or unreadable marker is never rewritten, so
+ # repeated startups cannot churn the released shape.
+ assert stored == marker_json
+ else:
+ assert json.loads(stored)["state"] == expected_state
+ finally:
+ store.close()
+ engine.dispose()
+
+
+def test_personal_resources_cannot_use_organization_access_levels(tmp_path) -> None:
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ with engine.begin() as connection:
+ with pytest.raises(resource_access_service.ResourceAccessError, match="invalid_resource_acl_intent"):
+ resource_access_service.ensure_resource_policy(
+ connection,
+ resource_kind="agent",
+ resource_id="personal-agent",
+ organization_id=None,
+ owner_user_id="owner-1",
+ access_level="public",
+ )
+ finally:
+ engine.dispose()
+
+
+def test_migration_defers_to_a_disagreeing_durable_binding_row(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """A binding row from a peer's reclassification outranks the config read.
+
+ Regression: PR #1606 round 1 — the migration running from a bare
+ ``ensure_sqlite_state()`` must not bind ambiguous snapshots to a config
+ kind that the durable binding row does not (yet) agree with.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path, instance_kind="personal")
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ binding_row = json.dumps(
+ {
+ "schema_version": 1,
+ "state": "ready",
+ "instance_id": "same-instance",
+ "instance_kind": "organization",
+ "generation": 3,
+ "updated_at": "1700000000",
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ )
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ connection.execute(
+ state_meta.insert().values(
+ key="remote_access.instance_binding.v1",
+ value_json=binding_row,
+ updated_at="1700000000",
+ )
+ )
+ counts = _migration_counts(_run_sqlite_data_migrations(connection))
+ marker = json.loads(_stored_migration_marker(connection))
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+
+ # No snapshot was bound and the opportunity stays retriable.
+ assert counts == _EMPTY_MIGRATION_COUNTS
+ assert marker["state"] == "pending"
+ assert marker["instance_id"] == "same-instance"
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert "vibe_instance_kind" not in snapshot
+ finally:
+ engine.dispose()
+
+
+def test_recovered_config_is_unavailable_and_does_not_seal_legacy_snapshots(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r3: a recovered/defaulted V2Config.load() (broken
+ JSON, load_warnings set) is UNAVAILABLE, never authoritative UNPAIRED.
+ Repairing the config later must still be able to migrate the snapshots.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = _paired_cloud_config(tmp_path)
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+
+ class Recovered:
+ load_warnings = ("invalid json recovered to defaults",)
+ class remote_access:
+ class vibe_cloud:
+ instance_id = ""
+ instance_kind = ""
+ enabled = False
+ @staticmethod
+ def runtime_credentials():
+ return None
+
+ monkeypatch.setattr(V2Config, "load", staticmethod(lambda: Recovered()))
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ counts = _migration_counts(_run_sqlite_data_migrations(connection))
+ marker = _stored_migration_marker(connection)
+
+ assert _migration_counts(counts) == _EMPTY_MIGRATION_COUNTS
+ # No terminal seal was written.
+ if marker is not None:
+ payload = json.loads(marker)
+ assert payload.get("state") != "sealed_unattributed"
+
+ # Repair: restore a real pairing and migrate.
+ monkeypatch.undo()
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ with engine.begin() as connection:
+ _seed_ready_binding(connection, instance_id="same-instance", instance_kind="personal")
+ repaired = _migration_counts(_run_sqlite_data_migrations(connection))
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert snapshot["vibe_instance_id"] == "same-instance"
+ assert snapshot["vibe_instance_kind"] == "personal"
+ assert repaired.get("legacy_deferred_definitions", 0) >= 1
+ finally:
+ engine.dispose()
+
+
+def test_gate_under_writer_lock_does_not_open_a_second_write_connection(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r3: resource_user_context_from_metadata is called
+ while a queued-delivery transaction already holds reserve_write_lock.
+ Bootstrap must not open a second write connection (it would time out
+ and permanently retire the delivery as unauthorized).
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ from storage.agent_session_rows import reserve_write_lock
+
+ metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_instance_id": "same-instance",
+ "vibe_instance_kind": "personal",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ with engine.begin() as conn:
+ reserve_write_lock(conn)
+ # Absent binding row + known kind: the gate must fail closed
+ # WITHOUT opening a second writer, and without raising.
+ context = resource_access_service.resource_user_context_from_metadata(metadata)
+ # Fail-closed is acceptable; a timeout / deadlock is not.
+ assert context is None or context.instance_id == "same-instance"
+ finally:
+ engine.dispose()
+
+
+def test_typed_reader_from_sqlite_migration_does_not_persist_config(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r4: the typed reader used under an open SQLite
+ writer must not persist on-load config migrations (that would invert
+ C2 lock order against a peer holding the config lock).
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ calls = {"persist": 0}
+ real_load = V2Config.load
+
+ def load_counting(*args, **kwargs):
+ persist = kwargs.get("persist_migrations", True)
+ if persist:
+ calls["persist"] += 1
+ return real_load(*args, **kwargs)
+
+ monkeypatch.setattr(V2Config, "load", staticmethod(load_counting))
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ _run_sqlite_data_migrations(connection)
+ assert calls["persist"] == 0
+ finally:
+ engine.dispose()
+
+
+def test_terminal_delivery_snapshots_are_left_byte_identical(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r4: accepted/retired delivery snapshots are the
+ immutable submitted Message candidate and must not be rewritten.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ engine = create_sqlite_engine(db)
+ try:
+ from storage.importer import _run_sqlite_data_migrations
+ from storage.models import agent_sessions, message_deliveries, scopes
+ import hashlib
+
+ snapshot = {
+ "metadata_json": json.dumps(
+ {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ )
+ }
+ snapshot_json = json.dumps(snapshot, sort_keys=True, separators=(",", ":"))
+ snapshot_sha = hashlib.sha256(snapshot_json.encode("utf-8")).hexdigest()
+ with engine.begin() as connection:
+ connection.execute(
+ scopes.insert().values(
+ id="scope_term",
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_term",
+ is_private=0,
+ supports_threads=0,
+ metadata_json="{}",
+ first_seen_at="now",
+ last_seen_at="now",
+ updated_at="now",
+ )
+ )
+ connection.execute(
+ agent_sessions.insert().values(
+ id="sess_term",
+ scope_id="scope_term",
+ title="t",
+ status="idle",
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_term",
+ native_session_id="native_term",
+ created_at="now",
+ updated_at="now",
+ last_active_at="now",
+ metadata_json="{}",
+ )
+ )
+ connection.execute(
+ message_deliveries.insert().values(
+ id="del_retired",
+ session_id="sess_term",
+ priority="p3",
+ state="retired",
+ snapshot_json=snapshot_json,
+ snapshot_sha256=snapshot_sha,
+ dispatch_sha256=snapshot_sha,
+ submitted_at="now",
+ updated_at="now",
+ )
+ )
+ _run_sqlite_data_migrations(connection)
+ rows = {
+ row["id"]: row
+ for row in connection.execute(
+ select(
+ message_deliveries.c.id,
+ message_deliveries.c.snapshot_json,
+ message_deliveries.c.snapshot_sha256,
+ )
+ ).mappings()
+ }
+ assert rows["del_retired"]["snapshot_json"] == snapshot_json
+ assert rows["del_retired"]["snapshot_sha256"] == snapshot_sha
+ finally:
+ engine.dispose()
+
+
+def test_absent_binding_fails_closed_for_deferred_personal_context(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r5: a known-kind pairing with no durable binding
+ row must not project a Personal context for deferred execution.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "personal-instance"
+ config.remote_access.vibe_cloud.instance_kind = "personal"
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.save()
+ context = resource_access_service.ResourceUserContext(
+ subject="personal-user",
+ instance_id="personal-instance",
+ instance_role="editor",
+ instance_access_source="owner",
+ instance_kind="personal",
+ is_remote=True,
+ )
+ metadata = resource_access_service.metadata_with_resource_user_context({}, context)
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+
+
+def test_migration_stays_pending_without_a_validated_binding_row(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r5: known-kind config + absent binding row must
+ not complete the deferred-context migration or relabel snapshots.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ cloud = config.remote_access.vibe_cloud
+ cloud.enabled = True
+ cloud.instance_id = "same-instance"
+ cloud.instance_kind = "personal"
+ cloud.instance_secret = "instance-secret"
+ config.save()
+ legacy_snapshot = {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ db = tmp_path / "vibe.sqlite"
+ run_migrations(db)
+ store = SQLiteBackgroundTaskStore(db)
+ engine = create_sqlite_engine(db)
+ try:
+ _seed_legacy_scheduled_task(store, definition_id="legacy-task", snapshot=legacy_snapshot)
+ from storage.importer import _run_sqlite_data_migrations
+
+ with engine.begin() as connection:
+ counts = _migration_counts(_run_sqlite_data_migrations(connection))
+ marker = json.loads(_stored_migration_marker(connection))
+ metadata = _legacy_definition_metadata(connection, "legacy-task")
+ assert counts == _EMPTY_MIGRATION_COUNTS
+ assert marker["state"] == "pending"
+ snapshot = metadata[resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY]
+ assert "vibe_instance_kind" not in snapshot
+ finally:
+ engine.dispose()
+
+
+def test_unsupported_deferred_snapshot_kind_is_rejected(monkeypatch, tmp_path) -> None:
+ """Regression PR #1606 r5: a present-but-unrecognized kind is not a
+ no-kind legacy snapshot for deferred execution either.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+ metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "vibe_instance_id": "same-instance",
+ "vibe_instance_kind": "enterprise",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+
+
+def test_unrelated_section_load_warning_does_not_make_pairing_unavailable(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """Regression PR #1606 r5: Model Hub recovery warnings must not classify
+ an intact Vibe Cloud pairing as UNAVAILABLE.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ _paired_cloud_config(tmp_path)
+
+ class IntactPairing:
+ load_warnings = ("Recovered invalid config section 'model_hub.sources.vendor': bad",)
+ class remote_access:
+ class vibe_cloud:
+ enabled = True
+ instance_id = "same-instance"
+ instance_kind = "personal"
+ instance_secret = "instance-secret"
+ @staticmethod
+ def runtime_credentials():
+ return ("https://backend.test", "same-instance", "instance-secret")
+
+ monkeypatch.setattr(V2Config, "load", staticmethod(lambda **kwargs: IntactPairing()))
+ state = resource_access_service._configured_resource_state()
+ assert state.status == "ready"
+ assert state.instance_id == "same-instance"
+ assert state.instance_kind == "personal"
+
+
+def test_kindless_deferred_snapshot_fails_closed_when_pairing_is_unpaired(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ """P2 a0D_l: kindless snapshot + unpaired/unavailable config → no Editor context.
+
+ The valid legacy no-kind PAIRING path (PARTIAL, runtime-ready, kind not
+ yet backfilled) still returns the original context.
+ """
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path / "home"))
+ config = V2Config.default()
+ config.remote_access.vibe_cloud.enabled = False
+ config.remote_access.vibe_cloud.instance_id = ""
+ config.save()
+ metadata = {
+ resource_access_service.RESOURCE_USER_CONTEXT_METADATA_KEY: {
+ "sub": "legacy-user",
+ "vibe_instance_role": "editor",
+ "vibe_instance_access_source": "email",
+ "claims_issued_at": 1_700_000_000,
+ }
+ }
+ assert resource_access_service.resource_user_context_from_metadata(metadata) is None
+
+ # Valid legacy no-kind pairing: runtime-ready, kind not yet backfilled.
+ config.remote_access.vibe_cloud.enabled = True
+ config.remote_access.vibe_cloud.instance_id = "same-instance"
+ config.remote_access.vibe_cloud.instance_kind = ""
+ config.remote_access.vibe_cloud.instance_secret = "instance-secret"
+ config.remote_access.vibe_cloud.backend_url = "https://backend.test"
+ config.save()
+ restored = resource_access_service.resource_user_context_from_metadata(metadata)
+ assert restored is not None
+ assert restored.instance_role == "editor"
+ assert restored.instance_kind is None
diff --git a/tests/test_resource_acl_agents.py b/tests/test_resource_acl_agents.py
index 5ef317ee3..9efb0228b 100644
--- a/tests/test_resource_acl_agents.py
+++ b/tests/test_resource_acl_agents.py
@@ -58,6 +58,9 @@ def _organization_cookie(
"vibe_instance_id": "inst_123",
"vibe_instance_role": instance_role,
"vibe_instance_access_source": "organization_group",
+ "vibe_instance_authorization_revision": (
+ remote_access.current_authorization_revision(config) or 0
+ ),
"vibe_organization_id": "org-1",
"vibe_organization_member_id": f"member-{subject}",
"vibe_organization_role": organization_role,
@@ -166,7 +169,7 @@ def test_agent_removal_deletes_resource_policy_and_groups(monkeypatch, tmp_path)
def test_owner_can_create_agent_without_a_trusted_local_identity(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
client = app.test_client()
client.set_cookie(
remote_access.SESSION_COOKIE_NAME,
@@ -419,7 +422,7 @@ def test_missing_agent_selector_fails_closed_for_editor_only(monkeypatch, tmp_pa
def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
store = VibeAgentStore()
try:
agent = store.create(
@@ -467,7 +470,7 @@ def test_active_org_agent_detail_uses_full_runtime_projection(monkeypatch, tmp_p
def test_editor_agent_selection_and_harness_bindings_follow_acl(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- config = _save_config(tmp_path)
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
store, agents = _seed_agents_with_policies()
private_agent = agents["private"]
store.set_default_agent_name(private_agent.name)
@@ -776,7 +779,7 @@ def test_project_runtime_uses_acls_while_harness_remains_editor_wide(monkeypatch
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
ensure_sqlite_state()
- config = _save_config(tmp_path)
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
store, agents = _seed_agents_with_policies()
engine = get_cached_sqlite_engine()
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
diff --git a/tests/test_resource_acl_show_pages.py b/tests/test_resource_acl_show_pages.py
index dde05863d..b57af15b5 100644
--- a/tests/test_resource_acl_show_pages.py
+++ b/tests/test_resource_acl_show_pages.py
@@ -73,6 +73,7 @@ def _paired_config(tmp_path, *, instance_kind: str):
cloud.instance_secret = "device-secret"
cloud.instance_kind = instance_kind
config.save()
+ remote_access._replace_authorization_revision(config, 0)
return config
@@ -887,63 +888,6 @@ def test_show_access_owner_read_and_apply_use_controller_ipc(monkeypatch, tmp_pa
]
-def test_show_access_apply_forwards_group_and_organization_entries(monkeypatch, tmp_path) -> None:
- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
- store = ShowPageStore()
- try:
- store.ensure("ses-access-entries")
- finally:
- store.close()
- calls: list[tuple[str, dict]] = []
- request_payload = {
- "page_id": "ses-access-entries",
- "expected_revision": 0,
- "target_access_mode": "limited",
- "target_share_id": "stable-link",
- "target_entries": [
- {"kind": "group", "value": "group-7"},
- {"kind": "organization", "value": "org-1"},
- ],
- }
-
- async def _apply(payload):
- calls.append(("apply", payload))
- return {
- "status_code": 200,
- "body": {
- "status": "applied",
- "show_access": {
- **_show_access_payload("ses-access-entries", revision=1),
- "access_mode": "limited",
- "entries": [
- {
- "kind": "group",
- "value": "group-7",
- "organization_id": "org-1",
- },
- {
- "kind": "organization",
- "value": "org-1",
- "organization_id": "org-1",
- },
- ],
- },
- },
- }
-
- monkeypatch.setattr(internal_client, "show_access_apply", _apply)
- client = app.test_client()
- applied = client.post(
- "/api/show-pages/ses-access-entries/access-settings/apply",
- json=request_payload,
- headers=csrf_headers(client),
- )
-
- assert applied.status_code == 200
- assert applied.get_json()["show_access"]["entries"][0]["kind"] == "group"
- assert calls == [("apply", request_payload)]
-
-
def test_show_access_route_identity_mismatch_is_rejected_before_ipc(monkeypatch, tmp_path) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
diff --git a/tests/test_ui_memory_routes.py b/tests/test_ui_memory_routes.py
index 1645e86b8..3ef24c958 100644
--- a/tests/test_ui_memory_routes.py
+++ b/tests/test_ui_memory_routes.py
@@ -490,13 +490,17 @@ def _save_remote_config(tmp_path) -> V2Config:
config = V2Config.load()
cloud = config.remote_access.vibe_cloud
cloud.enabled = True
+ cloud.backend_url = "https://backend.test"
cloud.public_url = "https://alex.avibe.bot"
cloud.client_id = "vr_client_123"
cloud.instance_id = "inst_123"
+ cloud.instance_kind = "organization"
+ cloud.instance_secret = "instance-secret"
cloud.session_secret = "session-secret"
cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"
config.save()
+ remote_access._replace_authorization_revision(config, 0)
return config
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index 72500dd27..c0dcce563 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -9,7 +9,7 @@ from storage.importer import ensure_sqlite_state
from storage.models import agent_sessions, messages
from storage.settings_service import upsert_scope
from vibe import remote_access
-from vibe.authorization import AuthorizationContext
+from vibe.authorization import AuthorizationContext, context_from_session_payload
@pytest.fixture(autouse=True)
@@ -25,6 +25,8 @@ def _remote_authorization_record(
authorization_revision: int | None = None,
instance_access_source: str = "email",
organization: bool = False,
+ instance_kind: str | None = None,
+ instance_id: str | None = "inst-push",
) -> dict:
subject = user_key.removeprefix("remote:")
record = web_push_notifications.web_push_authorization_context_record(
@@ -39,6 +41,8 @@ def _remote_authorization_record(
organization_id="org_1" if organization else None,
organization_member_id="member_1" if organization else None,
organization_role="member" if organization else None,
+ instance_id=instance_id,
+ instance_kind=instance_kind,
is_remote=True,
),
)
@@ -46,6 +50,182 @@ def _remote_authorization_record(
return record
+def test_web_push_authorization_snapshot_preserves_instance_kind() -> None:
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_kind="personal",
+ )
+
+ assert record["vibe_instance_kind"] == "personal"
+ assert context_from_session_payload(record).is_personal_instance
+
+
+def test_kindless_web_push_snapshot_adopts_current_personal_pairing_kind(
+ monkeypatch,
+ tmp_path,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_revision_config(41, instance_kind="personal")
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_id="inst-push",
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert decision.authorized
+ assert decision.context is not None
+ assert decision.context.is_personal_instance
+
+
+def test_unbound_kindless_web_push_snapshot_is_rejected(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _paired_revision_config(41, instance_kind="personal")
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_id=None,
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert decision.reason == (
+ "persisted snapshot lacks a binding to the current paired instance"
+ )
+
+
+def test_unrecognized_web_push_snapshot_kind_is_rejected(tmp_path) -> None:
+ """Regression PR #1606 r4: a present-but-unrecognized kind is not a
+ no-kind legacy snapshot and must not fall through to Personal policy.
+ """
+
+ config = _paired_revision_config(41, instance_kind="personal")
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_id="inst-push",
+ )
+ record["vibe_instance_kind"] = "something-else"
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert decision.reason == "persisted snapshot instance kind is unrecognized"
+
+
+def test_kind_specific_web_push_snapshot_requires_known_current_pairing_kind(tmp_path) -> None:
+ config = _paired_revision_config(41, instance_kind="")
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_kind="personal",
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
+ assert decision.reason == "current pairing instance kind is unavailable"
+
+
+def test_web_push_rejects_remote_snapshot_when_pairing_config_is_absent() -> None:
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_kind="personal",
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ None,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
+ assert decision.reason == (
+ "paired configuration is unavailable; instance binding cannot be validated"
+ )
+
+
+def test_personal_web_push_requires_runtime_valid_pairing(tmp_path) -> None:
+ config = _paired_revision_config(41, instance_kind="personal")
+ config.remote_access.vibe_cloud.instance_secret = ""
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_kind="personal",
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
+ assert decision.reason == "current pairing lacks complete runtime credentials"
+
+
+def test_web_push_does_not_use_personal_bypass_while_binding_is_reconciling(tmp_path) -> None:
+ config = _paired_revision_config(41, instance_kind="personal")
+ from storage import remote_access_authorization_service
+
+ remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst-push",
+ instance_kind="personal",
+ )
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_kind="personal",
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
+ assert "not ready" in (decision.reason or "")
+
+
+def test_web_push_snapshot_with_stale_instance_kind_is_rejected(tmp_path) -> None:
+ config = _paired_revision_config(41, instance_kind="organization")
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_kind="personal",
+ )
+
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+
+ assert not decision.authorized
+ assert decision.disposition == web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED
+ assert decision.reason == (
+ "persisted snapshot instance kind differs from the current pairing"
+ )
+
+
def _paired_revision_config(revision: int, *, instance_kind: str = ""):
from core.services.settings import default_config
@@ -329,6 +509,7 @@ def test_web_push_owner_uses_transcript_acceptance_order(monkeypatch, tmp_path):
def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-06-04T00:00:00Z"
@@ -473,6 +654,7 @@ def test_send_to_enabled_subscriptions_rejects_stale_instance_authorization_revi
- remote_access.SESSION_AUTHORIZATION_REFRESH_SECONDS
- 3600,
authorization_revision=41,
+ instance_id="inst-push",
is_remote=True,
),
)
@@ -595,6 +777,7 @@ def test_personal_policy_ignores_revision_state_and_refresh_cutoff(monkeypatch,
"remote:user-a",
claims_age_seconds=remote_access.SESSION_AUTHORIZATION_REFRESH_SECONDS + 3600,
authorization_revision=41,
+ instance_kind="personal",
)
with engine.begin() as conn:
@@ -1029,6 +1212,7 @@ def test_in_flight_authorization_sync_wait_recovers_watermark(monkeypatch, tmp_p
def test_merged_delivery_reports_provider_failure_per_owner(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-08-14T00:00:00Z"
@@ -1145,6 +1329,7 @@ def test_persisted_ring_survives_delivery_process_restart(monkeypatch, tmp_path)
def test_merged_owner_without_endpoint_reports_no_subscription(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-08-15T00:00:00Z"
@@ -1302,7 +1487,7 @@ def test_unsigned_organization_snapshot_without_config_is_rejected(monkeypatch,
assert sends == []
recent = web_push_notifications.recent_delivery_dispositions()
- assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
assert recent[0]["owners"]["remote:user-a"]["policy"] == "organization"
engine.dispose()
@@ -1602,7 +1787,7 @@ def test_organization_signed_snapshot_without_config_records_unavailable(monkeyp
assert sends == []
recent = web_push_notifications.recent_delivery_dispositions()
- assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_REVISION_UNAVAILABLE
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE
assert recent[0]["owners"]["remote:user-a"]["policy"] == "organization"
engine.dispose()
@@ -2034,6 +2219,7 @@ def test_organization_unsigned_record_reports_refresh_required(monkeypatch, tmp_
def test_authorized_owner_without_subscription_records_no_subscription(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-08-04T00:00:00Z"
@@ -2125,6 +2311,7 @@ def test_authorized_owner_without_subscription_records_no_subscription(monkeypat
def test_send_to_enabled_subscriptions_rechecks_restricted_project_access(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="organization")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-06-04T00:00:00Z"
@@ -2133,6 +2320,11 @@ def test_send_to_enabled_subscriptions_rechecks_restricted_project_access(monkey
subject="user-a",
instance_access_source="email",
+ organization_id="org_1",
+ organization_member_id="member_1",
+ organization_role="member",
+ instance_kind="organization",
+ authorization_revision=41,
claims_issued_at=int(web_push_notifications.time.time()),
is_remote=True,
)
@@ -2319,9 +2511,164 @@ def test_send_to_enabled_subscriptions_rechecks_restricted_project_access(monkey
assert [send[0]["endpoint"] for send in sends] == ["https://push.example.test/a"]
+def test_send_to_enabled_subscriptions_personal_editor_ignores_restricted_project_acl(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-06-04T00:00:00Z"
+ context = AuthorizationContext(
+ instance_role="editor",
+ subject="personal-user",
+ instance_access_source="email",
+ instance_kind="personal",
+ claims_issued_at=int(web_push_notifications.time.time()),
+ is_remote=True,
+ )
+ authorization_record = web_push_notifications.web_push_authorization_context_record(
+ "remote:personal-user",
+ context,
+ )
+ assert authorization_record is not None
+
+ with engine.begin() as conn:
+ primary_scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_personal_acl",
+ now=now,
+ )
+ other_scope_id = upsert_scope(
+ conn,
+ platform="avibe",
+ scope_type="project",
+ native_id="proj_push_personal_other",
+ now=now,
+ )
+ for session_id, scope_id in (
+ ("ses_push_personal_acl", primary_scope_id),
+ ("ses_push_personal_other", other_scope_id),
+ ):
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor=session_id,
+ native_session_id="",
+ title=session_id,
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ for project_id in ("proj_push_personal_acl", "proj_push_personal_other"):
+ assert project_access_service.apply_project_access_intent(
+ conn,
+ {
+ "project_id": project_id,
+ "revision": 1,
+ "mode": "restricted",
+ "bindings": [
+ {
+ "principal_kind": "email",
+ "principal_value": "[email protected]",
+ "access_role": "editor",
+ }
+ ],
+ },
+ ).outcome == "applied"
+ messages_service.append(
+ conn,
+ scope_id=primary_scope_id,
+ session_id="ses_push_personal_acl",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:personal-user",
+ metadata={
+ "_web_push_user_key": "remote:personal-user",
+ "_web_push_authorization_contexts": [authorization_record],
+ },
+ message_type="user",
+ text="Please finish",
+ )
+ primary_message = messages_service.append(
+ conn,
+ scope_id=primary_scope_id,
+ session_id="ses_push_personal_acl",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done",
+ )
+ messages_service.append(
+ conn,
+ scope_id=other_scope_id,
+ session_id="ses_push_personal_other",
+ platform="avibe",
+ author="user",
+ source="user",
+ author_id="remote:personal-user",
+ message_type="user",
+ text="Please finish another project",
+ )
+ messages_service.append(
+ conn,
+ scope_id=other_scope_id,
+ session_id="ses_push_personal_other",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="Done another",
+ )
+ web_push_service.upsert_subscription(
+ conn,
+ user_key="remote:personal-user",
+ payload={
+ "endpoint": "https://push.example.test/personal-acl",
+ "keys": {"p256dh": "personal-key", "auth": "personal-auth"},
+ },
+ )
+
+ sends = []
+ monkeypatch.setattr(web_push_notifications.time, "sleep", lambda _seconds: None)
+ monkeypatch.setattr(
+ "core.web_push.send_web_push",
+ lambda *, subscription, payload: sends.append((subscription, payload)),
+ )
+ web_push_notifications._send_to_enabled_subscriptions(
+ {
+ "title": "Personal ACL Push",
+ "body": "Done",
+ "session_id": "ses_push_personal_acl",
+ "message_id": primary_message["id"],
+ }
+ )
+
+ assert [send[0]["endpoint"] for send in sends] == [
+ "https://push.example.test/personal-acl"
+ ]
+ assert [send[1]["badge_count"] for send in sends] == [2]
+ recent = web_push_notifications.recent_delivery_dispositions(user_key="remote:personal-user")
+ assert recent[0]["disposition"] == web_push_notifications.WEB_PUSH_DISPOSITION_SENT
+ engine.dispose()
+
+
def test_send_to_enabled_subscriptions_sets_visible_badge_count(monkeypatch, tmp_path):
"""One Project's badge includes every visible unread session in it."""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-06-04T00:00:00Z"
@@ -2330,6 +2677,7 @@ def test_send_to_enabled_subscriptions_sets_visible_badge_count(monkeypatch, tmp
subject="user-a",
instance_access_source="email",
+ instance_id="inst-push",
claims_issued_at=int(web_push_notifications.time.time()),
is_remote=True,
)
@@ -2483,6 +2831,7 @@ def test_send_to_enabled_subscriptions_rejects_legacy_session_owner(monkeypatch,
def test_send_to_enabled_subscriptions_prefers_message_owner_over_legacy_session(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-06-04T00:00:00Z"
@@ -2557,6 +2906,7 @@ def test_send_to_enabled_subscriptions_prefers_message_owner_over_legacy_session
def test_send_to_enabled_subscriptions_sends_to_merged_prompt_owners(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-06-04T00:00:00Z"
@@ -3016,6 +3366,7 @@ def test_send_to_enabled_subscriptions_skips_local_fallback_when_remote_access_e
def test_send_to_enabled_subscriptions_sends_terminal_error_with_owner(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _paired_revision_config(41, instance_kind="personal")
ensure_sqlite_state()
engine = create_sqlite_engine()
now = "2026-06-04T00:00:00Z"
@@ -3142,3 +3493,47 @@ def test_send_to_enabled_subscriptions_skips_ambiguous_legacy_owner(monkeypatch,
)
assert sends == []
+
+
+def test_web_push_does_not_mix_reconciling_personal_policy_with_ready_org_binding(
+ tmp_path,
+) -> None:
+ """Class 2: one evaluation, one snapshot of (ready, kind, generation)."""
+
+ config = _paired_revision_config(41, instance_kind="organization")
+ record = _remote_authorization_record(
+ "remote:personal-user",
+ instance_id="inst-push",
+ )
+ # Kindless released snapshot: policy would infer Personal if the first
+ # gate saw reconciling. Evaluation must not mix that with a later-ready
+ # Org binding.
+ from storage import remote_access_authorization_service
+
+ started = remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst-push",
+ instance_kind="organization",
+ )
+ remote_access_authorization_service.complete_instance_binding_transition(
+ instance_id="inst-push",
+ instance_kind="organization",
+ generation=started["generation"],
+ )
+ remote_access_authorization_service.begin_instance_binding_transition(
+ instance_id="inst-push",
+ instance_kind="organization",
+ )
+ decision = web_push_notifications._evaluate_record_authorization(
+ config,
+ "remote:personal-user",
+ record,
+ )
+ # Evaluation captured reconciling: must not authorize under Personal
+ # against an Org-configured pairing.
+ assert not decision.authorized
+ assert decision.policy != "personal" or not decision.authorized
+ assert decision.disposition in {
+ web_push_notifications.WEB_PUSH_DISPOSITION_CONFIG_UNAVAILABLE,
+ web_push_notifications.WEB_PUSH_DISPOSITION_AUTHORIZATION_REFRESH_REQUIRED,
+ web_push_notifications.WEB_PUSH_DISPOSITION_REVOKED,
+ }
diff --git a/tests/ui_server_test_helpers.py b/tests/ui_server_test_helpers.py
index 6a677fb30..d41225bb1 100644
--- a/tests/ui_server_test_helpers.py
+++ b/tests/ui_server_test_helpers.py
@@ -21,7 +21,12 @@ def remote_peer() -> dict[str, str]:
return _remote_peer()
-def _save_config(tmp_path):
+def _save_config(
+ tmp_path,
+ *,
+ paired: bool = False,
+ instance_kind: str = "organization",
+):
from config.v2_config import (
AgentsConfig,
PlatformsConfig,
@@ -48,10 +53,21 @@ def _save_config(tmp_path):
cloud.public_url = "https://alex.avibe.bot"
cloud.client_id = "vr_client_123"
cloud.instance_id = "inst_123"
+ cloud.instance_secret = "instance-secret"
cloud.session_secret = "session-secret"
cloud.authorization_endpoint = "https://backend.test/oauth/authorize"
cloud.redirect_uri = "https://alex.avibe.bot/auth/callback"
+ if paired:
+ cloud.backend_url = "https://backend.test"
+ cloud.instance_kind = instance_kind
+ else:
+ cloud.instance_secret = ""
config.save()
+ if paired:
+ # A complete paired fixture also needs the device authorization
+ # watermark; production session cookies must carry it once runtime
+ # credentials exist.
+ remote_access._replace_authorization_revision(config, 0)
return config
@@ -90,6 +106,10 @@ def remote_session_cookie(
"vibe_instance_role": role,
"vibe_instance_access_source": access_source,
}
+ if remote_access._authorization_revision_sync_configured(config):
+ claims["vibe_instance_authorization_revision"] = (
+ remote_access.current_authorization_revision(config) or 0
+ )
if organization_id is not None:
claims["vibe_organization_id"] = organization_id
if organization_member_id is not None:
@@ -98,6 +118,15 @@ def remote_session_cookie(
claims["vibe_organization_role"] = organization_role
if group_ids is not None:
claims["vibe_group_ids"] = group_ids
+ elif remote_access._authorization_revision_sync_configured(config) and (
+ "vibe_instance_authorization_revision" not in claims
+ ):
+ claims = {
+ **claims,
+ "vibe_instance_authorization_revision": (
+ remote_access.current_authorization_revision(config) or 0
+ ),
+ }
return remote_access.make_session_cookie(
config,
email,
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 4a32d8c41..ec39d93aa 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -25,7 +25,33 @@ INSTANCE_ACCESS_SOURCES = frozenset(
}
)
ORGANIZATION_ROLES = frozenset({"owner", "admin", "member"})
+INSTANCE_KINDS = frozenset({"personal", "organization"})
_ROLE_RANK = {"viewer": 1, "editor": 2, "owner": 3}
+
+
+def recognized_instance_kind(value: object) -> str | None:
+ """Return a recognized instance kind, or None for a genuine no-kind snapshot.
+
+ A present-but-unrecognized value (corruption, a future release, a typo)
+ is not a no-kind legacy snapshot. Callers that need fail-closed behavior
+ must distinguish ``None`` (absent/legacy) from an unrecognized string
+ via :func:`instance_kind_is_unsupported`.
+ """
+
+ if not isinstance(value, str):
+ return None
+ cleaned = value.strip()
+ return cleaned if cleaned in INSTANCE_KINDS else None
+
+
+def instance_kind_is_unsupported(value: object) -> bool:
+ """True when a kind field is present but not a known Personal/Organization value."""
+
+ if value is None:
+ return False
+ if not isinstance(value, str):
+ return True
+ return value.strip() not in {"", *INSTANCE_KINDS}
_RESOURCE_USE_MINIMUM_ROLES = {
"agent": "editor",
"skill": "editor",
@@ -77,11 +103,20 @@ class AuthorizationContext:
authorization_revision: int | None = None
show_page_id: str | None = None
is_remote: bool = False
+ instance_kind: str | None = None
@property
def is_instance_owner(self) -> bool:
return self.instance_role == "owner"
+ @property
+ def is_personal_instance(self) -> bool:
+ return self.instance_kind == "personal"
+
+ @property
+ def is_organization_instance(self) -> bool:
+ return self.instance_kind == "organization"
+
@property
def is_active_organization_member(self) -> bool:
return bool(
@@ -226,6 +261,11 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
)
if organization_role not in ORGANIZATION_ROLES:
organization_role = None
+ raw_instance_kind = payload.get("vibe_instance_kind")
+ if instance_kind_is_unsupported(raw_instance_kind):
+ instance_kind = None
+ else:
+ instance_kind = recognized_instance_kind(raw_instance_kind)
return AuthorizationContext(
instance_role=role,
subject=_optional_string(payload.get("sub")),
@@ -254,6 +294,7 @@ def context_from_session_payload(payload: Mapping[str, Any]) -> AuthorizationCon
),
show_page_id=show_page_id,
is_remote=True,
+ instance_kind=instance_kind,
)
@@ -402,9 +443,6 @@ _EDITOR_HTTP_RULES = tuple(
("POST", r"^/api/config$"),
("POST", r"^/api/show/sessions/[^/]+/events$"),
("POST", r"^/api/show/sessions/[^/]+/prewarm$"),
- # Reading one page stays at the role its ensure POST already required, so
- # replacing that POST with this GET changes no caller's authorization
- # outcome. Widening to viewer would be a policy change, not a read.
("GET", r"^/api/show-pages/[^/]+$"),
("POST", r"^/api/show-pages/[^/]+/icon$"),
("POST", r"^/api/show-pages/[^/]+/(?:ensure|availability)$"),
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index fb0cc53bb..54d604743 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -97,17 +97,17 @@ _AUTHORIZATION_REVISION_SYNC_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_POLL_LOCK = threading.Lock()
_AUTHORIZATION_REVISION_POLL_STARTED = False
_AUTHORIZATION_REFRESH_LOCK = threading.Lock()
-_AUTHORIZATION_REFRESH_FAILURES: dict[tuple[str, str, str, str], float] = {}
+_AUTHORIZATION_REFRESH_FAILURES: dict[tuple[str, str, str, str, int], float] = {}
_AUTHORIZATION_REFRESH_RESULTS: dict[
- tuple[str, str, str, str],
+ tuple[str, str, str, str, int],
tuple[float, str, str | None, int | None],
] = {}
_AUTHORIZATION_REFRESH_FLIGHTS: dict[
- tuple[str, str, str, str],
+ tuple[str, str, str, str, int],
tuple[threading.Lock, int],
] = {}
_AUTHORIZATION_BACKGROUND_REFRESH_LOCK = threading.Lock()
-_AUTHORIZATION_BACKGROUND_REFRESHES: set[tuple[str, str, str, str]] = set()
+_AUTHORIZATION_BACKGROUND_REFRESHES: set[tuple[str, str, str, str, int]] = set()
AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS = 5.0
_REVOKED_BROWSER_SESSIONS_LOCK = threading.Lock()
_REVOKED_BROWSER_SESSIONS: dict[str, int] = {}
@@ -1591,17 +1591,35 @@ def report_runtime_status(config: V2Config | None = None, event: str = "heartbea
return {"ok": False, "error": "remote_status_not_configured"}
if urllib.parse.urlsplit(cloud.backend_url).scheme.lower() != "https":
return {"ok": False, "error": "remote_status_backend_url_invalid"}
+ from storage import remote_access_authorization_service
+
+ request_instance_id = str(cloud.instance_id)
+ request_binding_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ )
payload = {
"instance_secret": cloud.instance_secret,
**runtime_status_payload(config, event=event, last_error=last_error),
}
result = _json_request(
- f"{cloud.backend_url.rstrip('/')}/api/v1/instances/{cloud.instance_id}/runtime-status",
+ f"{cloud.backend_url.rstrip('/')}/api/v1/instances/{request_instance_id}/runtime-status",
payload,
timeout=5.0,
)
_replace_active_hostnames(config, result.get("active_hostnames"))
- _persist_instance_kind(cloud.instance_id, result.get("instance_kind"))
+ reported_kind = _normalized_instance_kind(result.get("instance_kind"))
+ if reported_kind is not None:
+ # Capture-before-IO: overlapping heartbeats can arrive out of
+ # order. A late Personal response must CAS-fail against a newer
+ # Organization generation rather than rewrite the live binding.
+ _persist_instance_kind(
+ request_instance_id,
+ reported_kind,
+ reconcile=True,
+ expected_binding_generation=request_binding_generation,
+ )
return {"ok": True, **result}
except Exception as exc:
return {"ok": False, "error": "remote_status_report_failed", "detail": str(exc)}
@@ -1611,20 +1629,232 @@ def _normalized_instance_kind(value: object) -> str | None:
return value if isinstance(value, str) and value in _INSTANCE_KINDS else None
-def _persist_instance_kind(instance_id: str, value: object) -> bool:
+def _run_pending_deferred_context_migration() -> dict[str, int | str]:
+ """Bind or seal released snapshots against the current pairing."""
+
+ from storage.db import get_cached_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.resource_access_service import (
+ RESOURCE_BINDING_STATE_UNAVAILABLE,
+ RESOURCE_BINDING_STATUS_KEY,
+ migrate_legacy_deferred_resource_contexts,
+ )
+
+ ensure_sqlite_state()
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as connection:
+ result = migrate_legacy_deferred_resource_contexts(connection)
+ if result.get(RESOURCE_BINDING_STATUS_KEY) == RESOURCE_BINDING_STATE_UNAVAILABLE:
+ raise RuntimeError("legacy_deferred_context_provenance_unavailable")
+ return result
+
+
+def _runtime_pairing_available(config: V2Config) -> bool:
+ try:
+ return config.remote_access.vibe_cloud.runtime_credentials() is not None
+ except Exception:
+ return False
+
+
+def _known_kind_requires_runtime_pairing(config: V2Config) -> bool:
+ """Require complete device credentials once the server-owned kind is known.
+
+ Legacy pre-kind pairings still use the existing authorization path while
+ they await backfill. They cannot take either Personal or Organization
+ kind-specific bypass; an explicit server-owned kind, however, must never
+ be projected from a degraded pairing.
+ """
+
+ return _normalized_instance_kind(config.remote_access.vibe_cloud.instance_kind) is not None
+
+
+def _is_exact_show_page_grant(
+ identity: Mapping[str, Any],
+ record: Mapping[str, Any] | None = None,
+) -> bool:
+ candidates: list[Mapping[str, Any]] = [identity]
+ if isinstance(record, Mapping):
+ claims = record.get("claims")
+ if isinstance(claims, Mapping):
+ candidates.append(claims)
+ return any(
+ candidate.get("vibe_instance_access_source") == "show_page_email"
+ and isinstance(candidate.get("vibe_show_page_id"), str)
+ and bool(candidate["vibe_show_page_id"].strip())
+ for candidate in candidates
+ )
+
+
+def binding_is_ready(config: V2Config, identity: Mapping[str, Any] | None = None) -> bool:
+ """C3: single gate for every authorization consumer.
+
+ A missing durable row is the fail-open legacy no-kind path. Once a row
+ exists, only ``ready`` for the current pairing admits kind-specific
+ bypass. Exact show_page_email grants are independent of instance kind.
+ """
+
+ if identity is not None:
+ if _is_exact_show_page_grant(identity):
+ return True
+ from storage import remote_access_authorization_service
+
+ instance_id = str(identity.get("instance_id") or config.remote_access.vibe_cloud.instance_id or "")
+ subject = str(identity.get("sub") or "")
+ try:
+ if subject and instance_id:
+ record = remote_access_authorization_service.load_reference_record(
+ reference=str(identity.get("authorization_ref") or ""),
+ instance_id=instance_id,
+ subject=subject,
+ now=int(time.time()),
+ )
+ if record is not None and _is_exact_show_page_grant(identity, record):
+ return True
+ except Exception:
+ pass
+ try:
+ from storage import remote_access_authorization_service
+
+ cloud = config.remote_access.vibe_cloud
+ # bootstrap=True: on the upgrade path a known configured kind with no
+ # durable row earns a validated binding through one real transition
+ # (C2) before any kind-specific bypass is granted.
+ return remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id=str(cloud.instance_id or ""),
+ instance_kind=_normalized_instance_kind(cloud.instance_kind),
+ ensure=False,
+ bootstrap=True,
+ )
+ except Exception:
+ return False
+
+
+def _transition_instance_binding(
+ *,
+ instance_id: str,
+ instance_kind: str | None,
+ previous_instance_id: str | None = None,
+ hold_config_lock: bool = True,
+) -> dict[str, Any]:
+ """One cross-process identity transition (C2). SQLite is initialized first."""
+
+ from storage import remote_access_authorization_service
+
+ return remote_access_authorization_service.reconcile_instance_binding(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ previous_instance_id=previous_instance_id,
+ reconcile=_run_pending_deferred_context_migration,
+ hold_config_lock=hold_config_lock,
+ )
+
+
+def _authorization_binding_epoch() -> int:
+ """Compatibility no-op: durable generation is the only fencing token."""
+
+ return 0
+
+
+def _persist_instance_kind(
+ instance_id: str,
+ value: object,
+ *,
+ reconcile: bool = False,
+ expected_binding_generation: int | None = None,
+ expected_binding_epoch: int | None = None,
+) -> bool | int:
+ """Persist kind + reconcile under one cross-process critical section (C2).
+
+ Lock order is owned by reconcile_instance_binding: SQLite init, then
+ config_file_lock. This function never takes CONFIG_LOCK. The unused
+ ``expected_binding_epoch`` argument exists only so older in-process tests
+ that still pass it keep exercising the durable generation CAS.
+ """
+
+ del expected_binding_epoch
instance_kind = _normalized_instance_kind(value)
if instance_kind is None:
return False
- with CONFIG_LOCK:
+ from storage import remote_access_authorization_service
+ from storage.importer import ensure_sqlite_state
+
+ # C2 lock order: initialize SQLite before taking the config lock, then
+ # keep compare + config-write + transition in one critical section.
+ ensure_sqlite_state()
+ with config_file_lock():
live_config = V2Config.load()
live_cloud = live_config.remote_access.vibe_cloud
- if live_cloud.instance_id != instance_id or live_cloud.instance_kind == instance_kind:
+ if str(live_cloud.instance_id or "") != instance_id:
return False
- api.save_config(
- {"remote_access": {"vibe_cloud": {"instance_kind": instance_kind}}},
- validate_remote_access_network=False,
+ previous_kind = _normalized_instance_kind(live_cloud.instance_kind)
+ current_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
)
- return True
+ if (
+ expected_binding_generation is not None
+ and current_generation > int(expected_binding_generation)
+ ):
+ return False
+ already_ready = remote_access_authorization_service.binding_is_ready_for_pairing(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ ensure=False,
+ )
+ if previous_kind == instance_kind and already_ready:
+ return current_generation
+ if previous_kind != instance_kind:
+ live_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ )
+ if (
+ expected_binding_generation is not None
+ and live_generation > int(expected_binding_generation)
+ ):
+ return False
+ api.save_config(
+ {"remote_access": {"vibe_cloud": {"instance_kind": instance_kind}}},
+ validate_remote_access_network=False,
+ )
+ # Whether the kind was already persisted by a prior attempt or just
+ # saved above, reconcile it now. The transition is what moves the
+ # durable binding to ready.
+ try:
+ transition = _transition_instance_binding(
+ instance_id=instance_id,
+ instance_kind=instance_kind,
+ hold_config_lock=False,
+ )
+ except Exception:
+ logger.warning("Remote instance binding reconciliation failed", exc_info=True)
+ return False
+ if expected_binding_generation is not None:
+ live_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ )
+ try:
+ persisted_generation = int(transition.get("generation"))
+ except (TypeError, ValueError):
+ persisted_generation = live_generation
+ # Our own transition advancing the generation is success; only a
+ # FOREIGN writer moving past our transition is a lost race.
+ if live_generation > persisted_generation:
+ return False
+ if persisted_generation < int(expected_binding_generation):
+ return False
+ if not (transition.get("ok") and (transition.get("ready") or instance_kind is None)):
+ return False
+ try:
+ return int(transition.get("generation"))
+ except (TypeError, ValueError):
+ return remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
def mint_cloud_token(
@@ -4344,6 +4574,31 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
origin_service = origin_service_for_pairing()
except Exception:
origin_service = "http://127.0.0.1:5123"
+ try:
+ previous_instance_id = str(V2Config.load().remote_access.vibe_cloud.instance_id or "")
+ except FileNotFoundError:
+ previous_instance_id = ""
+ except Exception as exc:
+ logger.warning("pre-pair config read failed", exc_info=True)
+ return {
+ "ok": False,
+ "error": "pairing_provenance_unavailable",
+ "detail": str(exc),
+ "pairing": {"ok": False},
+ }
+ # Provenance must be validated BEFORE the one-time redeem. An unavailable
+ # read or failing migration aborts without consuming the key; a genuine
+ # unpaired install seals unattributed snapshots so they cannot be adopted.
+ try:
+ _run_pending_deferred_context_migration()
+ except Exception as exc:
+ logger.warning("legacy deferred context migration before pairing failed", exc_info=True)
+ return {
+ "ok": False,
+ "error": "pairing_provenance_unavailable",
+ "detail": str(exc),
+ "pairing": {"ok": False},
+ }
try:
result = _json_request(
f"{backend.base_url}/api/v1/pairing/redeem",
@@ -4371,40 +4626,85 @@ def pair(pairing_key: str, backend_url: str, device_name: str = "avibe") -> dict
"error": str(origin_update.get("error") or "tunnel_origin_update_failed"),
"pairing": {"ok": False, "origin_service": origin_service},
}
- try:
- previous_instance_id = str(V2Config.load().remote_access.vibe_cloud.instance_id or "")
- except Exception:
- previous_instance_id = ""
- config = api.save_config(
- {
- "remote_access": {
- "provider": "vibe_cloud",
- "vibe_cloud": {
- "enabled": True,
- "backend_url": backend.base_url,
- "instance_id": result["instance_id"],
- "instance_kind": instance_kind or "",
- "client_id": result["client_id"],
- "issuer": result["issuer"],
- "authorization_endpoint": result["authorization_endpoint"],
- "token_endpoint": result["token_endpoint"],
- "jwks_uri": result["jwks_uri"],
- "public_url": result["public_url"],
- "redirect_uri": result["redirect_uri"],
- "tunnel_token": result["tunnel_token"],
- "instance_secret": result["instance_secret"],
- "session_secret": secrets.token_urlsafe(32),
- },
- }
- }
- )
- if previous_instance_id and previous_instance_id != str(result["instance_id"]):
+ # C2: the pairing save and its binding transition form ONE cross-process
+ # critical section, so two concurrent pair() calls cannot interleave
+ # save A / save B / transition B / transition A. SQLite initializes
+ # before the config lock per the canonical lock order.
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ with config_file_lock():
try:
- from storage import remote_access_authorization_service
+ previous_instance_id = str(V2Config.load().remote_access.vibe_cloud.instance_id or "")
+ except Exception:
+ previous_instance_id = ""
+ config = api.save_config(
+ {
+ "remote_access": {
+ "provider": "vibe_cloud",
+ "vibe_cloud": {
+ "enabled": True,
+ "backend_url": backend.base_url,
+ "instance_id": result["instance_id"],
+ "instance_kind": instance_kind or "",
+ "client_id": result["client_id"],
+ "issuer": result["issuer"],
+ "authorization_endpoint": result["authorization_endpoint"],
+ "token_endpoint": result["token_endpoint"],
+ "jwks_uri": result["jwks_uri"],
+ "public_url": result["public_url"],
+ "redirect_uri": result["redirect_uri"],
+ "tunnel_token": result["tunnel_token"],
+ "instance_secret": result["instance_secret"],
+ "session_secret": secrets.token_urlsafe(32),
+ },
+ }
+ }
+ )
+ if previous_instance_id and previous_instance_id != str(result["instance_id"]):
+ try:
+ from storage import remote_access_authorization_service
- remote_access_authorization_service.delete_for_instance(previous_instance_id)
+ remote_access_authorization_service.delete_for_instance(previous_instance_id)
+ except Exception:
+ logger.warning("Old remote authorization cleanup failed after pairing", exc_info=True)
+ # Under the held cross-process lock, save_config's returned config IS
+ # the persisted config; verify it still names the instance this call
+ # redeemed before publishing a binding for it.
+ persisted_instance_id = str(config.remote_access.vibe_cloud.instance_id or "")
+ if persisted_instance_id != str(result["instance_id"]):
+ # The persisted pairing is no longer the one this call redeemed;
+ # do not publish a binding for it.
+ return {
+ **status(config),
+ "ok": False,
+ "error": "pairing_reconciliation_failed",
+ "detail": "persisted_instance_mismatch",
+ "pairing": {"ok": False, "reconciling": True},
+ }
+ try:
+ transition = _transition_instance_binding(
+ instance_id=str(result["instance_id"]),
+ instance_kind=instance_kind,
+ previous_instance_id=previous_instance_id or None,
+ hold_config_lock=False,
+ )
except Exception:
- logger.warning("Old remote authorization cleanup failed after pairing", exc_info=True)
+ logger.warning("Remote instance binding transition failed after pairing", exc_info=True)
+ return {
+ **status(config),
+ "ok": False,
+ "error": "pairing_reconciliation_failed",
+ "pairing": {"ok": False, "reconciling": True},
+ }
+ if not transition.get("ok"):
+ return {
+ **status(config),
+ "ok": False,
+ "error": "pairing_reconciliation_failed",
+ "detail": transition.get("error"),
+ "pairing": {"ok": False, "reconciling": True},
+ }
start_result = start(config)
_report_runtime_status_async(config, event="pair", last_error=start_result.get("error"))
return {**status(config), "ok": True, "pairing": {"ok": True}, "start": start_result}
@@ -4631,10 +4931,28 @@ def _store_scoped_authorization(
claims: Mapping[str, Any],
authorization_state: str,
checked_at: int,
+ instance_kind: str | None = None,
+ expected_binding_generation: int | None = None,
) -> str:
from storage import remote_access_authorization_service
- scope_kind, scope_ref = _authorization_scope(config, claims)
+ stored_claims = dict(claims)
+ persisted_kind = _normalized_instance_kind(instance_kind) or _normalized_instance_kind(
+ config.remote_access.vibe_cloud.instance_kind
+ )
+ if persisted_kind is not None:
+ stored_claims["vibe_instance_kind"] = persisted_kind
+ scope_kind, scope_ref = _authorization_scope(config, stored_claims)
+ if expected_binding_generation is None and scope_kind != "show_page":
+ # Recapturing live generation here is the TOCTOU: a transition can
+ # complete between the caller's persist-kind CAS and this write, and
+ # the recaptured gen would let a stale response resurrect a current
+ # row. Callers that produced claims via network/IO must pass the
+ # generation they captured BEFORE that IO. Local cookie/legacy paths
+ # capture immediately before this call.
+ raise remote_access_authorization_service.InstanceBindingChangedError(
+ "expected_binding_generation_required"
+ )
return remote_access_authorization_service.upsert_scoped(
reference=reference,
instance_id=str(config.remote_access.vibe_cloud.instance_id),
@@ -4643,9 +4961,10 @@ def _store_scoped_authorization(
scope_kind=scope_kind,
scope_ref=scope_ref,
authorization_state=authorization_state,
- claims=claims,
+ claims=stored_claims,
last_checked_at=checked_at,
updated_at=checked_at,
+ expected_binding_generation=expected_binding_generation,
)
@@ -4668,6 +4987,13 @@ def make_session_cookie(
except ValueError as exc:
raise OAuthCodeExchangeError("stale_authorization_revision") from exc
stored_claims = {**validated_claims, "claims_issued_at": issued_at}
+ from storage import remote_access_authorization_service
+
+ request_binding_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ )
reference = _store_scoped_authorization(
config,
reference=None,
@@ -4676,6 +5002,7 @@ def make_session_cookie(
claims=stored_claims,
authorization_state="current",
checked_at=issued_at,
+ expected_binding_generation=request_binding_generation,
)
payload = {
"email": email,
@@ -4849,6 +5176,11 @@ def _load_authorization_record(
if existing is not None:
return existing
try:
+ request_binding_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ )
stored_reference = _store_scoped_authorization(
config,
reference=None,
@@ -4857,6 +5189,7 @@ def _load_authorization_record(
claims=claims,
authorization_state="current",
checked_at=checked_at,
+ expected_binding_generation=request_binding_generation,
)
return remote_access_authorization_service.load_reference_record(
reference=stored_reference,
@@ -4886,17 +5219,40 @@ def _validated_authorization_payload(
config: V2Config,
identity: Mapping[str, Any],
record: Mapping[str, Any],
+ *,
+ binding_gate: bool | None = None,
) -> dict[str, Any] | None:
+ # Class 2: one (ready, kind, generation) consultation per evaluation.
+ # Callers that already captured the gate pass it in; this function must
+ # not trigger a second live read inside the same evaluation.
+ gate = binding_is_ready(config, identity) if binding_gate is None else binding_gate
+ if not gate and not _is_exact_show_page_grant(identity, record):
+ return None
+ if (
+ _known_kind_requires_runtime_pairing(config)
+ and not _runtime_pairing_available(config)
+ and not _is_exact_show_page_grant(identity, record)
+ ):
+ return None
claims = record.get("claims")
if not isinstance(claims, Mapping):
return None
+ from vibe.authorization import instance_kind_is_unsupported
+
+ if instance_kind_is_unsupported(
+ claims.get("vibe_instance_kind")
+ ) and not _is_exact_show_page_grant(identity, record):
+ # A present-but-unrecognized persisted kind (corruption or a newer
+ # release's artifact) is not a legacy no-kind row. Fail closed so the
+ # row revalidates instead of falling through to legacy-current.
+ return None
payload = dict(identity)
payload.update(claims)
reference = record.get("id")
if isinstance(reference, str):
payload[_SESSION_AUTHORIZATION_REFERENCE_KEY] = reference
try:
- session_claims_from_oidc(config, payload)
+ session_claims_from_oidc(config, claims)
except OAuthCodeExchangeError:
return None
return payload
@@ -4931,6 +5287,11 @@ def _fetch_authorization_context(
now: int,
observed_revision: int | None,
) -> AuthorizationResolution:
+ from storage import remote_access_authorization_service
+
+ request_binding_generation = (
+ remote_access_authorization_service.current_instance_binding_generation()
+ )
subject = str(identity.get("sub") or "").strip()
email = str(identity.get("email") or "").strip()
request_payload: dict[str, Any] = {"sub": subject, "email": email}
@@ -4965,6 +5326,12 @@ def _fetch_authorization_context(
claims=revoked_claims,
authorization_state="revoked",
checked_at=now,
+ expected_binding_generation=request_binding_generation,
+ )
+ except remote_access_authorization_service.InstanceBindingChangedError:
+ return AuthorizationResolution(
+ "unavailable",
+ reason="instance_binding_changed",
)
except Exception:
logger.warning("remote authorization revocation persistence failed", exc_info=True)
@@ -4980,6 +5347,42 @@ def _fetch_authorization_context(
return AuthorizationResolution("unavailable", reason="instance_kind_unavailable")
try:
claims = session_claims_from_oidc(config, response)
+ except Exception:
+ logger.warning("remote authorization context validation failed", exc_info=True)
+ return AuthorizationResolution("unavailable", reason="authorization_context_invalid")
+ live_state = remote_access_authorization_service.load_instance_binding_state(
+ ensure=False
+ )
+ live_generation = int((live_state or {}).get("generation") or 0)
+ live_id = str((live_state or {}).get("instance_id") or "")
+ request_id = str(identity.get("instance_id") or "")
+ if live_id and request_id and live_id != request_id:
+ return AuthorizationResolution("unavailable", reason="instance_binding_changed")
+ if live_generation > int(request_binding_generation):
+ # Same-instance kind reclassification is still a binding change.
+ return AuthorizationResolution("unavailable", reason="instance_binding_changed")
+ try:
+ persisted = _persist_instance_kind(
+ str(identity.get("instance_id") or ""),
+ instance_kind,
+ expected_binding_generation=request_binding_generation,
+ )
+ except Exception:
+ logger.warning("remote instance kind persistence failed", exc_info=True)
+ persisted = False
+ if persisted is False:
+ live_state = remote_access_authorization_service.load_instance_binding_state(
+ ensure=False
+ )
+ live_generation = int((live_state or {}).get("generation") or 0)
+ live_id = str((live_state or {}).get("instance_id") or "")
+ request_id = str(identity.get("instance_id") or "")
+ if live_id and request_id and live_id != request_id:
+ return AuthorizationResolution("unavailable", reason="instance_binding_changed")
+ if live_generation > int(request_binding_generation):
+ return AuthorizationResolution("unavailable", reason="instance_binding_changed")
+ return AuthorizationResolution("unavailable", reason="instance_kind_persistence_failed")
+ try:
revision = _authorization_revision_from_claims(claims)
if revision is not None:
_replace_authorization_revision(config, revision)
@@ -4996,27 +5399,25 @@ def _fetch_authorization_context(
claims=stored_claims,
authorization_state="current",
checked_at=now,
+ instance_kind=instance_kind,
+ expected_binding_generation=(
+ int(persisted)
+ if not isinstance(persisted, bool)
+ else request_binding_generation
+ ),
)
- from storage import remote_access_authorization_service
-
refreshed_record = remote_access_authorization_service.load_reference_record(
reference=reference,
instance_id=str(identity.get("instance_id") or ""),
subject=subject,
now=now,
)
+ except remote_access_authorization_service.InstanceBindingChangedError:
+ return AuthorizationResolution("unavailable", reason="instance_binding_changed")
except Exception:
- logger.warning("remote authorization context validation failed", exc_info=True)
+ logger.warning("remote authorization context persistence failed", exc_info=True)
return AuthorizationResolution("unavailable", reason="authorization_context_invalid")
config.remote_access.vibe_cloud.instance_kind = instance_kind
- try:
- _persist_instance_kind(str(identity.get("instance_id") or ""), instance_kind)
- except Exception:
- # The authoritative response and durable context are already valid.
- # A config write failure must not turn accepted access into an outage;
- # this in-memory config immediately follows the discovered policy and a
- # later runtime status/auth refresh can retry the persistent backfill.
- logger.warning("Remote instance kind backfill failed", exc_info=True)
if refreshed_record is None:
return AuthorizationResolution("unavailable", reason="authorization_context_persistence_failed")
payload = _validated_authorization_payload(config, identity, refreshed_record)
@@ -5080,7 +5481,10 @@ def _refresh_authorization_context(
if current_record is not None:
if current_record.get("authorization_state") == "revoked":
return AuthorizationResolution("revoked", reason="access_denied")
- if recent_result[1] == "current":
+ if (
+ recent_result[1] == "current"
+ and current_record.get("authorization_state") == "current"
+ ):
current_payload = _validated_authorization_payload(
config,
identity,
@@ -5109,7 +5513,10 @@ def _refresh_authorization_context(
completed_at = time.monotonic()
with _AUTHORIZATION_REFRESH_LOCK:
_AUTHORIZATION_REFRESH_RESULTS.pop(key, None)
- if refreshed.state == "unavailable":
+ if (
+ refreshed.state == "unavailable"
+ and refreshed.reason != "instance_binding_changed"
+ ):
_AUTHORIZATION_REFRESH_FAILURES[key] = completed_at
if len(_AUTHORIZATION_REFRESH_FAILURES) > 1024:
cutoff = completed_at - AUTHORIZATION_REFRESH_FAILURE_BACKOFF_SECONDS
@@ -5161,18 +5568,27 @@ def _refresh_authorization_context(
def _authorization_refresh_key(
identity: Mapping[str, Any],
record: Mapping[str, Any] | None,
-) -> tuple[str, str, str, str]:
+) -> tuple[str, str, str, str, int]:
scope_kind = str(record.get("scope_kind") or "instance") if record else "instance"
scope_ref = (
str(record.get("scope_ref") or identity.get("instance_id") or "")
if record
else str(identity.get("instance_id") or "")
)
+ try:
+ from storage import remote_access_authorization_service
+
+ generation = remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ except Exception:
+ generation = 0
return (
str(identity.get("instance_id") or ""),
str(identity.get("sub") or ""),
scope_kind,
scope_ref,
+ int(generation),
)
@@ -5263,11 +5679,26 @@ def resolve_current_authorization(
if refreshed.state != "unavailable":
return refreshed
return AuthorizationResolution("revoked", reason="access_denied")
+ # Class 2: capture the binding gate ONCE for this evaluation. Both the
+ # payload admission and the kind derivation below use this snapshot; a
+ # reconciling that begins mid-evaluation can no longer collapse a failed
+ # second read into the legacy no-kind branch.
+ binding_gate = binding_is_ready(config, identity)
payload = (
- _validated_authorization_payload(config, identity, record)
+ _validated_authorization_payload(
+ config, identity, record, binding_gate=binding_gate
+ )
if record is not None
else None
)
+ if (
+ payload is None
+ and record is not None
+ and not _runtime_pairing_available(config)
+ and _known_kind_requires_runtime_pairing(config)
+ and not _is_exact_show_page_grant(identity, record)
+ ):
+ return AuthorizationResolution("unavailable", reason="pairing_unavailable")
if payload is None:
return (
_refresh_authorization_context(config, identity, record, now=current)
@@ -5275,13 +5706,58 @@ def resolve_current_authorization(
else AuthorizationResolution("unavailable", reason="authorization_context_missing")
)
- instance_kind = _normalized_instance_kind(config.remote_access.vibe_cloud.instance_kind)
+ instance_kind = (
+ _normalized_instance_kind(config.remote_access.vibe_cloud.instance_kind)
+ if binding_gate
+ else None
+ )
signed_revision = _authorization_revision_from_claims(payload)
current_revision = (
current_authorization_revision(config, now=revision_now)
if _authorization_revision_sync_configured(config)
else None
)
+ stored_kind = None
+ if record is not None:
+ stored_claims = record.get("claims")
+ if isinstance(stored_claims, Mapping):
+ stored_kind = _normalized_instance_kind(stored_claims.get("vibe_instance_kind"))
+ is_exact_show_page = _is_exact_show_page_grant(identity, record)
+ kindless_current_needs_refresh = (
+ not is_exact_show_page
+ and instance_kind is not None
+ and stored_kind is None
+ and record is not None
+ and record.get("authorization_state") == "current"
+ )
+ kind_mismatch = (
+ not is_exact_show_page
+ and (
+ (
+ instance_kind is not None
+ and stored_kind is not None
+ and stored_kind != instance_kind
+ )
+ or (
+ instance_kind is not None
+ and stored_kind is None
+ and record is not None
+ and record.get("authorization_state") == "stale"
+ )
+ or kindless_current_needs_refresh
+ )
+ )
+ if kind_mismatch:
+ # A row tagged with the previous kind (or invalidated by a
+ # reclassification) must revalidate before EITHER kind-specific
+ # policy runs — returning it as current under the new kind would let
+ # the old kind's claims outlive the reclassification.
+ if allow_refresh:
+ return _refresh_authorization_context(config, identity, record, now=current)
+ return AuthorizationResolution(
+ "unavailable",
+ reason="authorization_context_missing",
+ )
if instance_kind == "personal":
if (
@@ -5386,8 +5862,15 @@ def renew_session_cookie(
current = int(time.time()) if now is None else now
reference = payload.get(_SESSION_AUTHORIZATION_REFERENCE_KEY)
if not isinstance(reference, str):
+ from storage import remote_access_authorization_service
+
claims = _authorization_claims_from_payload(payload)
checked_at = int(payload.get("claims_issued_at", payload.get("iat", current)))
+ request_binding_generation = (
+ remote_access_authorization_service.current_instance_binding_generation(
+ ensure=False
+ )
+ )
reference = _store_scoped_authorization(
config,
reference=None,
@@ -5396,6 +5879,7 @@ def renew_session_cookie(
claims=claims,
authorization_state="current",
checked_at=checked_at,
+ expected_binding_generation=request_binding_generation,
)
browser_session_id = payload.get(_SESSION_BROWSER_ID_KEY)
if not isinstance(browser_session_id, str):