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(remote-access): finish hardening the unauthenticated OAuth path (codex round 3)

cyhb4cf7f41cedc
diff --git a/tests/test_ui_remote_access_auth.py b/tests/test_ui_remote_access_auth.py
index d8fb120d2..062968931 100644
--- a/tests/test_ui_remote_access_auth.py
+++ b/tests/test_ui_remote_access_auth.py
@@ -1233,6 +1233,34 @@ def test_oauth_handshake_store_caps_entries(monkeypatch, tmp_path):
assert remote_access.pop_oauth_handshake("rid-0") is not None
+def test_oauth_handshake_cap_holds_under_concurrency(monkeypatch, tmp_path):
+ # Atomic admission: a concurrent burst must not blow past the cap. Without the
+ # lock, many threads could pass the count check before any writes.
+ import threading
+
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ _save_config(tmp_path)
+ monkeypatch.setattr(remote_access, "OAUTH_HANDSHAKE_MAX_ENTRIES", 5)
+
+ barrier = threading.Barrier(20)
+
+ def worker(i):
+ try:
+ barrier.wait(timeout=5)
+ except threading.BrokenBarrierError:
+ pass
+ remote_access.store_oauth_handshake(f"rid-{i:03d}", nonce="n", code_verifier="v", next_target="/")
+
+ threads = [threading.Thread(target=worker, args=(i,)) for i in range(20)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ live = list((paths.get_runtime_dir() / "oauth_handshakes").glob("*.json"))
+ assert len(live) <= 5
+
+
def test_oauth_diag_log_is_rate_limited(monkeypatch):
# The unauthenticated callback failure path must not grow the log without bound:
# repeated hits within the window emit once, with the suppressed count folded in.
diff --git a/vibe/remote_access.py b/vibe/remote_access.py
index fc1358423..c41cc64f6 100644
--- a/vibe/remote_access.py
+++ b/vibe/remote_access.py
@@ -880,6 +880,14 @@ OAUTH_HANDSHAKE_TTL_SECONDS = 300
# logins) and is far above any realistic concurrent-login count.
OAUTH_HANDSHAKE_MAX_ENTRIES = 2048
_OAUTH_HANDSHAKE_RID_RE = re.compile(r"\A[A-Za-z0-9_-]{1,64}\Z")
+# Serializes prune+capacity-check+write so the cap is enforced atomically under a
+# concurrent burst (count-then-write without a lock could blow past the cap).
+_OAUTH_STORE_LOCK = threading.Lock()
+# Throttle the "at capacity" warning: under a sustained flood it would otherwise be
+# emitted on every shed write and grow the log unbounded — the very thing the cap
+# is meant to prevent.
+_OAUTH_STORE_CAPACITY_WARN_INTERVAL_SECONDS = 60.0
+_oauth_store_capacity_warned_at = 0.0
def _oauth_handshake_dir() -> Path:
@@ -905,6 +913,15 @@ def _prune_oauth_handshakes(directory: Path) -> int:
return survivors
+def _warn_oauth_store_at_capacity() -> None:
+ """Log the capacity-shed warning at most once per interval (call under the lock)."""
+ global _oauth_store_capacity_warned_at
+ now = time.monotonic()
+ if now - _oauth_store_capacity_warned_at >= _OAUTH_STORE_CAPACITY_WARN_INTERVAL_SECONDS:
+ _oauth_store_capacity_warned_at = now
+ logger.warning("oauth handshake store at capacity (>= %d); shedding writes", OAUTH_HANDSHAKE_MAX_ENTRIES)
+
+
def store_oauth_handshake(
rid: str, *, nonce: str, code_verifier: str, next_target: str, device_hash: str | None = None
) -> None:
@@ -917,16 +934,6 @@ def store_oauth_handshake(
if not _OAUTH_HANDSHAKE_RID_RE.match(rid or ""):
return
directory = _oauth_handshake_dir()
- try:
- directory.mkdir(parents=True, exist_ok=True)
- directory.chmod(0o700)
- except OSError:
- pass
- # Prune expired records first; if the store is still at capacity (i.e. flooded
- # with fresh entries), shed this write rather than grow unbounded on disk.
- if _prune_oauth_handshakes(directory) >= OAUTH_HANDSHAKE_MAX_ENTRIES:
- logger.warning("oauth handshake store at capacity (>= %d); skipping write", OAUTH_HANDSHAKE_MAX_ENTRIES)
- return
payload = {
"nonce": nonce,
"code_verifier": code_verifier,
@@ -935,19 +942,32 @@ def store_oauth_handshake(
"exp": int(time.time()) + OAUTH_HANDSHAKE_TTL_SECONDS,
}
final = directory / f"{rid}.json"
- tmp = directory / f".{rid}.{os.getpid()}.tmp"
- try:
- tmp.write_text(json.dumps(payload, separators=(",", ":")), encoding="utf-8")
+ tmp = directory / f".{rid}.{os.getpid()}.{secrets.token_hex(6)}.tmp"
+ # Hold the lock across prune + capacity-check + write so admission is atomic:
+ # otherwise a concurrent burst could all pass the check and blow past the cap.
+ with _OAUTH_STORE_LOCK:
try:
- tmp.chmod(0o600)
+ directory.mkdir(parents=True, exist_ok=True)
+ directory.chmod(0o700)
except OSError:
pass
- os.replace(tmp, final)
- except OSError:
+ # Prune expired records first; if the store is still at capacity (i.e. a
+ # flood of fresh entries), shed this write rather than grow unbounded.
+ if _prune_oauth_handshakes(directory) >= OAUTH_HANDSHAKE_MAX_ENTRIES:
+ _warn_oauth_store_at_capacity()
+ return
try:
- tmp.unlink()
+ tmp.write_text(json.dumps(payload, separators=(",", ":")), encoding="utf-8")
+ try:
+ tmp.chmod(0o600)
+ except OSError:
+ pass
+ os.replace(tmp, final)
except OSError:
- pass
+ try:
+ tmp.unlink()
+ except OSError:
+ pass
def pop_oauth_handshake(rid: str | None) -> dict[str, Any] | None:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index d0f28530e..c125a9a2b 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2645,7 +2645,8 @@ def remote_access_auth_callback():
result = remote_access.exchange_oauth_code(config, _oauth_callback_arg("code") or "", code_verifier)
claims = result["claims"]
except Exception as exc:
- logger.warning("vibe cloud oauth code exchange failed: %s", exc)
+ # Unauthenticated-reachable (valid handshake + bad code), so rate-limited.
+ _log_oauth_diag("exchange_failed", "vibe cloud oauth code exchange failed: %s", exc)
return _oauth_callback_error_response("oauth_exchange_failed", next_target=next_target)
if claims.get("nonce") != handshake_nonce:
return _oauth_callback_error_response("invalid_oauth_nonce", next_target=next_target)