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): restore instance Member management parity (#2004)

Maxfc45b282339e
diff --git a/config/v2_config.py b/config/v2_config.py
index 808529b6b..68671855d 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -1571,7 +1571,7 @@ class SlackConfig(BaseIMConfig):
require_mention: bool = False
# Global default for the per-channel require_bind gate (allowed users).
# False=any channel member may drive the agent, True=only bound users.
- # Channels whose per-channel require_bind is None inherit this value.
+ # Seeds newly enabled channels; runtime None/False remains unrestricted.
require_bind: bool = False
disable_link_unfurl: bool = False
@@ -3938,39 +3938,10 @@ class V2Config:
return config
migrated_payload, migrated, migration_warnings = _migrate_config_payload_on_load(payload)
- candidate = migrated_payload
- recovery_warnings: list[str] = []
- recovered_sections: set[str] = set()
- whole_config_recovery = False
- while True:
- try:
- config = cls.from_payload(candidate)
- break
- except (TypeError, ValueError) as exc:
- section = _recovery_section_for_error(exc)
- field_name = _recovery_field_for_error(section, exc)
- # Keyed by whatever this pass will actually repair, so the
- # dedupe that stops the loop cannot mistake a second unreadable
- # field of a field-scoped section for no progress and discard
- # the whole file.
- recovered = section if field_name is None else f"{section}.{field_name}"
- if section is None or recovered in recovered_sections:
- warning = f"Config could not be loaded; using recovery defaults: {exc}"
- logger.error("%s", warning)
- config = cls.default()
- recovery_warnings.append(warning)
- whole_config_recovery = True
- break
- if not _reset_recoverable_config_section(candidate, section, field_name):
- warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"
- logger.error("%s", warning)
- config = cls.default()
- recovery_warnings.append(warning)
- whole_config_recovery = True
- break
- recovered_sections.add(recovered)
- recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")
-
+ config = cls._recover_payload(migrated_payload)
+ recovery_warnings = config.load_warnings
+ recovered_sections = config.recovered_sections
+ whole_config_recovery = config.whole_config_recovery
all_warnings = tuple(dict.fromkeys((*migration_warnings, *recovery_warnings)))
if (
persist_migrations
@@ -4014,6 +3985,46 @@ class V2Config:
config.whole_config_recovery = whole_config_recovery
return config
+ @classmethod
+ def _recover_payload(cls, candidate: dict) -> "V2Config":
+ """Parse stored data with recovery defaults, without file IO or locks."""
+ recovery_warnings: list[str] = []
+ recovered_sections: set[str] = set()
+ whole_config_recovery = False
+ while True:
+ try:
+ config = cls.from_payload(candidate)
+ break
+ except (TypeError, ValueError) as exc:
+ section = _recovery_section_for_error(exc)
+ field_name = _recovery_field_for_error(section, exc)
+ # Keyed by whatever this pass will actually repair, so the
+ # dedupe that stops the loop cannot mistake a second unreadable
+ # field of a field-scoped section for no progress and discard
+ # the whole file.
+ recovered = section if field_name is None else f"{section}.{field_name}"
+ if section is None or recovered in recovered_sections:
+ warning = f"Config could not be loaded; using recovery defaults: {exc}"
+ logger.error("%s", warning)
+ config = cls.default()
+ recovery_warnings.append(warning)
+ whole_config_recovery = True
+ break
+ if not _reset_recoverable_config_section(candidate, section, field_name):
+ warning = f"Config section '{section}' could not be recovered; using recovery defaults: {exc}"
+ logger.error("%s", warning)
+ config = cls.default()
+ recovery_warnings.append(warning)
+ whole_config_recovery = True
+ break
+ recovered_sections.add(recovered)
+ recovery_warnings.append(f"Recovered invalid config section '{recovered}': {exc}")
+
+ config.load_warnings = tuple(recovery_warnings)
+ config.recovered_sections = tuple(sorted(recovered_sections))
+ config.whole_config_recovery = whole_config_recovery
+ return config
+
@classmethod
def from_payload(cls, payload: dict) -> "V2Config":
if not isinstance(payload, dict):
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 18c0e7f51..920673f5b 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -1,3 +1,4 @@
+import copy
import json
import logging
import hmac
@@ -547,20 +548,24 @@ class SettingsStore:
def _load(self) -> None:
self.settings = self._service.load_state()
+ self._loaded_state = copy.deepcopy(self.settings)
self._generation += 1
- def save(self) -> None:
+ def save(self, *, user_context=None) -> None:
with self._reload_lock:
try:
- revision = self._service.save_state(self.settings)
+ revision = self._service.save_state(
+ self.settings, user_context=user_context, baseline=self._loaded_state
+ )
except Exception:
- # API helpers mutate the singleton before saving. A refused transaction
- # must restore the durable snapshot before any later read or save.
+ # Restore the durable snapshot after a refused transaction before
+ # this store can be read or saved again.
self._load_with_revision()
raise
# Use the exact revision committed by this transaction. Reading the
# current value here could absorb a later external write without loading it.
self._observed_revision = revision
+ self._loaded_state = copy.deepcopy(self.settings)
self._generation += 1
# --- Channel helpers ---
@@ -632,21 +637,25 @@ class SettingsStore:
thread_id: str,
settings: ChannelSettings,
platform: Optional[str] = None,
+ *,
+ user_context=None,
) -> None:
key = self._thread_key(channel_id, thread_id, platform)
self._carry_agent_binding_expectation(self.settings.threads.get(key), settings)
self.settings.threads[key] = settings
- self.save()
+ self.save(user_context=user_context)
def delete_thread(
self,
channel_id: str,
thread_id: str,
platform: Optional[str] = None,
+ *,
+ user_context=None,
) -> bool:
removed = self.settings.threads.pop(self._thread_key(channel_id, thread_id, platform), None)
if removed is not None:
- self.save()
+ self.save(user_context=user_context)
return True
return False
diff --git a/core/chat_discovery.py b/core/chat_discovery.py
index 8dd23808e..df69004d6 100644
--- a/core/chat_discovery.py
+++ b/core/chat_discovery.py
@@ -1058,6 +1058,7 @@ def delete_scope(
*,
scope_type: str = CHANNEL_SCOPE_TYPE,
db_path: Path | None = None,
+ user_context: Any = None,
) -> dict[str, bool]:
"""Remove a discovered scope and its settings without destroying history.
@@ -1076,13 +1077,27 @@ def delete_scope(
Returns ``{"removed": bool, "dismissed": bool}``.
"""
scope_id = make_scope_id(platform, scope_type, native_id)
+ from storage.agent_session_rows import reserve_write_lock
+ from vibe.authorization import InstanceAuthorizationError, require_instance_role
+
+ context = require_instance_role(user_context, "member")
engine = _engine(db_path)
try:
with engine.begin() as conn:
+ reserve_write_lock(conn)
row = conn.execute(select(scopes).where(scopes.c.id == scope_id)).mappings().one_or_none()
if row is None:
return {"removed": False, "dismissed": False}
descendants = _descendant_scope_rows(conn, scope_id)
+ if not context.can_manage_access_members:
+ removed_ids = [scope_id, *(item["id"] for item in descendants)]
+ settings = conn.execute(
+ select(scope_settings.c.settings_json).where(scope_settings.c.scope_id.in_(removed_ids))
+ ).scalars()
+ # Removing a parent also removes thread overrides. All would
+ # return to the open default if rediscovered.
+ if any(json.loads(value or "{}").get("require_bind") for value in settings):
+ raise InstanceAuthorizationError("owner")
runtime_settings_changed = False
for descendant in reversed(descendants):
_, descendant_changed = _remove_scope_row_preserving_history(conn, descendant)
diff --git a/docs/plans/instance-access-role-member.md b/docs/plans/instance-access-role-member.md
index f39738f1c..b613316d2 100644
--- a/docs/plans/instance-access-role-member.md
+++ b/docs/plans/instance-access-role-member.md
@@ -126,7 +126,7 @@ Project ACL (`access_role` `editor|viewer`) is **out of scope**.
## HTTP / SSE policy (app)
- Default `/api/` minimum stays fail-closed.
-- Member-reachable management routes are explicitly declared in `_MEMBER_HTTP_RULES`; unknown APIs remain Owner-only. Member-management, credential, host-lifecycle, ACL-write, and bulk-onboarding routes stay outside that allowlist.
+- Member-reachable management routes are explicitly declared in `_MEMBER_HTTP_RULES`; unknown APIs remain Owner-only. Ordinary instance management includes Model Hub, backend/platform credentials, host lifecycle, safe remote transport settings and existing DM preferences. Access-member/role administration, pairing identity, Project/Resource ACL writes, WeChat QR binding and bulk ownership onboarding remain protected. Mixed settings writes preserve access effects at the locked writer; see [Member management parity](member-management-parity.md).
- `POST /api/agents/default` requires the member tier and its setter requires `can_manage_agents`. The default remains advisory: assigning a private or scope-policy Agent does not widen its ACL, and callers who cannot use it degrade to another usable Agent at resolution time.
- Privileged SSE events (definitions/runs/vaults updated) currently require owner. **Member receives them** (they are instance-management events, not member-management). Implement by treating them as `has_role("member")`.
- Editor SSE (`queue.updated`) and viewer SSE unchanged.
diff --git a/docs/plans/member-management-parity.md b/docs/plans/member-management-parity.md
new file mode 100644
index 000000000..f64072bd1
--- /dev/null
+++ b/docs/plans/member-management-parity.md
@@ -0,0 +1,231 @@
+# Instance Member management parity
+
+Status: authoritative implementation contract, 2026-09-16.
+Orchestrator: Avibe Session `sescctptxwqdq`.
+Implementation Session: `sesb5c3sb2ayz`.
+Baseline: `avibe-bot/avibe` master `1b191200ce0834ee811d478f54255ff0b0cb9819`.
+
+This contract supersedes the initial Model Hub-only scope. Deliver one coherent
+PR in the existing task branch/worktree.
+
+## Owner intent and causal model
+
+The owner originally defined Member on 2026-08-19 as having the same Avibe-side
+instance settings as Owner, except adding/removing access members and changing
+their roles. On 2026-09-16 they reported broken Organization Model Hub settings,
+then explicitly requested an audit and one complete fix of the other unintended
+Member restrictions.
+
+Example: a remote instance Member opens Models. Navigation admits the user via
+`can_manage_instance`, but the mandatory runtime-status HTTP read requires Owner.
+The page consequently hides its settings. Config saves repeat the same mismatch
+one layer deeper by giving a Member the Editor preference-only write schema.
+
+The cause is competing definitions of instance management: capability projection
+says Member; a historical partial HTTP allowlist and individual owner-identity
+checks say Owner. Repair that category across real consumers, rather than adding
+another isolated route exception.
+
+## Frozen authority boundaries
+
+1. **Instance management** follows the existing `can_manage_instance`,
+ `can_manage_agents`, `can_manage_projects` and `can_use_system` capabilities.
+ Instance Member and Owner pass. Do not add a role or redundant capability.
+2. **Access administration and ownership** remain Owner-only. This includes
+ creating/removing/enabling/disabling bound access members, role/admin changes,
+ binding codes (including reads that disclose live codes), pairing identity and
+ session-signing material, ownership transfer, and Project/Resource access
+ grants. Channel binding requirements and explicit principal admission lists
+ are access policy, not ordinary routing preferences.
+3. **Resource visibility and use** retain the existing Organization Project,
+ Agent, session, Show Page and principal scopes. Being an instance manager must
+ not turn `is_instance_owner` into true or bypass private content filtering.
+ Personal behavior retains its existing rules. Management of visible Projects
+ and existing owner-equivalent Agent management must keep working.
+4. **Organization roles are independent.** Organization Member/Admin/Owner does
+ not substitute for an instance-management grant.
+5. **Other roles and authentication remain stable.** Editor/Viewer grants,
+ unauthenticated denial, CSRF, secret redaction, protected Vault proofs, and
+ Model Hub supply-impact confirmations are unchanged. Unknown management APIs
+ remain fail-closed until deliberately classified.
+
+These distinctions are based on effects. Do not replace every owner-identity
+check mechanically. In particular `_has_runtime_owner_access` often protects
+private records and must not become a general management predicate.
+
+## Audit and required corrections
+
+The baseline main UI module registers 276 `/api` HTTP route/method pairs, with
+15 further Memory pairs: 291 total. Of these, 106 are Owner-only; 28 of those
+are Model Hub. The other 78 consist of 59 routine management candidates, nine
+access/identity operations, and ten mixed-effect operations. These counts include
+implicit GET decorators and exclude WebSockets. This is an inventory starting
+point, not a claim that all 106 are wrong. Include dynamically registered modules
+(especially Memory), non-API authenticated runtime repair, frontend controls and
+service-level guards in the completed audit.
+
+| Surface | Required Member behavior | Retained boundary |
+| --- | --- | --- |
+| Model Hub | Complete status, source/credential/OAuth, gateway lifecycle, catalogs, routes, probes, usage, events and migration management | Existing picker permissions, auth, secret handling and supply-impact guards |
+| Backend setup | Inspect/configure/login/logout/test providers; install/restart Agent backends; edit provider models and defaults | No instance access grants are minted by these operations |
+| General settings | Save the same ordinary settings and provider/platform credentials as Owner | Access-policy fields and pairing identity cannot change through generic config |
+| Messaging | Inspect/connect/configure platforms; discover and enable/disable channels; change routing, cwd and display/mention preferences | Bound-user set/roles, binding requirements and explicit admission lists remain protected |
+| Existing DM preferences | Update non-membership settings for existing users | Cannot create/delete/reactivate users, change roles, or overwrite concurrent membership changes |
+| Runtime and system | Service lifecycle, UI reload, upgrade, dependency installation, diagnostics/logs, directory browsing/creation | Validation uses test doubles; no actual production operations |
+| Remote access operation | Status, diagnostics, optimization, start/stop and transport tuning of the current pairing | No re-pair, identity replacement, secret replacement, or ownership change |
+| Workbench | Save ordinary preferences and repair the runtime of an accessible Show Page | Private resource/session visibility remains enforced |
+| Vault | Edit metadata/tags/policy/classification, rotate and delete secrets through existing manager paths | Protected operations still require the original cryptographic authorization; access grants and private principal data are not bypassed |
+| Agents/Projects/Skills/Memory/Harness | Verify existing advertised management capabilities reach real operations; fix further demonstrated settings mismatches | Preserve Project/Agent use ACL, Memory user identity and managed-mode restrictions |
+
+Two effect-based exceptions already identified must be recorded explicitly:
+
+- Legacy bulk Agent onboarding claims previously ownerless resources under the
+ caller's ownership. It is ownership migration; keep its Owner gate and existing
+ hidden Member UI rather than changing resource ownership as a side effect of
+ this repair. Ordinary Agent CRUD/import/default selection remain Member.
+- The existing WeChat QR completion flow automatically binds a user and may
+ appoint an admin. Preserve Owner authorization for this combined binding flow;
+ direct platform credential settings are instance management. Make the UI
+ reflect this restriction rather than offering an action that inevitably fails.
+
+## Mixed-write invariant
+
+Do not choose between blocking a whole settings page and admitting its embedded
+access-control writes. The invariant is:
+
+> A Member settings mutation may change ordinary configuration but must preserve
+> the authoritative access-member set, roles and explicit access policy.
+
+Apply validation where the current state and mutation are committed together.
+Reuse existing config locks/settings transactions. Refuse unauthorized changes
+with an actionable existing error contract; do not silently strip requested
+changes and report success. Preserve normal field-scoped UI writes and legacy
+shapes where safe. Equal protected-field echoes may be accepted only after
+comparison with the fresh authoritative value.
+
+Audit all input shapes reaching that writer: partial updates, full replacements,
+list operations, legacy aliases, defaults/omission, inherited thread settings and
+deletion. An omitted protected field cannot reset it, and deleting a thread
+override cannot relax its effective binding policy. A concurrent user removal
+cannot be undone by a stale DM-preference save. Protect the membership effect,
+not just one JSON spelling of it.
+
+Candidate state must remain private to the request until authorized and committed.
+The process-wide SettingsStore must never expose an unvalidated Member mutation
+to a concurrent Owner/internal save. A SQLite comparison alone is insufficient
+when another writer can commit that shared candidate first. Cover an interleaving
+where Member attempts a role/admission change while Owner saves unrelated ordinary
+settings; neither the Owner write nor a later Member comparison may authorize it.
+Reuse the existing settings writer and transaction rather than adding another
+permissions or persistence model.
+
+Request isolation must also preserve concurrent ordinary writes. Under the same
+SQLite write lock, apply only the request's changes relative to its loaded
+baseline to the fresh state; never replay an entire stale database snapshot.
+Untouched scopes and their concurrent creation/deletion must survive. Evaluate
+the resulting access effects against that fresh state before committing, without
+silently removing explicitly requested forbidden changes. Keep existing Agent
+binding conflict checks and effective thread-policy checks in this transaction.
+If protected policy changed since the Member's baseline was loaded, refuse the
+stale save before merging: an explicit unchanged role/binding echo must not be
+silently discarded. The caller can reload and retry against current policy.
+
+Runtime semantics govern that comparison: `core/auth.py` checks the selected
+channel/thread record's explicit `require_bind`. Channel `None`/`False` means
+unrestricted by binding; platform defaults only seed new configuration. A thread
+without its own record falls back to its parent channel. Do not introduce global
+runtime inheritance based on the stale platform-config comment. Channel
+`enabled` is an operational switch and remains Member-writable; bound-user
+`enabled` controls member admission and remains Owner-only. The existing
+`core/chat_discovery.py::delete_scope` writer may receive a narrow same-transaction
+policy-preservation check, including descendant settings it removes.
+
+Generic `/api/config` must keep pairing/session identity protected; the dedicated
+remote-access settings route already owns safe transport tuning. Preserve
+provider credential redaction on responses. Frontend controls for retained
+Owner-only actions must use `can_manage_access_members` or the appropriate true
+ownership condition, while ordinary settings use management capabilities.
+
+## Implementation approach and scope
+
+- Evolve the existing central HTTP/capability policy. Express each management
+ surface coherently and cover the complete registered route inventory in tests;
+ do not leave a manually curated subset as the definition of completeness.
+- Allowed production files: `vibe/authorization.py`, `vibe/ui_server.py`,
+ `vibe/api.py`, `vibe/ui_memory_routes.py` if a real mismatch is found,
+ `storage/vault_service.py`, existing settings/config service modules needed for
+ atomic mixed-write validation, and narrow related frontend settings/control
+ files. Existing other service guards may be changed only for demonstrated
+ management mismatch and with an audit entry explaining the effect.
+- Allowed tests/docs: focused authorization/config/settings/Vault/remote-access
+ and corresponding UI/scenario tests; this contract, the prior Member plan,
+ relevant Model Hub contract wording and concise user documentation.
+- Do not modify resource-use ACL semantics, the backend control-plane repo,
+ unrelated runtime features, dependency versions or deployment state.
+- No visual redesign is necessary. Prefer capability binding and existing
+ disabled/read-only patterns and localized copy for retained restrictions.
+
+## Validation and delivery gate
+
+1. Audit every registered API route/method and every remaining relevant
+ owner-identity management guard. Assign it a capability or a documented
+ retained boundary; newly unclassified management surfaces must fail a test.
+2. Compare every existing role against the invariant, with both Personal and
+ Organization identities. Seed private/foreign/missing-policy resources to
+ show that settings parity does not change visibility or use grants.
+3. Exercise real signed remote HTTP session + CSRF paths through representative
+ workflows from each changed category. Stub only external providers, host
+ operations and runtime IPC, after authorization. Verify writes and read-back,
+ not merely a mocked policy result or a non-403 status.
+4. For mixed writers, cover omissions, aliases, replacement/deletion and a stale
+ concurrent membership update. Denial must happen before any protected effect.
+5. Include the reported Models bootstrap scenario and preserve all Model Hub
+ role/registered-route coverage from the initial work.
+6. Run focused tests, Ruff on changed Python, focused UI tests and the production
+ UI build when frontend changes. Update relevant scenario catalogs where an
+ affected workflow already has one. Use hermetic test-owned state only.
+7. Open one non-draft PR whose title/body describe final Member management parity.
+ Follow `.agents/skills/pr-delivery-loop/SKILL.md`, obtain exact-head Codex pass,
+ all required CI green and zero unresolved threads. Enforce the review circuit
+ breaker before further patches; report full head/class inventory to the
+ orchestrator. Keep one lane watch and one independent orchestrator gate watch.
+8. Do not merge, install, restart live services or deploy without explicit owner
+ instruction. Deliver the PR, category-level change matrix, evidence and any
+ genuine unresolved product boundary before close-out.
+
+## Completed boundary inventory
+
+The live registered router has 291 distinct API method/path pairs, including
+Memory and the constant-decorated Model Service notification. Fifteen pairs
+retain the Owner default: access-member/role and binding-code administration,
+Project/Resource ACL writes, pairing, bulk Agent ownership onboarding, WeChat
+QR binding, and the internal `POST /api/model-service/refresh` notification.
+That last endpoint additionally requires the existing same-machine CLI token;
+a normal Owner session is insufficient. It is not a settings operation.
+
+The registered-route test independently names these retained boundaries and
+checks every registered route, rather than deriving completeness from the
+management allowlist. Memory retains its signed principal and trusted-origin
+gate; Skills and Harness retain their existing Editor surface. Resource-use
+and private runtime-record identity checks remain separate from management.
+
+Mixed writes prepare request-private SettingsStore candidates, then compare
+normalized config under the config lock and fresh settings under the SQLite
+write lock. Unvalidated candidates never enter the process-wide cache, so an
+overlapping Owner/controller save cannot commit a Member's forbidden draft.
+Real thread/event tests cover each mixed writer with an overlapping save. The settings check includes legacy Discord policy
+until migration, effective channel/thread binding, descendant deletion, and stale
+DM updates after member removal or role changes. Normal channel enabled state
+and DM routing/display/cwd remain management.
+
+Automated evidence: PERMISSIONS-013 covers signed Member management and guarded
+mixed writes; AUTH-SETUP-301 saves and reads a native backend credential in a
+test-owned home. Model Hub conformance covers all documented/registered endpoints
+through signed remote roles. UI controls and accessible Show Runtime repair have
+focused role tests. All providers, host lifecycle operations and runtime IPC are
+stubbed; this evidence does not claim a live deployment or tenant verification.
+
+Known by design: validated active remote Organization Editor-or-higher sessions
+already use Skills/Vault through the existing capability fast path. This change
+does not add that behavior or alter direct-context/private resource-use checks;
+protected secret use still needs its existing approval and cryptographic proof.
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index b481b72c0..252df60db 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1,5 +1,13 @@
# Model Hub — REST API contract
+Authorization: all current Model Hub management endpoints admit Instance Member
+and Owner in both Personal and Organization instances. The model picker read
+`GET /api/models/agents/<backend>/models` remains Editor-readable. Organization
+membership alone supplies no instance-management grant. Signed-session, CSRF,
+credential redaction and supply-impact confirmation rules still apply; unknown
+API siblings retain the Owner default.
+
+
Status: **Normative, `contract_version` 10** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
Success envelope: `{ok: true, contract_version: 10, ...}`.
diff --git a/storage/settings_service.py b/storage/settings_service.py
index 35d3a4120..f16459979 100644
--- a/storage/settings_service.py
+++ b/storage/settings_service.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import json
-from dataclasses import asdict, replace
+from dataclasses import asdict, fields, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
@@ -35,6 +35,117 @@ from storage.settings_revision import (
SETTINGS_VERSION = 1
GUILD_POLICY_KIND = "guild_policy"
+
+
+def _merge_settings_changes(
+ current: SettingsState, candidate: SettingsState, baseline: SettingsState
+) -> SettingsState:
+ """Apply changed scopes only, retaining other transactions' committed rows."""
+ def merge_rows(fresh, draft, original):
+ merged = dict(fresh)
+ for key in original.keys() - draft.keys():
+ merged.pop(key, None)
+ for key, item in draft.items():
+ previous = original.get(key)
+ if item != previous or getattr(item, "_agent_name_at_load", None) != getattr(
+ previous, "_agent_name_at_load", None
+ ):
+ merged[key] = item
+ return merged
+
+ merged = SettingsState()
+ for name in ("channels", "threads", "users", "guilds", "guild_default_enabled"):
+ setattr(merged, name, merge_rows(getattr(current, name), getattr(candidate, name), getattr(baseline, name)))
+ merged.guild_scope_platforms = (
+ current.guild_scope_platforms - (baseline.guild_scope_platforms - candidate.guild_scope_platforms)
+ ) | (candidate.guild_scope_platforms - baseline.guild_scope_platforms)
+ merged.bind_codes = list(merge_rows(
+ {item.code: item for item in current.bind_codes},
+ {item.code: item for item in candidate.bind_codes},
+ {item.code: item for item in baseline.bind_codes},
+ ).values())
+ return merged
+
+
+def _require_preserved_access_policy(current: SettingsState, candidate: SettingsState) -> None:
+ """Compare access effects against the snapshot held by the SQLite write lock."""
+ from vibe.authorization import InstanceAuthorizationError
+
+ # Until its first settings migration, Discord reads admission from config.
+ # Read the atomic config file directly: V2Config.load can itself migrate and
+ # acquire the config lock, inverting the config -> SQLite writer lock order.
+ from config import paths
+ from config.v2_config import V2Config, _migrate_config_payload_on_load
+
+ legacy_guilds = None
+ if "discord" not in current.guild_scope_platforms or "discord" not in candidate.guild_scope_platforms:
+ try:
+ config_payload = json.loads(paths.get_config_path().read_text(encoding="utf-8"))
+ except (FileNotFoundError, UnicodeDecodeError, json.JSONDecodeError):
+ config_payload = {}
+ if isinstance(config_payload, dict):
+ migrated, _, _ = _migrate_config_payload_on_load(config_payload)
+ config = V2Config._recover_payload(migrated)
+ else:
+ config = V2Config.default()
+ discord = config.discord
+ allowed = getattr(discord, "guild_allowlist", None) or []
+ denied = getattr(discord, "guild_denylist", None) or []
+ default = not bool(allowed)
+ entries = {str(key): True for key in allowed}
+ entries.update({str(key): False for key in denied})
+ legacy_guilds = default, {
+ _make_scoped_key("discord", key): enabled
+ for key, enabled in entries.items() if enabled != default
+ }
+
+ def members(state):
+ return {
+ key: (user.is_admin, user.enabled, user.bound_at, user.dm_chat_id)
+ for key, user in state.users.items()
+ }
+
+ def guild_policy(state, platform):
+ if platform == "discord" and platform not in state.guild_scope_platforms:
+ return legacy_guilds
+ default = (
+ bool(state.guild_default_enabled.get(platform, False))
+ if platform in state.guild_scope_platforms else True
+ )
+ exceptions = {
+ key: bool(guild.enabled)
+ for key, guild in state.guilds.items()
+ if _split_scoped_key(key)[0] == platform and bool(guild.enabled) != default
+ }
+ return default, exceptions
+
+ def binding(state, key, *, thread=False):
+ if thread:
+ item = state.threads.get(key)
+ if item is not None:
+ return bool(item.require_bind)
+ platform, native_id = _split_scoped_key(key)
+ channel_id, _ = split_thread_native_id(native_id)
+ key = _make_scoped_key(platform, channel_id) if platform else channel_id
+ item = state.channels.get(key)
+ # Channel None/False is open; the platform flag only seeds new channels.
+ return bool(item and item.require_bind)
+
+ changed = members(current) != members(candidate) or current.bind_codes != candidate.bind_codes
+ platforms = current.guild_scope_platforms | candidate.guild_scope_platforms
+ changed = changed or any(guild_policy(current, p) != guild_policy(candidate, p) for p in platforms)
+ changed = changed or any(
+ binding(current, key) != binding(candidate, key)
+ for key in current.channels.keys() | candidate.channels.keys()
+ )
+ changed = changed or any(
+ binding(current, key, thread=True) != binding(candidate, key, thread=True)
+ for key in current.threads.keys() | candidate.threads.keys()
+ )
+ if changed:
+ raise InstanceAuthorizationError("owner")
+
+
class StaleScopeAgentBindingError(ValueError):
code = "settings_conflict"
@@ -65,20 +176,42 @@ class SQLiteSettingsService:
def load_state(self) -> SettingsState:
with self.engine.connect() as conn:
- return SettingsState(
- channels=self._load_channels(conn),
- threads=self._load_threads(conn),
- guilds=self._load_guilds(conn),
- guild_scope_platforms=self._load_guild_scope_platforms(conn),
- guild_default_enabled=self._load_guild_policies(conn),
- users=self._load_users(conn),
- bind_codes=self._load_bind_codes(conn),
- )
+ return self._load_state(conn)
+
+ def _load_state(self, conn: Connection) -> SettingsState:
+ return SettingsState(
+ channels=self._load_channels(conn),
+ threads=self._load_threads(conn),
+ guilds=self._load_guilds(conn),
+ guild_scope_platforms=self._load_guild_scope_platforms(conn),
+ guild_default_enabled=self._load_guild_policies(conn),
+ users=self._load_users(conn),
+ bind_codes=self._load_bind_codes(conn),
+ )
+
+ def save_state(
+ self, state: SettingsState, *, user_context: Any = None, baseline: SettingsState | None = None
+ ) -> str:
+ from vibe.authorization import require_instance_role
- def save_state(self, state: SettingsState) -> str:
+ # General config still accepts Editor preferences and may round-trip
+ # the legacy Discord scope projection. HTTP/API management callers
+ # require Member before entering; every non-owner preserves access here.
+ context = require_instance_role(user_context, "editor")
+ draft = state
saved_bindings: list[tuple[ChannelSettings | UserSettings, RoutingSettings]] = []
with self.engine.begin() as conn:
reserve_write_lock(conn)
+ current = self._load_state(conn)
+ if baseline is not None and not context.can_manage_access_members:
+ # A protected-field echo may equal the loaded value but no
+ # longer equal the authoritative value. Reject that stale
+ # snapshot before delta merging could silently drop the echo.
+ _require_preserved_access_policy(current, baseline)
+ if baseline is not None:
+ state = _merge_settings_changes(current, draft, baseline)
+ if not context.can_manage_access_members:
+ _require_preserved_access_policy(current, state)
now = _utc_now_iso()
# Per-row reconcile (NOT a delete-everything rewrite): upsert each
# managed scope's settings, then delete only the managed rows that
@@ -243,6 +376,9 @@ class SQLiteSettingsService:
for item, routing in saved_bindings:
item.routing = routing
item._agent_name_at_load = routing.agent_name
+ # Publish the committed snapshot only after the transaction succeeds.
+ for field in fields(SettingsState):
+ setattr(draft, field.name, getattr(state, field.name))
return revision
@staticmethod
diff --git a/storage/vault_service.py b/storage/vault_service.py
index ea0f77c24..2b5a324df 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -1816,7 +1816,7 @@ def _require_secret_resource_management(conn: Connection, row: dict[str, Any], u
from storage import resource_access_service
context = resolve_resource_access_context(user_context)
- if not context.is_instance_owner:
+ if not context.can_manage_instance:
raise VaultSecretAccessError("Vault secret access is not permitted.")
resource_id = str(row.get("id") or "")
if not resource_id or not resource_access_service.can_manage_resource_acl(
diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.json
new file mode 100644
index 000000000..31556c12c
--- /dev/null
+++ b/tests/fixtures/member_management_existing_read_roles.json
@@ -0,0 +1,155 @@
+{
+ "DELETE /api/dock/pins/example": "editor",
+ "DELETE /api/harness/tasks/example": "editor",
+ "DELETE /api/harness/watches/example": "editor",
+ "DELETE /api/sessions/example": "editor",
+ "DELETE /api/sessions/example/queue/example": "editor",
+ "DELETE /api/skills/example": "editor",
+ "DELETE /api/terminal/example": "viewer",
+ "DELETE /api/vault/grants/example": "editor",
+ "DELETE /api/vault/secrets/example": "editor",
+ "DELETE /api/web-push/subscriptions": "viewer",
+ "GET /api/agent-backends": "editor",
+ "GET /api/agents": "editor",
+ "GET /api/agents-graph": "editor",
+ "GET /api/agents/example": "editor",
+ "GET /api/asr/status": "editor",
+ "GET /api/browse/favorites": "editor",
+ "GET /api/claude/models": "editor",
+ "GET /api/cloud/token": "editor",
+ "GET /api/codex/models": "editor",
+ "GET /api/config": "viewer",
+ "GET /api/csrf-token": "viewer",
+ "GET /api/dock": "editor",
+ "GET /api/events": "viewer",
+ "GET /api/files/content": "editor",
+ "GET /api/files/list": "editor",
+ "GET /api/files/meta": "editor",
+ "GET /api/files/search": "editor",
+ "GET /api/files/search_names": "editor",
+ "GET /api/harness/bootstrap": "editor",
+ "GET /api/harness/counts": "editor",
+ "GET /api/harness/runs": "editor",
+ "GET /api/harness/runs/example": "editor",
+ "GET /api/harness/tasks": "editor",
+ "GET /api/harness/watches": "editor",
+ "GET /api/inbox": "viewer",
+ "GET /api/media/example": "viewer",
+ "GET /api/media/example/meta": "viewer",
+ "GET /api/memory/failures": "viewer",
+ "GET /api/memory/maintenance": "viewer",
+ "GET /api/memory/processing-record": "viewer",
+ "GET /api/memory/processing-record/entries": "viewer",
+ "GET /api/memory/processing-record/entry": "viewer",
+ "GET /api/memory/profile": "viewer",
+ "GET /api/memory/projects": "viewer",
+ "GET /api/memory/settings": "viewer",
+ "GET /api/memory/status": "viewer",
+ "GET /api/models/agents/example/models": "editor",
+ "GET /api/permissions": "viewer",
+ "GET /api/permissions/resources/example/example/access": "viewer",
+ "GET /api/platforms": "viewer",
+ "GET /api/projects": "viewer",
+ "GET /api/projects/example": "viewer",
+ "GET /api/running-agents": "editor",
+ "GET /api/search/messages": "viewer",
+ "GET /api/session": "viewer",
+ "GET /api/sessions": "viewer",
+ "GET /api/sessions/example": "viewer",
+ "GET /api/sessions/example/activity": "viewer",
+ "GET /api/sessions/example/archive-preview": "editor",
+ "GET /api/sessions/example/bootstrap": "viewer",
+ "GET /api/sessions/example/draft": "editor",
+ "GET /api/sessions/example/messages": "viewer",
+ "GET /api/sessions/example/queue": "editor",
+ "GET /api/sessions/example/turn-state": "viewer",
+ "GET /api/show-pages": "viewer",
+ "GET /api/show-pages/example": "editor",
+ "GET /api/show-pages/example/access": "viewer",
+ "GET /api/show-pages/example/icon": "viewer",
+ "GET /api/skills": "editor",
+ "GET /api/skills/check": "editor",
+ "GET /api/skills/find": "editor",
+ "GET /api/vault/agent/pubkey": "editor",
+ "GET /api/vault/audit": "editor",
+ "GET /api/vault/grants": "editor",
+ "GET /api/vault/provision-requests/by-id/example": "editor",
+ "GET /api/vault/provision-requests/example": "editor",
+ "GET /api/vault/pubkey": "editor",
+ "GET /api/vault/requests": "editor",
+ "GET /api/vault/requests/example": "editor",
+ "GET /api/vault/sandbox/root-metadata": "editor",
+ "GET /api/vault/secrets": "editor",
+ "GET /api/vault/settings": "editor",
+ "GET /api/vault/tags": "editor",
+ "GET /api/vault/vmk": "editor",
+ "GET /api/version": "viewer",
+ "GET /api/web-push/status": "viewer",
+ "GET /api/web-push/vapid-public-key": "viewer",
+ "GET /api/workbench/prefs": "viewer",
+ "GET /api/workbench/projects-bootstrap": "viewer",
+ "PATCH /api/harness/tasks/example": "editor",
+ "PATCH /api/harness/watches/example": "editor",
+ "PATCH /api/memory/settings": "viewer",
+ "PATCH /api/sessions/example": "editor",
+ "PATCH /api/vault/secrets/example": "editor",
+ "PATCH /api/vault/settings": "editor",
+ "POST /api/asr/telemetry": "editor",
+ "POST /api/asr/transcribe": "editor",
+ "POST /api/config": "editor",
+ "POST /api/dock/pins": "editor",
+ "POST /api/files/copy": "editor",
+ "POST /api/files/delete": "editor",
+ "POST /api/files/delete/undo": "editor",
+ "POST /api/files/mkdir": "editor",
+ "POST /api/files/move": "editor",
+ "POST /api/files/rename": "editor",
+ "POST /api/files/search/replace": "editor",
+ "POST /api/files/search/undo": "editor",
+ "POST /api/files/upload": "editor",
+ "POST /api/memory/delete-data": "viewer",
+ "POST /api/memory/list": "viewer",
+ "POST /api/memory/repair": "viewer",
+ "POST /api/memory/runtime/wake": "viewer",
+ "POST /api/memory/search": "viewer",
+ "POST /api/running-agents/end": "editor",
+ "POST /api/sessions": "editor",
+ "POST /api/sessions/example/attachments": "editor",
+ "POST /api/sessions/example/cancel": "editor",
+ "POST /api/sessions/example/cli-activity": "editor",
+ "POST /api/sessions/example/fork": "editor",
+ "POST /api/sessions/example/mark-read": "viewer",
+ "POST /api/sessions/example/messages": "editor",
+ "POST /api/sessions/example/queue/example/send-now": "editor",
+ "POST /api/show-pages/example/access-settings/apply": "editor",
+ "POST /api/show-pages/example/access-settings/read": "editor",
+ "POST /api/show-pages/example/availability": "editor",
+ "POST /api/show-pages/example/ensure": "editor",
+ "POST /api/show-pages/example/icon": "editor",
+ "POST /api/show/sessions/example/events": "editor",
+ "POST /api/show/sessions/example/prewarm": "editor",
+ "POST /api/skills": "editor",
+ "POST /api/skills/preview": "editor",
+ "POST /api/skills/update": "editor",
+ "POST /api/skills/upload": "editor",
+ "POST /api/vault/agent-binding": "editor",
+ "POST /api/vault/agent-bindings:batch": "editor",
+ "POST /api/vault/authz/factors/webauthn": "editor",
+ "POST /api/vault/authz/factors/webauthn/options": "editor",
+ "POST /api/vault/grants": "editor",
+ "POST /api/vault/pubkey-pin": "editor",
+ "POST /api/vault/requests/access": "editor",
+ "POST /api/vault/requests/example/deny": "editor",
+ "POST /api/vault/requests/example/fulfill-access": "editor",
+ "POST /api/vault/requests/sign": "editor",
+ "POST /api/vault/secrets": "editor",
+ "POST /api/vault/secrets/example/reveal-context": "editor",
+ "POST /api/vault/sign": "editor",
+ "POST /api/vault/signing-addresses": "editor",
+ "POST /api/web-push/status": "viewer",
+ "POST /api/web-push/subscriptions": "viewer",
+ "POST /api/web-push/test": "viewer",
+ "PUT /api/dock/order": "editor",
+ "PUT /api/files/write": "editor",
+ "PUT /api/sessions/example/draft": "editor"
+}
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 1dd099e7a..bd34caeac 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -303,4 +303,11 @@ scenarios:
layer: scenario
backend: codex
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_codex_connection_probe_reuses_persistent_app_server
+ - id: AUTH-SETUP-301
+ name: Instance Member saves backend credentials through signed remote HTTP
+ status: covered
+ kind: authorization
+ layer: scenario
+ backend: claude
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_instance_manager_backend_credentials_round_trip
next_priority: []
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 6701d7629..8629bfeb3 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -3314,3 +3314,46 @@ def test_custom_auto_policy_response_cannot_reject_or_exclude_credentials(
if __name__ == "__main__":
unittest.main()
+
+
[email protected]("role", ["member", "owner"])
+def test_instance_manager_backend_credentials_round_trip(monkeypatch, tmp_path, role):
+ """AUTH-SETUP-301: signed remote management reaches native credential storage."""
+ import json
+ from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_peer, remote_session_cookie
+ from vibe import api, remote_access
+ from vibe.ui_server import app
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
+ client = app.test_client()
+ base_url = "https://alex.avibe.bot"
+ client.set_cookie(remote_access.SESSION_COOKIE_NAME, remote_session_cookie(
+ config, f"{role}@example.com", role, role=role, access_source="organization_group",
+ organization_id="org-1", organization_member_id=f"membership-{role}",
+ organization_role="member", group_ids=[],
+ ), domain="alex.avibe.bot")
+ headers = csrf_headers(client, base_url=base_url)
+
+ def request(method, path, *, payload=None):
+ return client.request(method, path, json=payload, headers=headers, base_url=base_url, environ_base=remote_peer())
+ from vibe import claude_config
+ native_dir = tmp_path / "test-claude"
+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(native_dir))
+ monkeypatch.setattr(api, "_get_oauth_service", lambda: object())
+ monkeypatch.setattr(api, "_clear_claude_oauth_credentials_after_api_key_save", lambda service: {"ok": True})
+ monkeypatch.setattr(api, "_read_claude_cli_oauth_signed_in", lambda *a, **kw: False)
+ monkeypatch.setattr(claude_config, "read_claude_oauth_signed_in", lambda: False)
+ refreshed = []
+ monkeypatch.setattr(api, "restart_backend", lambda name, **kw: refreshed.append(name) or {"ok": True})
+ response = request("POST", "/api/backend/claude/auth", payload={
+ "auth_mode": "api_key", "api_key": "isolated-test-credential", "base_url": "https://provider.invalid",
+ })
+ assert response.status_code == 200, response.get_json()
+ assert response.get_json()["ok"], response.get_json()
+ saved = json.loads((native_dir / "settings.json").read_text())
+ assert saved["env"]["ANTHROPIC_API_KEY"] == "isolated-test-credential"
+ assert refreshed == ["claude"]
+ readback = request("GET", "/api/backend/claude/auth")
+ assert readback.status_code == 200
+ assert "isolated-test-credential" not in json.dumps(readback.get_json())
diff --git a/tests/scenarios/permissions/catalog.yaml b/tests/scenarios/permissions/catalog.yaml
index 169bf82c1..850a8e91e 100644
--- a/tests/scenarios/permissions/catalog.yaml
+++ b/tests/scenarios/permissions/catalog.yaml
@@ -5,6 +5,7 @@ capability:
canonical_tests:
- tests/scenarios/permissions/test_permissions_scenarios.py
- tests/test_permissions.py
+ - tests/test_member_management_parity.py
status_legend:
covered: scenario coverage exists
partial: unit or contract coverage exists but the closed loop is incomplete
@@ -119,3 +120,13 @@ scenarios:
given: A paired Instance Owner calls the retired show_page Resource ACL endpoint
when: The local boundary validates the resource kind before any Backend contact
then: Both read and write are rejected as invalid_resource_kind with no Backend request
+
+ - id: PERMISSIONS-013
+ name: Instance Member manages settings while preserving access administration
+ status: covered
+ kind: authorization
+ layer: scenario
+ test: tests/test_member_management_parity.py::test_member_channel_and_dm_preferences_preserve_access_state
+ given: A signed Organization instance Member and existing bound users and channels
+ when: The Member saves channel operation and DM preferences and attempts access mutations
+ then: Ordinary writes persist while user creation, role changes and reactivation are refused without mutation
diff --git a/tests/test_delete_channel_scope.py b/tests/test_delete_channel_scope.py
index 3943c08d6..42ba2b861 100644
--- a/tests/test_delete_channel_scope.py
+++ b/tests/test_delete_channel_scope.py
@@ -7,7 +7,7 @@ from vibe import api
def test_delete_channel_scope_rejects_non_channel_scope(monkeypatch) -> None:
calls: list[tuple] = []
- def fake_delete_scope(platform, native_id, *, scope_type="channel", db_path=None):
+ def fake_delete_scope(platform, native_id, *, scope_type="channel", db_path=None, user_context=None):
calls.append((platform, native_id, scope_type))
return {"removed": True, "dismissed": False}
@@ -22,7 +22,7 @@ def test_delete_channel_scope_rejects_non_channel_scope(monkeypatch) -> None:
def test_delete_channel_scope_allows_channel(monkeypatch) -> None:
calls: list[tuple] = []
- def fake_delete_scope(platform, native_id, *, scope_type="channel", db_path=None):
+ def fake_delete_scope(platform, native_id, *, scope_type="channel", db_path=None, user_context=None):
calls.append((platform, native_id, scope_type))
return {"removed": True, "dismissed": False}
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 073445597..ff2aaa50c 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -217,7 +217,7 @@ def test_http_policy_is_role_only_and_unknown_api_routes_fail_closed() -> None:
for method, path in editor_routes:
assert http_authorization_policy(method, path).minimum_role == "editor"
- for method, path in (("GET", "/api/future-owner-capability"), ("POST", "/api/control")):
+ for method, path in (("GET", "/api/future-owner-capability"), ("DELETE", "/api/control")):
assert http_authorization_policy(method, path).minimum_role == "owner"
assert (
@@ -226,9 +226,9 @@ def test_http_policy_is_role_only_and_unknown_api_routes_fail_closed() -> None:
)
assert http_authorization_policy("GET", "/show/ses-1/").minimum_role == "viewer"
assert http_authorization_policy("POST", "/api/remote-access/vibe-cloud/pair").minimum_role == "owner"
- assert http_authorization_policy("POST", "/api/remote-access/start").minimum_role == "owner"
- assert http_authorization_policy("POST", "/api/remote-access/stop").minimum_role == "owner"
- assert http_authorization_policy("POST", "/api/remote-access/settings").minimum_role == "owner"
+ assert http_authorization_policy("POST", "/api/remote-access/start").minimum_role == "member"
+ assert http_authorization_policy("POST", "/api/remote-access/stop").minimum_role == "member"
+ assert http_authorization_policy("POST", "/api/remote-access/settings").minimum_role == "member"
assert http_authorization_policy("POST", "/api/remote-access/future-unpair").minimum_role == "owner"
assert http_authorization_policy("GET", "/api/remote-access/status").minimum_role == "member"
@@ -341,48 +341,26 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("GET", "/api/remote-access/network-interfaces"),
("POST", "/api/remote-access/optimize-route"),
("POST", "/api/remote-access/diagnostics"),
+ ("POST", "/api/remote-access/start"),
+ ("POST", "/api/remote-access/stop"),
+ ("POST", "/api/remote-access/settings"),
)
for method, path in member_examples:
assert http_authorization_policy(method, path).minimum_role == "member", path
owner_examples = (
- # Unknown APIs, present and future, keep the role they had before the
- # member rank existed.
("GET", "/api/future-owner-capability"),
- ("POST", "/api/control"),
- ("POST", "/api/upgrade"),
- ("POST", "/api/logs"),
- # Classifying the read-only catalogs above does not widen /api/backend:
- # credential, custom-provider, install, and runtime routes keep Owner by
- # the unknown-route default. That includes OpenCode's provider catalog --
- # it is the Settings surface (base URLs, masked keys, active auth type,
- # tool-call permission state) and reading it starts the daemon, so unlike
- # the Claude and Codex snapshots it is not a catalog a lower rank may
- # read. The model picker treats its 403 as "no catalog".
- ("GET", "/api/backend/opencode/providers"),
- ("POST", "/api/backend/codex/auth"),
- ("POST", "/api/backend/claude/auth"),
- ("POST", "/api/backend/opencode/auth"),
- ("DELETE", "/api/backend/opencode/auth/anthropic"),
- ("POST", "/api/backend/opencode/providers"),
("POST", "/api/backend/opencode/future-mutation"),
- ("POST", "/api/claude/models/refresh"),
("POST", "/api/codex/future-mutation"),
- # Access administration and bearer credentials.
("PUT", "/api/permissions/authorized-users"),
("GET", "/api/users/bind-codes"),
("POST", "/api/users/first-bind-code"),
- # ACL writes and the IM access boundary.
("PUT", "/api/permissions/projects/project-1/access"),
("PUT", "/api/permissions/resources/agent/agent-1/access"),
- ("POST", "/api/settings"),
- ("POST", "/api/settings/thread"),
- # Host reach.
- ("POST", "/api/browse"),
- ("POST", "/api/browse/mkdir"),
- # Bulk migration.
("GET", "/api/agent-onboarding"),
("POST", "/api/agent-onboarding"),
+ ("POST", "/api/wechat/qr_login/start"),
+ ("POST", "/api/wechat/qr_login/poll"),
)
for method, path in owner_examples:
assert http_authorization_policy(method, path).minimum_role == "owner", path
@@ -393,6 +371,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("GET", r"^/api/remote-access/network-interfaces$"),
("POST", r"^/api/remote-access/optimize-route$"),
("POST", r"^/api/remote-access/diagnostics$"),
+ ("POST", r"^/api/remote-access/(?:start|stop|settings)$"),
}
@@ -409,7 +388,7 @@ def test_member_reachable_routes_are_bounded_by_declaration() -> None:
So the fallback is Owner and the member surface is the allow-list, and this
is the property that replaces those exceptions: every registered ``/api``
route resolves to an explicit tier; a route resolves to member only because
- ``_MEMBER_HTTP_RULES`` or the remote-access ops quartet says so; and a route
+ ``_MEMBER_HTTP_RULES`` or the explicit remote-access operations says so; and a route
the router does not have yet resolves to Owner. A management route added
tomorrow therefore keeps exactly the role it would have had before this rank
existed.
@@ -467,11 +446,8 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()
route picker shares the catalog loader and is an editor surface, so editor is
the floor for the catalogs; the rest of the page is member management.
- OpenCode is the exception the test also pins. It has no catalog separable
- from its Settings surface, so its read stays Owner and the picker degrades to
- a typed model id -- silently, because the loader declares that refusal
- expected. "Completes its load" therefore means "issues no request whose 403
- the user is told about", not "every backend answers".
+ OpenCode provider management is available to Member; Editor retains its
+ existing typed-model fallback.
"""
page_load_reads = (
@@ -498,15 +474,11 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()
for method, path in (*page_load_reads, *catalog_reads):
minimum_role = http_authorization_policy(method, path).minimum_role
assert minimum_role is not None and context.has_role(minimum_role), f"{role} {path}"
- # The counterparts a member page load must not announce. Bulk onboarding is a
- # one-way instance-wide migration and must not be requested at all; the
- # OpenCode provider catalog may be requested but its refusal is expected data
- # for the picker. Both stay Owner, so a toast from either is a UI defect
- # rather than a policy gap.
+ assert http_authorization_policy("GET", "/api/backend/opencode/providers").minimum_role == "member"
+ # Bulk onboarding claims ownership and remains Owner-only.
owner_only_page_neighbours = (
("GET", "/api/agent-onboarding"),
("POST", "/api/agent-onboarding"),
- ("GET", "/api/backend/opencode/providers"),
)
for method, path in owner_only_page_neighbours:
minimum_role = http_authorization_policy(method, path).minimum_role
@@ -533,7 +505,57 @@ def test_backend_catalog_surface_follows_the_agent_management_boundary() -> None
("DELETE", "/api/models/sources/src-1/models/model-1"),
)
for method, source_path in source_model_mutations:
- assert http_authorization_policy(method, source_path).minimum_role == "owner"
+ assert http_authorization_policy(method, source_path).minimum_role == "member"
+
+
+def test_all_registered_model_hub_routes_follow_instance_management_roles() -> None:
+ """Inventory the live API independently of the authorization allow-list."""
+ from vibe.ui_server import app
+
+ endpoints = {
+ (method, _sample_path(route.path))
+ for route in app.routes
+ if getattr(route, "path", "").startswith("/api/models/")
+ for method in route.methods or ()
+ }
+ assert len(endpoints) >= 40
+ for method, path in endpoints:
+ picker = method == "GET" and re.fullmatch(r"/api/models/agents/[^/]+/models", path)
+ minimum_role = http_authorization_policy(method, path).minimum_role
+ assert minimum_role == ("editor" if picker else "member"), (method, path)
+ for kind in ("personal", "organization"):
+ for organization_role in ("owner", "admin", "member", None):
+ for role in ("owner", "member", "editor", "viewer", None):
+ context = AuthorizationContext(
+ instance_role=role,
+ instance_kind=kind,
+ organization_role=organization_role,
+ is_remote=True,
+ )
+ expected = role in {"owner", "member"} or bool(picker and role == "editor")
+ assert context.has_role(minimum_role) is expected, (
+ kind, organization_role, role, method, path,
+ )
+
+
[email protected]("method", ["GET", "POST", "PUT", "PATCH", "DELETE"])
+def test_model_hub_unknown_siblings_remain_owner_only(method: str) -> None:
+ for path in (
+ "/api/models/future-management",
+ "/api/models/runtime/future-operation",
+ "/api/models/oauth/future-operation",
+ "/api/models/migration/future-operation",
+ "/api/models/sources/src-1/future-operation",
+ "/api/models/agents/claude/future-operation",
+ ):
+ assert http_authorization_policy(method, path).minimum_role == "owner"
+
+
[email protected]("method", ["PATCH", "DELETE"])
+def test_model_hub_source_model_ids_can_contain_slashes(method: str) -> None:
+ assert http_authorization_policy(
+ method, "/api/models/sources/src-1/models/provider/模型",
+ ).minimum_role == "member"
def test_workbench_events_follow_role_boundaries() -> None:
@@ -622,6 +644,9 @@ _REMOTE_ACCESS_MEMBER_OPS = frozenset(
("GET", "/api/remote-access/network-interfaces"),
("POST", "/api/remote-access/optimize-route"),
("POST", "/api/remote-access/diagnostics"),
+ ("POST", "/api/remote-access/start"),
+ ("POST", "/api/remote-access/stop"),
+ ("POST", "/api/remote-access/settings"),
}
)
@@ -727,7 +752,7 @@ def test_registered_remote_access_writes_default_to_owner(monkeypatch, tmp_path)
Introspect the live router so a newly added pair/unpair/settings sibling
fails this test until it is classified. Viewer and editor stay 403 on the
- whole namespace, matching master. Member keeps the four ops that cannot
+ whole namespace, matching master. Member keeps the operations that cannot
change pairing identity.
"""
@@ -791,11 +816,10 @@ _ACCESS_ADMINISTRATION_NAMESPACES = (
"/api/agent-onboarding",
)
-# The only route in those namespaces allowed below Owner: it discloses the member
-# set without disclosing or minting a credential, matching the cloud allowlist
-# whose GET is member and whose PUT is Owner. Everything else registered in the
-# namespaces now or later must be Owner, which is what the sweep asserts.
-_ACCESS_ADMINISTRATION_MEMBER_READS = frozenset({("GET", "/api/users")})
+# Members may read users and update ordinary existing-user preferences. The
+# locked writer independently rejects membership effects in POST /api/users.
+# Other routes in these namespaces remain Owner-only.
+_ACCESS_ADMINISTRATION_MEMBER_SETTINGS = frozenset({("GET", "/api/users"), ("POST", "/api/users")})
def _registered_access_administration_routes():
@@ -869,7 +893,7 @@ def test_registered_access_administration_routes_are_owner_only(monkeypatch, tmp
for method, path in routes:
policy = http_authorization_policy(method, _sample_path(path))
- if (method, path) in _ACCESS_ADMINISTRATION_MEMBER_READS:
+ if (method, path) in _ACCESS_ADMINISTRATION_MEMBER_SETTINGS:
assert policy.minimum_role == "member", f"{method} {path}"
else:
assert policy.minimum_role == "owner", f"{method} {path} must be Owner-only"
@@ -907,24 +931,8 @@ def test_registered_access_administration_routes_are_owner_only(monkeypatch, tmp
assert response.get_json()["error"] == "instance_access_forbidden"
-def test_agent_cli_install_is_owner_only(monkeypatch, tmp_path) -> None:
- """Installing a backend CLI is host lifecycle, so it stays above member.
-
- The handler shells out to a package manager, a self-update, or a curl
- script, records the resulting CLI path, and can restart the backend. That is
- the "dependency installs" bullet the member policy declares Owner, and it
- had been on the member allow-list while the comment above that table said
- otherwise -- the table is hand-written, so the policy and its entries can
- disagree silently.
-
- Enforcement is by absence: neither route is declared, so both inherit the
- unknown-route Owner default and need no exception entry. Asserting the
- absence *and* the 403 it produces keeps those two from drifting apart, and
- the owner leg proves the routes are still live rather than unreachable for
- everyone. The install implementation is stubbed, so no package manager runs
- and the assertion at the end is what proves it: only the owner leg ever
- reached the handler.
- """
+def test_agent_cli_install_follows_instance_management(monkeypatch, tmp_path) -> None:
+ """Both managers reach the host operation; Editor/Viewer cannot."""
from tests.ui_server_test_helpers import (
csrf_headers,
@@ -956,11 +964,7 @@ def test_agent_cli_install_is_owner_only(monkeypatch, tmp_path) -> None:
("GET", "/api/agent/claude/install/job-1"),
)
for method, path in routes:
- assert not any(
- rule_method == method and pattern.fullmatch(path)
- for rule_method, pattern in _MEMBER_HTTP_RULES
- ), f"{method} {path} must not be declared on the member allow-list"
- assert http_authorization_policy(method, path).minimum_role == "owner", f"{method} {path}"
+ assert http_authorization_policy(method, path).minimum_role == "member"
for role in ("viewer", "editor", "member", "owner"):
client = app.test_client()
@@ -985,15 +989,15 @@ def test_agent_cli_install_is_owner_only(monkeypatch, tmp_path) -> None:
if method != "GET":
kwargs["json"] = {}
response = client.request(method, path, **kwargs)
- if role == "owner":
+ if role in {"owner", "member"}:
assert response.status_code == 200, f"{role} {method} {path}"
assert response.get_json()["ok"] is True, f"{role} {method} {path}"
else:
assert response.status_code == 403, f"{role} {method} {path}"
assert response.get_json()["error"] == "instance_access_forbidden"
- assert reached == [("start", "claude"), ("status", "job-1")], (
- "only the owner leg may reach the install handler"
+ assert reached == [("start", "claude"), ("status", "job-1")] * 2, (
+ "only manager legs may reach the install handler"
)
@@ -1040,7 +1044,7 @@ def test_access_administration_handlers_gate_without_the_route_policy(monkeypatc
)
headers = csrf_headers(client, base_url="https://alex.avibe.bot")
for method, path in _registered_access_administration_routes():
- if (method, path) in _ACCESS_ADMINISTRATION_MEMBER_READS:
+ if (method, path) in _ACCESS_ADMINISTRATION_MEMBER_SETTINGS:
continue
request_path = _sample_path(path)
kwargs = {
@@ -1079,10 +1083,8 @@ def test_member_config_write_cannot_change_pairing_identity(
) -> None:
"""Member POST /api/config cannot change pairing identity in any value shape.
- The refusal is the Editor allowlist, which every writer below Owner now runs:
- ``remote_access`` is not a field they may set, so the write is rejected
- outright rather than accepted with one key quietly removed. Stored pairing is
- asserted unchanged either way — the point is the identity, not the status code.
+ Compare protected access effects at the locked writer, including malformed
+ replacement shapes. No refusal may mutate the stored pairing.
"""
from config.v2_config import V2Config
@@ -1129,11 +1131,7 @@ def test_member_config_write_cannot_change_pairing_identity(
environ_base=remote_peer(),
)
- assert response.status_code == 400
- assert response.get_json()["error"] == {
- "code": "editor_config_write_forbidden",
- "message": "editor_config_write_forbidden",
- }
+ assert response.status_code in {400, 403}
after = V2Config.load().remote_access.vibe_cloud
assert after.instance_id == before.instance_id == "inst_123"
assert after.backend_url == before.backend_url == "https://backend.example"
@@ -1293,9 +1291,8 @@ def test_member_can_set_instance_default_agent(monkeypatch, tmp_path) -> None:
domain="alex.avibe.bot",
)
owner_headers = csrf_headers(owner_client, base_url="https://alex.avibe.bot")
- # Owner-only is the whole gate. The same Agent the member could not publish
- # is accepted from the Owner, because the target's audience is a use-time
- # question rather than a bind-time one.
+ # Owner retains the same management operation; target audience remains a
+ # use-time decision rather than a bind-time restriction.
owner_response = owner_client.post(
"/api/agents/default",
json={"name": "member-private"},
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
new file mode 100644
index 000000000..8a24b68da
--- /dev/null
+++ b/tests/test_member_management_parity.py
@@ -0,0 +1,815 @@
+"""Instance management preserves admission policy through real remote HTTP writes.
+
+Scenario: PERMISSIONS-013. All persistent state belongs to pytest's home;
+only provider/host/runtime effects are stubbed, after the authorization seam.
+"""
+
+from __future__ import annotations
+
+import copy
+import contextlib
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from config import paths
+from config.v2_config import V2Config
+from config.v2_settings import BindCode, ChannelSettings, GuildSettings, SettingsStore, UserSettings
+from storage.importer import ensure_sqlite_state
+from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_peer, remote_session_cookie
+from vibe import api, internal_client, remote_access, ui_server
+from vibe.authorization import AuthorizationContext, InstanceAuthorizationError, http_authorization_policy
+
+BASE_URL = "https://alex.avibe.bot"
+MEMBER = AuthorizationContext(
+ instance_role="member",
+ subject="manager",
+ instance_access_source="organization_group",
+ instance_kind="organization",
+ organization_id="org-1",
+ organization_member_id="membership-manager",
+ organization_role="member",
+ group_ids=frozenset(),
+ is_remote=True,
+)
+
+
+def management_http(tmp_path, monkeypatch):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
+ ensure_sqlite_state()
+ SettingsStore.reset_instance()
+
+ async def reconciled(*args, **kwargs):
+ return {"status_code": 200, "body": {"ok": True}}
+
+ monkeypatch.setattr(internal_client, "reconcile_platforms", reconciled)
+ monkeypatch.setattr(internal_client, "reconcile_agent_backends", reconciled)
+ monkeypatch.setattr(ui_server, "_ensure_remote_access_monitoring", lambda *args: None)
+
+ def connect(role="member", *, organization_role="member", authenticated=True):
+ client = ui_server.app.test_client()
+ if authenticated:
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ f"{role}@example.com",
+ role,
+ role=role,
+ access_source="owner" if role == "owner" else "organization_group",
+ organization_id="org-1",
+ organization_member_id=f"membership-{role}",
+ organization_role=organization_role,
+ group_ids=[],
+ ),
+ domain="alex.avibe.bot",
+ )
+ headers = csrf_headers(client, base_url=BASE_URL)
+
+ def request(method, route, *, payload=None, csrf=True, origin=None):
+ request_headers = dict(headers) if csrf else {}
+ if origin is not None:
+ request_headers["Origin"] = origin
+ return client.request(
+ method,
+ route,
+ json=payload,
+ headers=request_headers,
+ base_url=BASE_URL,
+ environ_base=remote_peer(),
+ )
+
+ return request
+
+ yield connect
+ SettingsStore.reset_instance()
+
+
+# This inventory describes retained effects independently of the policy rules.
+# A newly registered Owner-only management route must be consciously classified.
+_RETAINED_OWNER_ROUTES = {
+ ("POST", "/api/model-service/refresh"), # Internal signed CLI notification, not a settings API.
+ ("PUT", "/api/permissions/authorized-users"),
+ ("PUT", "/api/permissions/projects/{project_id}/access"),
+ ("PUT", "/api/permissions/resources/{resource_kind}/{resource_id}/access"),
+ ("GET", "/api/agent-onboarding"),
+ ("POST", "/api/agent-onboarding"),
+ ("POST", "/api/remote-access/vibe-cloud/pair"),
+ ("POST", "/api/wechat/qr_login/start"),
+ ("POST", "/api/wechat/qr_login/poll"),
+ ("POST", "/api/users/{user_id}/admin"),
+ ("DELETE", "/api/users/{user_id}"),
+ ("GET", "/api/bind-codes"),
+ ("POST", "/api/bind-codes"),
+ ("DELETE", "/api/bind-codes/{code}"),
+ ("GET", "/api/setup/first-bind-code"),
+}
+
+
+def test_complete_registered_api_management_inventory():
+ endpoints = {
+ (method, route.path)
+ for route in ui_server.app.routes
+ if getattr(route, "path", "").startswith("/api/")
+ for method in (getattr(route, "methods", None) or ())
+ if method not in {"HEAD", "OPTIONS"}
+ }
+ assert len(endpoints) == 291
+ # Frozen from 1b191200c: independently protect all existing lower-tier grants.
+ baseline_read_roles = json.loads(
+ (Path(__file__).parent / "fixtures/member_management_existing_read_roles.json").read_text()
+ )
+ actual_read_roles = {}
+ owners = {
+ (method, raw)
+ for method, raw in endpoints
+ if http_authorization_policy(method, re.sub(r"\{[^}]+\}", "example", raw)).minimum_role == "owner"
+ }
+ assert owners == _RETAINED_OWNER_ROUTES
+ for method, raw in endpoints:
+ path = re.sub(r"\{[^}]+\}", "example", raw)
+ minimum = http_authorization_policy(method, path).minimum_role
+ if minimum in {"viewer", "editor"}:
+ actual_read_roles[f"{method} {path}"] = minimum
+ for kind in ("personal", "organization"):
+ for role in ("owner", "member", "editor", "viewer", None):
+ context = AuthorizationContext(
+ instance_role=role,
+ instance_kind=kind,
+ organization_role="owner",
+ is_remote=True,
+ )
+ if role in {"owner", "member"}:
+ assert context.has_role(minimum) == (role == "owner" or (method, raw) not in _RETAINED_OWNER_ROUTES)
+ if role in {"editor", "viewer"}:
+ old_minimum = baseline_read_roles.get(f"{method} {path}")
+ expected = old_minimum == "viewer" or (old_minimum == "editor" and role == "editor")
+ assert context.has_role(minimum) is expected, (role, method, path)
+ if role is None:
+ assert not context.has_role(minimum), (method, raw)
+ assert actual_read_roles == baseline_read_roles
+
+
[email protected]("role", ["member", "owner"])
+def test_manager_saves_config_credentials_and_reads_masked_result(management_http, role):
+ request = management_http(role)
+ before = V2Config.load().remote_access
+ response = request(
+ "POST",
+ "/api/config",
+ payload={
+ "slack": {"bot_token": "xoxb-test-member-token", "app_token": "xapp-test-member-token"},
+ "runtime": {"log_level": "DEBUG"},
+ },
+ )
+ assert response.status_code == 200, response.get_json()
+ saved = V2Config.load()
+ assert saved.slack.bot_token == "xoxb-test-member-token"
+ assert saved.runtime.log_level == "DEBUG"
+ assert saved.remote_access == before
+ response = request("GET", "/api/config")
+ assert response.status_code == 200
+ assert "xoxb-test-member-token" not in json.dumps(response.get_json())
+ assert response.get_json()["runtime"]["log_level"] == "DEBUG"
+
+
+ "payload",
+ [
+ {"slack": {"require_bind": True}},
+ {"telegram": {"allowed_user_ids": ["attacker"]}},
+ {"telegram": {"allowed_chat_ids": ["attacker"]}},
+ {"ui": {"trusted_public_origins": ["https://attacker.example"]}},
+ {"remote_access": {"vibe_cloud": {"instance_id": "other"}}},
+ {"__avibe_list_ops": {"telegram.allowed_user_ids": {"add": ["attacker"]}}},
+ {"discord": {"guild_allowlist": ["attacker"]}},
+ ],
+)
+def test_member_generic_config_protects_access_fields(management_http, payload):
+ request = management_http()
+ before = paths.get_config_path().read_bytes()
+ response = request("POST", "/api/config", payload=payload)
+ assert response.status_code in {400, 403}, response.get_json()
+ assert paths.get_config_path().read_bytes() == before
+
+
+def test_legacy_discord_admission_survives_member_credential_migration(management_http):
+ request = management_http()
+ config_payload = json.loads(paths.get_config_path().read_text())
+ config_payload["discord"] = {"bot_token": "test-token", "guild_denylist": ["blocked"]}
+ paths.get_config_path().write_text(json.dumps(config_payload))
+ response = request("POST", "/api/config", payload={"discord": {"bot_token": "new-test-token"}})
+ assert response.status_code == 200, response.get_json()
+ store = SettingsStore.get_instance()
+ assert not store.is_guild_enabled("discord", "blocked")
+ assert store.is_guild_enabled("discord", "other")
+ response = request("POST", "/api/config", payload={"discord": {"guild_denylist": []}})
+ assert response.status_code == 403, response.get_json()
+ assert not store.is_guild_enabled("discord", "blocked")
+
+
+def test_member_config_equal_protected_echo_is_valid_but_omission_cannot_reset(management_http):
+ request = management_http()
+ config = V2Config.load()
+ config.slack.require_bind = True
+ config.save()
+ assert (
+ request("POST", "/api/config", payload={"slack": {"require_bind": True}, "language": "zh"}).status_code == 200
+ )
+ assert request("POST", "/api/config", payload={"runtime": {"log_level": "DEBUG"}}).status_code == 200
+ assert V2Config.load().slack.require_bind
+ assert request("POST", "/api/config", payload={"slack": None}).status_code == 403
+ assert V2Config.load().slack.require_bind
+
+
[email protected]("role", ["editor", "viewer"])
+def test_organization_owner_does_not_supply_instance_management(management_http, role):
+ request = management_http(role, organization_role="owner")
+ before = paths.get_config_path().read_bytes()
+ response = request("POST", "/api/config", payload={"runtime": {"log_level": "DEBUG"}})
+ assert response.status_code in {400, 403}
+ assert request("PUT", "/api/workbench/prefs", payload={"background_work_banner_enabled": False}).status_code == 403
+ assert paths.get_config_path().read_bytes() == before
+
+
[email protected]("csrf,origin", [(False, None), (True, "https://attacker.example")])
+def test_member_csrf_still_precedes_management_effects(management_http, csrf, origin):
+ request = management_http()
+ before = paths.get_config_path().read_bytes()
+ response = request("POST", "/api/config", payload={"language": "zh"}, csrf=csrf, origin=origin)
+ assert response.status_code == 403
+ assert paths.get_config_path().read_bytes() == before
+
+
+def test_unauthenticated_remote_management_is_denied(management_http):
+ request = management_http(authenticated=False)
+ response = request("POST", "/api/config", payload={"language": "zh"})
+ assert response.status_code in {401, 403}
+
+
+def test_member_channel_and_dm_preferences_preserve_access_state(management_http):
+ store = SettingsStore.get_instance()
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=True)})
+ store.set_users_for_platform("telegram", {"bound": UserSettings(is_admin=True, enabled=False, bound_at="old")})
+ store.save()
+ request = management_http()
+ response = request(
+ "POST",
+ "/api/settings",
+ payload={
+ "platform": "telegram",
+ "channels": {"chat": {"enabled": False, "require_mention": False, "custom_cwd": "/tmp/ordinary"}},
+ },
+ )
+ assert response.status_code == 200, response.get_json()
+ assert not store.find_channel("chat", platform="telegram").enabled
+ assert store.find_channel("chat", platform="telegram").require_bind
+ response = request(
+ "POST",
+ "/api/users",
+ payload={"platform": "telegram", "users": {"bound": {"display_name": "成员", "custom_cwd": "/tmp/dm"}}},
+ )
+ assert response.status_code == 200, response.get_json()
+ user = store.get_user("bound", platform="telegram")
+ assert (user.is_admin, user.enabled, user.bound_at, user.custom_cwd) == (True, False, "old", "/tmp/dm")
+ readback = request("GET", "/api/users?platform=telegram").get_json()
+ assert readback["users"]["bound"]["display_name"] == "成员"
+ for patch in ({"new": {}}, {"bound": {"enabled": True}}, {"bound": {"is_admin": False}}):
+ assert request("POST", "/api/users", payload={"platform": "telegram", "users": patch}).status_code == 403
+ assert set(store.get_users_for_platform("telegram")) == {"bound"}
+ assert not store.get_user("bound", platform="telegram").enabled
+
+
+ "channels", [{}, {"chat": {}}, {"chat": {"require_bind": None}}, {"chat": {"require_bind": False}}]
+)
+def test_member_channel_replacement_preserves_binding_effect(management_http, channels):
+ store = SettingsStore.get_instance()
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=True)})
+ store.save()
+ response = management_http()("POST", "/api/settings", payload={"platform": "telegram", "channels": channels})
+ assert response.status_code == (200 if channels == {"chat": {}} else 403), response.get_json()
+ assert store.find_channel("chat", platform="telegram").require_bind
+
+
[email protected]("parent,override", [(True, False), (False, True), (True, True), (False, None)])
+def test_thread_deletion_compares_actual_parent_fallback(management_http, parent, override):
+ store = SettingsStore.get_instance()
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=parent)})
+ store.update_thread("chat", "7", ChannelSettings(require_bind=override), platform="telegram")
+ response = management_http()("DELETE", "/api/settings/thread?platform=telegram&channel_id=chat&thread_id=7")
+ assert response.status_code == (200 if parent == bool(override) else 403), response.get_json()
+
+
[email protected]("mutation", ["remove", "role", "disable"])
+def test_locked_member_save_cannot_undo_concurrent_membership_change(management_http, mutation):
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bound": UserSettings(bound_at="old")})
+ store.save()
+ stale = copy.deepcopy(store.settings)
+ if mutation == "remove":
+ store.set_users_for_platform("telegram", {})
+ else:
+ user = store.get_user("bound", platform="telegram")
+ if mutation == "role":
+ user.is_admin = True
+ else:
+ user.enabled = False
+ store.save()
+ fresh = store._service.load_state()
+ stale.users["telegram::bound"].custom_cwd = "/tmp/stale-preference"
+ with pytest.raises(InstanceAuthorizationError):
+ store._service.save_state(stale, user_context=MEMBER)
+ assert store._service.load_state() == fresh
+
+
+def test_member_guild_aliases_cannot_change_admission(management_http):
+ store = SettingsStore.get_instance()
+ store.set_guilds_for_platform("discord", {"blocked": GuildSettings(enabled=False)}, default_enabled=True)
+ store.save()
+ request = management_http()
+ for payload in (
+ {"guilds": {}, "guild_default_enabled": True},
+ {"guild_allowlist": ["new"], "guild_default_enabled": False},
+ {"guilds": {"blocked": {"enabled": True}}},
+ ):
+ response = request("POST", "/api/settings", payload={"platform": "discord", **payload})
+ assert response.status_code == 403, response.get_json()
+ assert not store.is_guild_enabled("discord", "blocked")
+
+
+def test_member_workbench_preferences_round_trip(management_http):
+ request = management_http()
+ response = request("PUT", "/api/workbench/prefs", payload={"background_work_banner_enabled": False})
+ assert response.status_code == 200, response.get_json()
+ assert request("GET", "/api/workbench/prefs").get_json()["background_work_banner_enabled"] is False
+
+
[email protected]("role", ["owner", "member", "editor", "viewer"])
+def test_remote_management_handlers_reach_only_stubbed_host_effects(management_http, monkeypatch, role):
+ from vibe import cli
+
+ calls = []
+
+ def effect(name):
+ def run(*args, **kwargs):
+ calls.append((name, args, kwargs))
+ return {"ok": True, "operation": name}
+
+ return run
+
+ monkeypatch.setattr(api, "get_backend_runtime", effect("runtime"))
+ monkeypatch.setattr(api, "start_dependency_install_job", effect("dependency"))
+ monkeypatch.setattr(api, "slack_auth_test", effect("platform"))
+ monkeypatch.setattr(cli, "_doctor", effect("doctor"))
+ monkeypatch.setattr(remote_access, "apply_settings", effect("transport"))
+ request = management_http(role)
+ for method, path, payload in (
+ ("GET", "/api/backend/claude/runtime", None),
+ ("POST", "/api/dependencies/avault/install", {}),
+ ("POST", "/api/slack/auth_test", {"bot_token": "test-token"}),
+ ("POST", "/api/doctor", {"deep": True}),
+ ("POST", "/api/remote-access/settings", {"connector_mode": "manual"}),
+ ):
+ response = request(method, path, payload=payload)
+ assert response.status_code == (200 if role in {"owner", "member"} else 403), response.get_json()
+ if role in {"owner", "member"}:
+ assert response.get_json()["ok"]
+ assert [call[0] for call in calls] == (
+ ["runtime", "dependency", "platform", "doctor", "transport"] if role in {"owner", "member"} else []
+ )
+ if calls:
+ assert calls[0][1] == ("claude",)
+ assert calls[1][1] == ("avault",)
+ assert calls[2][1][0] == "test-token"
+ assert calls[3][2]["deep"] is True
+
+
[email protected]("child_requires_bind", [True, False])
+def test_channel_delete_checks_descendant_policy_in_same_transaction(management_http, child_requires_bind):
+ from core import chat_discovery
+
+ chat_discovery.remember_thread("telegram", "chat", "7")
+ store = SettingsStore.get_instance()
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=False)})
+ store.update_thread("chat", "7", ChannelSettings(require_bind=child_requires_bind), platform="telegram")
+ before = store._service.load_state()
+ response = management_http()("POST", "/api/channels/delete", payload={"platform": "telegram", "id": "chat"})
+ assert response.status_code == (403 if child_requires_bind else 200), response.get_json()
+ after = store._service.load_state()
+ if child_requires_bind:
+ assert after == before
+ else:
+ assert after.channels == {} and after.threads == {}
+
+
+def test_remote_member_vault_metadata_and_protected_use_boundary(management_http):
+ from storage import vault_service
+ from storage.vault_crypto import Sealed
+
+ engine = api._vault_engine()
+ try:
+ with engine.begin() as conn:
+ vault_service.create_secret(
+ conn,
+ name="MANAGED_TEST",
+ protection="protected",
+ sealed=Sealed(ciphertext="ct", nonce="n", wrap_meta="wm"),
+ )
+ request = management_http()
+ response = request(
+ "PATCH", "/api/vault/secrets/MANAGED_TEST", payload={"description": "managed metadata", "tags": ["test"]}
+ )
+ assert response.status_code == 200, response.get_json()
+ with engine.connect() as conn:
+ row = vault_service.get_secret_meta(conn, "MANAGED_TEST")
+ assert row["description"] == "managed metadata" and row["tags"] == ["test"]
+ result = vault_service.resolve_secret_access(
+ conn, "MANAGED_TEST", session_id="ses-test", user_context=MEMBER
+ )
+ assert result["status"] == "approval_required"
+ assert result.get("envelope") is None
+ assert (
+ management_http("editor")(
+ "PATCH", "/api/vault/secrets/MANAGED_TEST", payload={"description": "forbidden"}
+ ).status_code
+ == 403
+ )
+ finally:
+ engine.dispose()
+
+
+def test_member_remote_transport_save_preserves_pairing_identity(management_http, monkeypatch):
+ monkeypatch.setattr(remote_access, "status", lambda *args: {"running": False, "ok": True})
+ monkeypatch.setattr(remote_access, "edge_binding_error", lambda *args: None)
+ request = management_http()
+ before = V2Config.load().remote_access.vibe_cloud
+ response = request("POST", "/api/remote-access/settings", payload={"auto_recovery": not before.auto_recovery})
+ assert response.status_code == 200 and response.get_json()["settings_applied"], response.get_json()
+ after = V2Config.load().remote_access.vibe_cloud
+ assert after.auto_recovery != before.auto_recovery
+ assert (after.instance_id, after.instance_secret, after.session_secret) == (
+ before.instance_id,
+ before.instance_secret,
+ before.session_secret,
+ )
+ for field in ("instance_id", "session_secret", "instance_secret", "backend_url"):
+ response = request("POST", "/api/remote-access/settings", payload={field: "injected"})
+ assert response.get_json()["error"] == "remote_access_settings_invalid"
+ assert V2Config.load().remote_access.vibe_cloud == after
+
+
[email protected]("surface", ["users", "channels", "thread", "thread_delete", "guilds", "config_guilds"])
+def test_uncommitted_member_candidate_cannot_escape_through_owner_request(management_http, monkeypatch, surface):
+ """Two real HTTP worker threads overlap between mutation and guarded save."""
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Event
+
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bound": UserSettings(is_admin=False)})
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=True)})
+ store.update_thread("chat", "7", ChannelSettings(require_bind=False), platform="telegram")
+ store.set_guilds_for_platform("discord", {"blocked": GuildSettings(enabled=False)}, default_enabled=True)
+ store.save()
+ before = store._service.load_state()
+ member = management_http()
+ owner = management_http("owner")
+ prepared, owner_done = Event(), Event()
+ save = SettingsStore.save
+
+ def paused_save(candidate, *, user_context=None):
+ if user_context is not None and user_context.instance_role == "member":
+ prepared.set()
+ assert owner_done.wait(10), "Owner request did not finish while Member candidate was private"
+ return save(candidate, user_context=user_context)
+
+ monkeypatch.setattr(SettingsStore, "save", paused_save)
+ mutations = {
+ "users": ("POST", "/api/users", {"platform": "telegram", "users": {"bound": {"is_admin": True}}}),
+ "channels": ("POST", "/api/settings", {"platform": "telegram", "channels": {"chat": {"require_bind": False}}}),
+ "thread": (
+ "POST",
+ "/api/settings/thread",
+ {"platform": "telegram", "channel_id": "chat", "thread_id": "7", "settings": {"require_bind": True}},
+ ),
+ "thread_delete": ("DELETE", "/api/settings/thread?platform=telegram&channel_id=chat&thread_id=7", None),
+ "guilds": ("POST", "/api/settings", {"platform": "discord", "guilds": {"blocked": {"enabled": True}}}),
+ "config_guilds": ("POST", "/api/config", {"discord": {"guild_denylist": []}}),
+ }
+ method, route, payload = mutations[surface]
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ member_job = pool.submit(member, method, route, payload=payload)
+ assert prepared.wait(10)
+ try:
+ # Read the shared cache as a controller would, before Owner's save.
+ assert SettingsStore.get_instance().settings == before
+ if surface == "config_guilds":
+ # Config holds its own lock, so overlap the controller's existing
+ # shared-store writer, which does not need to load config.
+ def controller_save():
+ store.set_channels_for_platform("slack", {"ordinary": ChannelSettings(enabled=True)})
+ store.save()
+
+ pool.submit(controller_save).result(timeout=10)
+ else:
+ owner_job = pool.submit(
+ owner,
+ "POST",
+ "/api/settings",
+ payload={"platform": "slack", "channels": {"ordinary": {"enabled": True}}},
+ )
+ response = owner_job.result(timeout=10)
+ assert response.status_code == 200, response.get_json()
+ finally:
+ owner_done.set()
+ response = member_job.result(timeout=10)
+ assert response.status_code == 403, response.get_json()
+ after = store._service.load_state()
+ assert after.users == before.users and after.threads == before.threads
+ assert after.guilds == before.guilds
+ assert after.channels["telegram::chat"].require_bind
+ assert after.channels["slack::ordinary"].enabled
+
+
[email protected]("role", ["member", "owner"])
[email protected]("surface", ["users", "channels", "thread", "thread_delete", "guilds", "config_guilds"])
+def test_overlapping_settings_requests_keep_both_scopes(management_http, monkeypatch, role, surface):
+ """Successful private writes merge into the lock-fresh state, not a stale whole snapshot."""
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Event
+
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bound": UserSettings()})
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=True)})
+ store.set_channels_for_platform("slack", {
+ "ordinary": ChannelSettings(custom_cwd="/before"),
+ "removed": ChannelSettings(),
+ })
+ store.update_thread("chat", "7", ChannelSettings(require_bind=True), platform="telegram")
+ store.set_guilds_for_platform("discord", {"blocked": GuildSettings(enabled=False)}, default_enabled=True)
+ store.save()
+ first, owner = management_http(role), management_http("owner")
+ prepared, committed = Event(), Event()
+ save = SettingsStore.save
+
+ def paused_save(candidate, *, user_context=None):
+ if user_context is not None and not prepared.is_set():
+ prepared.set()
+ assert committed.wait(10)
+ return save(candidate, user_context=user_context)
+
+ monkeypatch.setattr(SettingsStore, "save", paused_save)
+ mutations = {
+ "users": ("POST", "/api/users", {"platform": "telegram", "users": {"bound": {"custom_cwd": "/first"}}}),
+ "channels": ("POST", "/api/settings", {"platform": "telegram", "channels": {"chat": {"custom_cwd": "/first"}}}),
+ "thread": ("POST", "/api/settings/thread", {
+ "platform": "telegram", "channel_id": "chat", "thread_id": "7", "settings": {"custom_cwd": "/first"},
+ }),
+ "thread_delete": ("DELETE", "/api/settings/thread?platform=telegram&channel_id=chat&thread_id=7", None),
+ "guilds": ("POST", "/api/settings", {"platform": "discord", "guilds": {"blocked": {"enabled": False}}}),
+ "config_guilds": ("POST", "/api/config", {"discord": {"guild_denylist": ["blocked"]}}),
+ }
+ method, route, payload = mutations[surface]
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ pending = pool.submit(first, method, route, payload=payload)
+ assert prepared.wait(10)
+ try:
+ if surface == "config_guilds":
+ # The config writer holds config lock; overlap the existing
+ # controller writer, not a second request needing that lock.
+ def controller_save():
+ store.set_channels_for_platform("slack", {
+ "ordinary": ChannelSettings(custom_cwd="/second"),
+ "added": ChannelSettings(enabled=True),
+ })
+ store.save()
+
+ pool.submit(controller_save).result(timeout=10)
+ else:
+ response = pool.submit(owner, "POST", "/api/settings", payload={
+ "platform": "slack", "channels": {
+ "ordinary": {"custom_cwd": "/second"}, "added": {"enabled": True},
+ },
+ }).result(timeout=10)
+ assert response.status_code == 200, response.get_json()
+ finally:
+ committed.set()
+ response = pending.result(timeout=10)
+ assert response.status_code == 200, response.get_json()
+ after = store._service.load_state()
+ assert after.channels["slack::ordinary"].custom_cwd == "/second"
+ assert after.channels["slack::added"].enabled
+ assert "slack::removed" not in after.channels
+ if surface in {"users", "channels", "thread"}:
+ changed = {
+ "users": after.users["telegram::bound"],
+ "channels": after.channels["telegram::chat"],
+ "thread": after.threads["telegram::chat/7"],
+ }
+ assert changed[surface].custom_cwd == "/first"
+ elif surface == "thread_delete":
+ assert not after.threads
+
+
[email protected]("mutation", ["remove", "role", "disable"])
+def test_private_member_dm_save_refuses_changed_membership(management_http, monkeypatch, mutation):
+ """The real HTTP candidate must not resurrect or rewrite a concurrently changed user."""
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Event
+
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bound": UserSettings()})
+ store.save()
+ request = management_http()
+ prepared, committed = Event(), Event()
+ save = SettingsStore.save
+
+ def paused_save(candidate, *, user_context=None):
+ if user_context is not None:
+ prepared.set()
+ assert committed.wait(10)
+ return save(candidate, user_context=user_context)
+
+ monkeypatch.setattr(SettingsStore, "save", paused_save)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ pending = pool.submit(request, "POST", "/api/users", payload={
+ "platform": "telegram", "users": {"bound": {"custom_cwd": "/stale"}},
+ })
+ assert prepared.wait(10)
+ try:
+ if mutation == "remove":
+ store.set_users_for_platform("telegram", {})
+ elif mutation == "role":
+ store.get_user("bound", platform="telegram").is_admin = True
+ else:
+ store.get_user("bound", platform="telegram").enabled = False
+ pool.submit(store.save).result(timeout=10)
+ fresh = store._service.load_state()
+ finally:
+ committed.set()
+ response = pending.result(timeout=10)
+ assert response.status_code == 403, response.get_json()
+ assert store._service.load_state() == fresh
+
+
+def test_member_stale_access_snapshot_cannot_replay_untouched_rows(management_http, monkeypatch):
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Event
+
+ store = SettingsStore.get_instance()
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings()})
+ store.set_users_for_platform("telegram", {"changed": UserSettings(), "removed": UserSettings()})
+ store.set_guilds_for_platform("discord", {"before": GuildSettings()}, default_enabled=False)
+ store.settings.bind_codes = [BindCode("old", "one_time", "now")]
+ store.save()
+ request = management_http()
+ prepared, committed = Event(), Event()
+ save = SettingsStore.save
+
+ def paused_save(candidate, *, user_context=None):
+ if user_context is not None:
+ prepared.set()
+ assert committed.wait(10)
+ return save(candidate, user_context=user_context)
+
+ monkeypatch.setattr(SettingsStore, "save", paused_save)
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ pending = pool.submit(request, "POST", "/api/settings", payload={
+ "platform": "telegram", "channels": {"chat": {"custom_cwd": "/ordinary"}},
+ })
+ assert prepared.wait(10)
+ try:
+ store.set_users_for_platform("telegram", {
+ "changed": UserSettings(is_admin=True, enabled=False), "added": UserSettings(),
+ })
+ store.set_guilds_for_platform("discord", {"after": GuildSettings()}, default_enabled=False)
+ store.settings.bind_codes = [BindCode("new", "one_time", "now")]
+ pool.submit(store.save).result(timeout=10)
+ fresh = store._service.load_state()
+ finally:
+ committed.set()
+ response = pending.result(timeout=10)
+ assert response.status_code == 403, response.get_json()
+ after = store._service.load_state()
+ assert after.channels["telegram::chat"].custom_cwd is None
+ assert after.users == fresh.users
+ assert after.guilds == fresh.guilds and after.guild_default_enabled == fresh.guild_default_enabled
+ assert after.bind_codes == fresh.bind_codes
+
+
[email protected]("field", ["is_admin", "enabled", "require_bind"])
+def test_member_explicit_unchanged_access_echo_is_checked_against_fresh_state(management_http, monkeypatch, field):
+ from concurrent.futures import ThreadPoolExecutor
+ from threading import Event
+
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bound": UserSettings(is_admin=False, enabled=True)})
+ store.set_channels_for_platform("telegram", {"chat": ChannelSettings(require_bind=False)})
+ store.save()
+ request = management_http()
+ prepared, committed = Event(), Event()
+ save = SettingsStore.save
+
+ def paused_save(candidate, *, user_context=None):
+ if user_context is not None:
+ prepared.set()
+ assert committed.wait(10)
+ return save(candidate, user_context=user_context)
+
+ monkeypatch.setattr(SettingsStore, "save", paused_save)
+ if field == "require_bind":
+ route = "/api/settings"
+ payload = {"platform": "telegram", "channels": {"chat": {field: False}}}
+ else:
+ route = "/api/users"
+ payload = {"platform": "telegram", "users": {"bound": {field: field == "enabled"}}}
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ pending = pool.submit(request, "POST", route, payload=payload)
+ assert prepared.wait(10)
+ try:
+ if field == "require_bind":
+ store.find_channel("chat", platform="telegram").require_bind = True
+ else:
+ setattr(store.get_user("bound", platform="telegram"), field, field == "is_admin")
+ pool.submit(store.save).result(timeout=10)
+ fresh = store._service.load_state()
+ finally:
+ committed.set()
+ response = pending.result(timeout=10)
+ assert response.status_code == 403, response.get_json()
+ assert store._service.load_state() == fresh
+
+
+ b"{", b"[]", b"null", b"\xff", b'{"discord": []}',
+ b'{"discord": {"bot_token": 12}}', b'{"discord": {"thread_auto_archive_minutes": 13}}',
+])
+def test_member_settings_save_uses_config_recovery_semantics(management_http, raw):
+ config_path = paths.get_config_path()
+ config_path.write_bytes(raw)
+ # Startup accepts these released/damaged shapes with recovery defaults.
+ recovered = V2Config.load()
+ assert recovered.load_warnings
+ result = api.save_settings({"platform": "telegram", "channels": {"safe": {"enabled": True}}}, user_context=MEMBER)
+ assert "safe" in result["channels"]
+ with contextlib.closing(SettingsStore()) as saved:
+ assert saved.find_channel("safe", platform="telegram").enabled
+ assert config_path.read_bytes() == raw # The policy read never persists recovery.
+
+
[email protected]("discord", [[], "invalid", {"bot_token": 12}])
[email protected]("surface", ["channels", "thread", "users"])
+def test_remote_member_can_save_with_recovered_discord_section(management_http, discord, surface):
+ store = SettingsStore.get_instance()
+ store.set_users_for_platform("telegram", {"bound": UserSettings()})
+ store.save()
+ request = management_http()
+ config_path = paths.get_config_path()
+ payload = json.loads(config_path.read_text())
+ payload["discord"] = discord
+ config_path.write_text(json.dumps(payload))
+ mutations = {
+ "channels": ("/api/settings", {"platform": "telegram", "channels": {"safe": {"enabled": True}}}),
+ "thread": ("/api/settings/thread", {
+ "platform": "telegram", "channel_id": "safe", "thread_id": "7", "settings": {"enabled": True},
+ }),
+ "users": ("/api/users", {"platform": "telegram", "users": {"bound": {"custom_cwd": "/recovered"}}}),
+ }
+ route, body = mutations[surface]
+ response = request("POST", route, payload=body)
+ assert response.status_code == 200, response.get_json()
+ after = store._service.load_state()
+ if surface == "channels":
+ assert after.channels["telegram::safe"].enabled
+ elif surface == "thread":
+ assert after.threads["telegram::safe/7"].enabled
+ else:
+ assert after.users["telegram::bound"].custom_cwd == "/recovered"
+ # Unrelated remote identity remains intact and the raw file is not repaired here.
+ assert json.loads(config_path.read_text()) == payload
+
+
+def test_recovery_keeps_valid_legacy_guild_admission_policy(management_http):
+ request = management_http()
+ config_path = paths.get_config_path()
+ payload = json.loads(config_path.read_text())
+ payload["discord"] = {"guild_allowlist": ["allowed"], "guild_denylist": ["blocked"]}
+ payload["runtime"] = []
+ config_path.write_text(json.dumps(payload))
+ recovered = V2Config.load()
+ assert recovered.load_warnings
+ assert recovered.discord.guild_allowlist == ["allowed"]
+ response = request("POST", "/api/settings", payload={
+ "platform": "discord", "guild_allowlist": ["attacker"],
+ })
+ assert response.status_code == 403, response.get_json()
+ response = request("POST", "/api/settings", payload={
+ "platform": "discord", "guilds": {"allowed": {"enabled": True}, "blocked": {"enabled": False}},
+ "guild_default_enabled": False,
+ })
+ assert response.status_code == 200, response.get_json()
+ assert json.loads(config_path.read_text()) == payload
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 72931abd8..e47a6a878 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -61,8 +61,14 @@ from core.handlers.model_hub.service import (
ModelHubService,
create_default_service,
)
-from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_config
-from vibe import backend_model_catalog, ui_server
+from tests.ui_server_test_helpers import (
+ _save_config,
+ csrf_headers,
+ remote_peer,
+ remote_session_cookie,
+ save_config,
+)
+from vibe import backend_model_catalog, remote_access, ui_server
from vibe.model_hub_client import ModelHubRemoteService, _decode
from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog
from vibe.model_hub_runtime.state import EngineStateError, _validate_source_target
@@ -615,6 +621,28 @@ def _as_ui_client(service):
return UIClientShape()
+def _remote_model_hub_client(tmp_path, *, role="member", kind="organization", organization_role="member"):
+ """Use the real paired-session signature, authorization and CSRF path."""
+ config = _save_config(tmp_path, paired=True, instance_kind=kind)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ remote_session_cookie(
+ config,
+ "model-hub-user",
+ role=role,
+ access_source="organization_group" if kind == "organization" else "email",
+ organization_id="org-model-hub" if kind == "organization" else None,
+ organization_member_id="membership-model-hub" if kind == "organization" else None,
+ organization_role=organization_role if kind == "organization" else None,
+ group_ids=[] if kind == "organization" else None,
+ ),
+ domain="alex.avibe.bot",
+ )
+ return client, "https://alex.avibe.bot"
+
+
def test_api_response_registry_exactly_covers_contract_and_server_routes():
api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
documented = {
@@ -717,11 +745,16 @@ def test_oauth_result_response_discriminates_terminal_intent_and_tail():
API_RESPONSE_EXERCISES,
ids=lambda value: (f"{value['method']} {value['path']}" if "method" in value else value.get("setup", "plain")),
)
[email protected]("access", [
+ "local", "personal-member", "organization-owner", "organization-member",
+ "organization-editor", "organization-viewer",
+])
def test_every_model_hub_endpoint_returns_its_contract_response(
monkeypatch,
tmp_path,
route_contract,
exercise,
+ access,
):
endpoint = f"{route_contract['method']} {route_contract['path']}"
@@ -729,18 +762,33 @@ def test_every_model_hub_endpoint_returns_its_contract_response(
monkeypatch.setenv("HOME", str(isolated_home))
monkeypatch.setenv("AVIBE_HOME", str(isolated_home / ".avibe"))
monkeypatch.setenv("XDG_CONFIG_HOME", str(isolated_home / ".config"))
- save_config(isolated_home)
+ if access == "local":
+ save_config(isolated_home)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+ else:
+ kind, role = access.split("-", 1)
+ client, base_url = _remote_model_hub_client(isolated_home, role=role, kind=kind)
service = _seed_response_conformance_service(tmp_path)
if endpoint == "POST /api/models/runtime/stop":
for agent in service.store.config.agents.values():
agent.mode = "direct"
- monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))
- client = app.test_client()
- base_url = "http://127.0.0.1:15131"
+ admitted = access not in {"organization-editor", "organization-viewer"} or (
+ access == "organization-editor"
+ and endpoint == "GET /api/models/agents/<backend>/models"
+ )
+
+ def get_service():
+ assert admitted, "authorization must deny before entering a Model Hub handler"
+ return _as_ui_client(service)
+
+ monkeypatch.setattr(ui_server, "_model_hub_service", get_service)
request_kwargs = {
"headers": csrf_headers(client, base_url),
"base_url": base_url,
}
+ if access != "local":
+ request_kwargs["environ_base"] = remote_peer()
setup = exercise.get("setup")
if setup in {"backend_model_guard", "backend_model_forced_removal"}:
baseline = service.backend_catalog_models("claude")
@@ -798,6 +846,10 @@ def test_every_model_hub_endpoint_returns_its_contract_response(
**request_kwargs,
)
body = response.get_json()
+ if not admitted:
+ assert response.status_code == 403
+ assert body["error"] == "instance_access_forbidden"
+ return
assert response.status_code == exercise["status"], (
f"{endpoint}: expected HTTP {exercise['status']}, got {response.status_code}: {body}"
)
@@ -9164,3 +9216,23 @@ def test_metadata_only_source_patch_does_not_require_engine_sync(tmp_path):
assert updated["interrupted"] == []
assert store.config.sources[0].display_name == "After rename"
assert len(adapter.synced) == sync_count
+
+
+def test_signed_organization_member_completes_models_page_bootstrap(monkeypatch, tmp_path):
+ """Reported settings/models regression: status must precede all page reads."""
+ client, base_url = _remote_model_hub_client(tmp_path)
+ service = _seed_response_conformance_service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))
+ for path, key in (
+ ("/api/models/runtime/status", "runtime"),
+ ("/api/models/sources", "sources"),
+ ("/api/models/agents", "agents"),
+ ("/api/models/events", "events"),
+ ("/api/models/usage", "usage"),
+ ):
+ response = client.get(path, base_url=base_url, environ_base=remote_peer())
+ assert response.status_code == 200, (path, response.get_json())
+ assert key in response.get_json()
+ # A valid signed session still needs CSRF for writes.
+ response = client.post("/api/models/runtime/start", json={}, base_url=base_url, environ_base=remote_peer())
+ assert response.status_code == 403
diff --git a/tests/test_resource_acl_vaults.py b/tests/test_resource_acl_vaults.py
index a7c67f87f..99142c6b5 100644
--- a/tests/test_resource_acl_vaults.py
+++ b/tests/test_resource_acl_vaults.py
@@ -543,8 +543,7 @@ def test_active_org_admin_can_manage_public_vault_secret(vault) -> None:
"PUBLIC_MANAGEMENT",
user_context=_context("member-1"),
)["name"] == "PUBLIC_MANAGEMENT"
- # Writes stay reserved to admin/owner Organization roles under the
- # Resource ACL boundary (see #1343).
+ # Instance Editor cannot manage secrets, regardless of Organization role.
with pytest.raises(vault_service.VaultSecretAccessError):
vault_service.update_secret_metadata(
conn,
@@ -726,3 +725,50 @@ def test_narrowed_vault_release_failure_stays_pending_until_retry_succeeds(vault
"outcome": "applied",
}
]
+
+
[email protected]("role", ["owner", "member", "editor", "viewer"])
+def test_secret_management_follows_instance_manager_capability(vault, role):
+ context = _context("manager", instance_role=role)
+ with vault.begin() as conn:
+ _create_secret(conn, "MANAGED_KEY")
+ operations = (
+ lambda: vault_service.update_secret_tags(conn, "MANAGED_KEY", ["test"], user_context=context),
+ lambda: vault_service.update_secret_metadata(conn, "MANAGED_KEY", description="managed", user_context=context),
+ lambda: vault_service.update_secret_classification(conn, "MANAGED_KEY", protection="protected", user_context=context),
+ lambda: vault_service.store_pubkey_pin(conn, "MANAGED_KEY", {"fingerprint": "test-pin"}, user_context=context),
+ lambda: vault_service.rotate_secret(conn, "MANAGED_KEY", _sealed("rotated"), user_context=context),
+ lambda: vault_service.delete_secret(conn, "MANAGED_KEY", user_context=context),
+ )
+ for operation in operations:
+ if role in {"owner", "member"}:
+ operation()
+ else:
+ with pytest.raises(vault_service.VaultSecretAccessError):
+ operation()
+ if role in {"owner", "member"}:
+ with pytest.raises(vault_service.SecretNotFoundError):
+ vault_service.get_secret_meta(conn, "MANAGED_KEY")
+ else:
+ assert vault_service.get_secret_meta(conn, "MANAGED_KEY")["tags"] == []
+
+
[email protected]("policy", ["missing", "foreign"])
+def test_management_parity_does_not_bypass_direct_secret_use_policy(vault, policy):
+ # Direct service contexts retain ACL checks; validated remote Organization
+ # use intentionally has the existing Editor-or-higher behavior above.
+ context = _context("manager", instance_role="member", is_remote=False)
+ with vault.begin() as conn:
+ _create_secret(conn, "DIRECT_PRIVATE", protection="protected")
+ resource_id = _secret_id(conn, "DIRECT_PRIVATE")
+ conn.execute(resource_access_policies.delete().where(resource_access_policies.c.resource_id == resource_id))
+ if policy == "foreign":
+ resource_access_service.ensure_resource_policy(
+ conn, resource_kind="vault_secret", resource_id=resource_id,
+ organization_id="foreign-org", owner_user_id="foreign-user",
+ access_level="private", group_ids=[], policy_revision=1,
+ last_applied_control_plane_revision=1,
+ )
+ vault_service.update_secret_metadata(conn, "DIRECT_PRIVATE", description="managed", user_context=context)
+ with pytest.raises(vault_service.VaultSecretAccessError):
+ vault_service.resolve_secret_access(conn, "DIRECT_PRIVATE", session_id="ses-private", user_context=context)
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index 84362b1c3..b5e5a8425 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -501,8 +501,8 @@ def test_settings_save_does_not_absorb_a_newer_external_revision(
external = SQLiteSettingsService(tmp_path / "vibe.sqlite")
original_save = store._service.save_state
- def save_then_race(state: SettingsState) -> str:
- committed_revision = original_save(state)
+ def save_then_race(state: SettingsState, *, user_context=None, baseline=None) -> str:
+ committed_revision = original_save(state, user_context=user_context, baseline=baseline)
external.save_state(
SettingsState(
channels={
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index a7d71ff8f..879d17bc3 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -3488,6 +3488,8 @@ def test_telegram_topic_settings_materialize_inherited_mention_default(tmp_path,
assert saved["ok"] is True
assert saved["settings"]["require_mention"] is False
+ # The API commits through a private store; consumers refresh by revision.
+ assert store.maybe_reload() is True
assert store.find_thread("-1001", "42", platform="telegram").require_mention is False
finally:
SettingsStore.reset_instance()
diff --git a/tests/test_ui_project_access.py b/tests/test_ui_project_access.py
index 0c5dc1a83..3de068c89 100644
--- a/tests/test_ui_project_access.py
+++ b/tests/test_ui_project_access.py
@@ -571,23 +571,11 @@ def test_editor_config_write_always_answers_with_a_renderable_code(monkeypatch,
assert V2Config.load().runtime.default_cwd == "."
-def test_no_non_owner_can_persist_a_credential_through_the_config_write(monkeypatch, tmp_path) -> None:
- """Persisting a secret is an Owner act, and the allowlist closes that by shape.
-
- The write schema used to be selected with ``can_manage_instance``, which
- stopped being an owner test once a member held that capability: the member
- fell past the Editor allowlist into a filter that removed only
- ``remote_access``, so platform bot tokens and gateway secrets reached the
- save path and were reconciled onto the live platform.
-
- The enumeration comes from ``api._PLATFORM_SECRET_FIELDS`` and
- ``api._GATEWAY_SECRET_FIELDS`` rather than from the four fields a review
- happened to name, and the assertion is over the allowlist rather than over
- those tables: a secret added to either table -- or a credential-bearing
- section nobody has written down yet -- is unreachable below Owner because
- it is absent from ``_EDITOR_CONFIG_WRITE_FIELDS``, not because someone
- remembered to strip it. ``remote_access`` rides the same rule, which is why
- the pairing-specific filter it used to need is gone.
+def test_editor_cannot_persist_a_credential_through_the_config_write(monkeypatch, tmp_path) -> None:
+ """Editor keeps its preference-only schema across all credential sections.
+
+ The field registry independently enumerates credential-bearing sections;
+ Member management is covered by the signed remote management scenarios.
"""
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
config, _ids = _setup_state(tmp_path)
@@ -617,7 +605,7 @@ def test_no_non_owner_can_persist_a_credential_through_the_config_write(monkeypa
assert baseline["slack.bot_token"] == ""
assert baseline["remote_access.instance_id"] == "inst_123"
- for role in ("member", "editor"):
+ for role in ("editor",):
client = _remote_client(config, role=role, email=f"{role}@example.com")
headers = csrf_headers(client, REMOTE_ORIGIN)
for section, fields in secret_sections.items():
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index d77da0927..d2de25859 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -322,12 +322,13 @@ def test_thread_settings_routes_use_native_fastapi(monkeypatch):
monkeypatch.setattr(
api,
"save_thread_settings",
- lambda payload: saved_payloads.append(payload) or {"ok": True, "settings": payload["settings"]},
+ lambda payload, *, user_context: saved_payloads.append(payload)
+ or {"ok": True, "settings": payload["settings"]},
)
monkeypatch.setattr(
api,
"delete_thread_settings",
- lambda platform, channel_id, thread_id: deleted_scopes.append(
+ lambda platform, channel_id, thread_id, *, user_context: deleted_scopes.append(
(platform, channel_id, thread_id)
)
or {"ok": True, "removed": True},
diff --git a/tests/test_ui_show_pages.py b/tests/test_ui_show_pages.py
index 54cf0e275..5ae7eff31 100644
--- a/tests/test_ui_show_pages.py
+++ b/tests/test_ui_show_pages.py
@@ -13842,3 +13842,28 @@ def test_show_runtime_manager_defaults_to_manifest_when_package_manifest_exists(
)
assert manager.runtime_source == "manifest-cache"
+
+
[email protected]("role", ["owner", "member", "editor", "viewer"])
+def test_remote_instance_manager_can_repair_accessible_show_runtime(monkeypatch, tmp_path, role):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ config = _save_config(tmp_path, paired=True, instance_kind="organization")
+ _create_show_page("ses-manager-repair", "private")
+ manager = _FakeShowRuntimeManager(fail=True, failure_reason="runtime_start_health_timeout")
+ set_show_runtime_manager_for_tests(manager)
+ client = app.test_client()
+ client.set_cookie(
+ remote_access.SESSION_COOKIE_NAME,
+ _active_org_cookie(config, f"{role}@example.com", role, role=role),
+ domain="alex.avibe.bot",
+ )
+ try:
+ response = client.get(
+ "/show/ses-manager-repair/", base_url="https://alex.avibe.bot",
+ environ_base=_remote_peer(), headers={"X-Avibe-Show-Recovery-Retry": "1"},
+ )
+ finally:
+ set_show_runtime_manager_for_tests(None)
+ assert response.status_code == 200
+ assert manager.automatic_calls == [role not in {"owner", "member"}]
+ assert (b"show-runtime-retry-now" in response.content) == (role in {"owner", "member"})
diff --git a/tests/test_wechat_auth.py b/tests/test_wechat_auth.py
index 659cc79aa..9e9cf41c6 100644
--- a/tests/test_wechat_auth.py
+++ b/tests/test_wechat_auth.py
@@ -133,7 +133,7 @@ class WeChatAuthManagerTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("const hasSavedBotToken = hasUsableSecret(data.wechat, 'bot_token', botToken);", source)
self.assertIn("const isAlreadyBound = loginState === 'idle' && !botToken && hasSavedBotToken;", source)
self.assertIn("loginState === 'idle' && !botToken && !isAlreadyBound", source)
- self.assertIn("if (!autoStartLogin) return;", source)
+ self.assertIn("if (!autoStartLogin || !canManageAccessMembers) return;", source)
settings_source = Path("ui/src/components/settings/SettingsPlatformsPage.tsx").read_text(encoding="utf-8")
self.assertIn("autoStartLogin={false}", settings_source)
diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsx
index e955abd3e..487481661 100644
--- a/ui/src/components/settings/SettingsPlatformsPage.tsx
+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx
@@ -1,3 +1,4 @@
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -55,6 +56,8 @@ const tileStyle = (id: string) =>
// and save. There is no user-facing "primary platform" — the backend derives
// an internal default from the enabled set, so this page never sends one.
export const SettingsPlatformsPage: React.FC = () => {
+ const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -96,7 +99,7 @@ export const SettingsPlatformsPage: React.FC = () => {
const savePlatformSettings = async (platform: string, nextData: any) => {
const discordGuildAllowlist = nextData?.discordGuildAllowlist;
if (
- platform === 'discord' &&
+ canManageAccessMembers && platform === 'discord' &&
Array.isArray(discordGuildAllowlist) &&
(discordGuildAllowlist.length > 0 || nextData?.discordGuildAllowlistTouched === true)
) {
diff --git a/ui/src/components/shared/MemberManagementControls.test.tsx b/ui/src/components/shared/MemberManagementControls.test.tsx
new file mode 100644
index 000000000..6e93c20ad
--- /dev/null
+++ b/ui/src/components/shared/MemberManagementControls.test.tsx
@@ -0,0 +1,56 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';
+import { OWNER_INSTANCE_CAPABILITIES } from '@/lib/sessionInfo';
+import { RoutingConfigPanel } from './RoutingConfigPanel';
+import { WeChatConfig } from '../steps/WeChatConfig';
+
+const api = vi.hoisted(() => ({ wechatStartLogin: vi.fn(), wechatPollLogin: vi.fn() }));
+vi.mock('@/context/ApiContext', async (loadOriginal) => ({
+ ...await loadOriginal<typeof import('@/context/ApiContext')>(), useApi: () => api,
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('../workbench/AgentRoutePicker', () => ({ AgentRoutePicker: () => null }));
+
+function manager(role: 'owner' | 'member', children: React.ReactNode) {
+ return <InstanceAuthorizationContext.Provider value={{
+ remote: true, instanceKind: 'organization', instanceRole: role,
+ capabilities: { ...OWNER_INSTANCE_CAPABILITIES, is_instance_owner: role === 'owner', can_manage_access_members: role === 'owner' },
+ }}>{children}</InstanceAuthorizationContext.Provider>;
+}
+
+afterEach(cleanup);
+beforeEach(() => { vi.clearAllMocks(); api.wechatStartLogin.mockResolvedValue({ qrcode_url: 'https://example.invalid' }); });
+
+describe('Instance Member settings boundaries', () => {
+ it.each(['owner', 'member'] as const)('%s can edit mentions; only Owner can change binding', async (role) => {
+ const onChange = vi.fn();
+ render(manager(role, <RoutingConfigPanel value={{ custom_cwd: '', routing: {}, show_message_types: [], require_mention: false, require_bind: true }} onChange={onChange} onBrowseDirectory={() => {}} globalConfig={{}} />));
+ const [mention, binding] = screen.getAllByRole('switch') as HTMLButtonElement[];
+ expect(mention.disabled).toBe(false);
+ expect(binding.disabled).toBe(role === 'member');
+ await userEvent.click(mention);
+ expect(onChange).toHaveBeenCalledWith({ require_mention: true });
+ await userEvent.click(binding);
+ expect(onChange).toHaveBeenCalledTimes(role === 'member' ? 1 : 2);
+ });
+
+ it('Member saves a WeChat credential without starting the user-binding QR flow', async () => {
+ const apply = vi.fn();
+ render(manager('member', <WeChatConfig data={{ wechat: {} }} embedded onNext={() => {}} onApply={apply} />));
+ expect(api.wechatStartLogin).not.toHaveBeenCalled();
+ expect(screen.getByText('wechatConfig.ownerBindingRequired')).toBeTruthy();
+ await userEvent.type(screen.getByLabelText('wechatConfig.botToken'), 'test-credential');
+ await userEvent.click(screen.getByRole('button', { name: 'platform.apply' }));
+ expect(apply).toHaveBeenCalledWith(expect.objectContaining({ wechat: expect.objectContaining({ bot_token: 'test-credential' }) }));
+ expect(api.wechatStartLogin).not.toHaveBeenCalled();
+ expect(api.wechatPollLogin).not.toHaveBeenCalled();
+ });
+
+ it('Owner retains automatic WeChat QR setup', async () => {
+ render(manager('owner', <WeChatConfig data={{ wechat: {} }} onNext={() => {}} />));
+ expect(api.wechatStartLogin).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/ui/src/components/shared/RoutingConfigPanel.tsx b/ui/src/components/shared/RoutingConfigPanel.tsx
index 618a1cb36..270cb314e 100644
--- a/ui/src/components/shared/RoutingConfigPanel.tsx
+++ b/ui/src/components/shared/RoutingConfigPanel.tsx
@@ -1,3 +1,4 @@
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useState } from 'react';
import { Bot, FolderOpen, HelpCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -87,6 +88,8 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
footerActions,
containerClass = 'border-t border-border/60 px-5 py-4',
}) => {
+ const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
const { t } = useTranslation();
const selectedVibeAgent = vibeAgents.find((agent) => agent.name === value.routing.agent_name) || null;
@@ -168,6 +171,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
<label className="text-xs font-medium uppercase text-muted">{t('channelList.requireBind')}</label>
<div className="flex h-9 items-center">
<ToggleSwitch
+ disabled={!canManageAccessMembers}
enabled={effective}
onClick={() => onChange({ require_bind: !effective })}
/>
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index 30cb755d0..d0690977d 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -1,3 +1,4 @@
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
ArrowLeft,
@@ -106,6 +107,8 @@ const addDiscordGuildToAllowlist = (allowlist: string[], selectedGuild: string):
};
export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onBack, isPage, forcedPlatform, wizardPlatforms }) => {
+ const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -1259,6 +1262,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
<label className="inline-flex items-center gap-2 text-[13px] text-foreground">
<span>{t('channelList.requireBind')}</span>
<ToggleSwitch
+ disabled={!canManageAccessMembers}
enabled={!!(config as any)[pageTab]?.require_bind}
onClick={() => savePlatformFlag(pageTab, 'require_bind')}
/>
@@ -1305,7 +1309,8 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
>
<input
type="checkbox"
- checked={selectedGuildIds.includes(g.id)}
+ disabled={!canManageAccessMembers}
+ checked={selectedGuildIds.includes(g.id)}
onChange={(e) => toggleAllowedGuild(g.id, e.target.checked)}
className="h-3.5 w-3.5 accent-accent"
/>
@@ -1453,7 +1458,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (rawConfig.require_mention === null || rawConfig.require_mention === undefined) {
patch.require_mention = !!platformDefaults.require_mention;
}
- if (rawConfig.require_bind === null || rawConfig.require_bind === undefined) {
+ if (canManageAccessMembers && (rawConfig.require_bind === null || rawConfig.require_bind === undefined)) {
patch.require_bind = !!platformDefaults.require_bind;
}
updateRow(patch);
@@ -1818,6 +1823,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
>
<input
type="checkbox"
+ disabled={!canManageAccessMembers}
checked={selectedGuildIds.includes(g.id)}
onChange={(e) => toggleAllowedGuild(g.id, e.target.checked)}
className="h-3.5 w-3.5 accent-accent"
@@ -1902,7 +1908,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
if (rawConfig.require_mention === null || rawConfig.require_mention === undefined) {
patch.require_mention = !!platformDefaults.require_mention;
}
- if (rawConfig.require_bind === null || rawConfig.require_bind === undefined) {
+ if (canManageAccessMembers && (rawConfig.require_bind === null || rawConfig.require_bind === undefined)) {
patch.require_bind = !!platformDefaults.require_bind;
}
updateConfig(channel.id, patch);
diff --git a/ui/src/components/steps/DiscordConfig.tsx b/ui/src/components/steps/DiscordConfig.tsx
index 1047ff3e0..aa60c37af 100644
--- a/ui/src/components/steps/DiscordConfig.tsx
+++ b/ui/src/components/steps/DiscordConfig.tsx
@@ -1,3 +1,4 @@
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useState } from 'react';
import {
Shield,
@@ -44,6 +45,8 @@ const getDiscordGuildAllowlist = (source: any): string[] => {
// Mirrors design.pen XCWAT (Slack creds wizard step) adapted for Discord.
// 920-wide WizardCard, mint eyebrow, accordion rows with mint-bordered active row.
export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBack, embedded = false, onApply, onCancel }) => {
+ const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -375,6 +378,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa
<div className="flex items-center gap-3">
<button
type="button"
+ disabled={!canManageAccessMembers}
onClick={selectAllGuilds}
className="text-[11px] font-medium text-cyan-ink transition hover:text-cyan-ink/80"
>
@@ -382,7 +386,9 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa
</button>
<button
type="button"
+ disabled={!canManageAccessMembers}
onClick={() => {
+ if (!canManageAccessMembers) return;
setGuildSelectionTouched(true);
setSelectedGuilds([]);
}}
@@ -404,6 +410,7 @@ export const DiscordConfig: React.FC<DiscordConfigProps> = ({ data, onNext, onBa
>
<input
type="checkbox"
+ disabled={!canManageAccessMembers}
checked={selectedGuilds.includes(g.id)}
onChange={(e) => toggleGuild(g.id, e.target.checked)}
className="size-4 accent-mint"
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index 9aee001b1..f3d30e972 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -1,3 +1,4 @@
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useState } from 'react';
import {
Bot,
@@ -444,6 +445,8 @@ const Modal: React.FC<{ title: string; onClose: () => void; children: React.Reac
// ─── User List Page ──────────────────────────────────────────────────────
export const UserList: React.FC = () => {
+ const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -522,7 +525,7 @@ export const UserList: React.FC = () => {
});
}, [aggregated, searchQuery, showDisabled]);
- const persistUsers = async (platform: string, next: Record<string, UserConfig>) => {
+ const persistUsers = async (platform: string, next: Record<string, Partial<UserConfig>>) => {
setLoading(true);
try {
await api.saveUsers({ users: next }, platform);
@@ -543,7 +546,10 @@ export const UserList: React.FC = () => {
}
const nextPlatformUsers = { ...platformUsers, [userId]: next };
setUsersByPlatform((prev) => ({ ...prev, [platform]: nextPlatformUsers }));
- void persistUsers(platform, nextPlatformUsers);
+ void persistUsers(platform, { [userId]: canManageAccessMembers ? next : {
+ display_name: next.display_name, custom_cwd: next.custom_cwd,
+ routing: next.routing, show_message_types: next.show_message_types,
+ } });
};
const handleToggleAdmin = async (platform: string, userId: string, isAdmin: boolean) => {
@@ -652,10 +658,10 @@ export const UserList: React.FC = () => {
</div>
{/* Bind code card */}
- <BindCodeCard
+ {canManageAccessMembers && <BindCodeCard
refreshTrigger={refreshTrigger}
onCodesChanged={() => setRefreshTrigger((v) => v + 1)}
- />
+ />}
{/* List header */}
<div className="flex items-center justify-between px-1 py-2">
@@ -706,7 +712,7 @@ export const UserList: React.FC = () => {
const updateRow = (patch: Partial<UserConfig>) => updateUser(u.platform, u.userId, patch);
const toggleEnabled = () => updateRow({ enabled: !userConfig.enabled });
- const toggleAdmin = () => handleToggleAdmin(u.platform, u.userId, !userConfig.is_admin);
+ const toggleAdmin = () => canManageAccessMembers && handleToggleAdmin(u.platform, u.userId, !userConfig.is_admin);
return (
<div
@@ -737,6 +743,7 @@ export const UserList: React.FC = () => {
{/* Enabled toggle */}
<span onClick={(e) => e.stopPropagation()}>
<ToggleSwitch
+ disabled={!canManageAccessMembers}
enabled={userConfig.enabled}
onClick={toggleEnabled}
/>
@@ -780,7 +787,8 @@ export const UserList: React.FC = () => {
) : (
<span
role="button"
- tabIndex={0}
+ tabIndex={canManageAccessMembers ? 0 : -1}
+ aria-disabled={!canManageAccessMembers}
aria-pressed={userConfig.is_admin}
onClick={(e) => { e.stopPropagation(); toggleAdmin(); }}
onKeyDown={(e) => {
@@ -829,6 +837,7 @@ export const UserList: React.FC = () => {
type="button"
variant="secondary"
size="xs"
+ disabled={!canManageAccessMembers}
onClick={() => handleRemoveUser(u.platform, u.userId)}
title={t('userList.removeUser')}
className="text-muted hover:border-destructive/40 hover:text-destructive-ink"
diff --git a/ui/src/components/steps/WeChatConfig.tsx b/ui/src/components/steps/WeChatConfig.tsx
index 999c55865..041d7b983 100644
--- a/ui/src/components/steps/WeChatConfig.tsx
+++ b/ui/src/components/steps/WeChatConfig.tsx
@@ -1,3 +1,4 @@
+import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import {
@@ -44,6 +45,8 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
onCancel,
autoStartLogin = true,
}) => {
+ const { capabilities } = useInstanceAuthorization();
+ const canManageAccessMembers = capabilities.can_manage_access_members;
const { t } = useTranslation();
const api = useApi();
const [applying, setApplying] = useState(false);
@@ -84,6 +87,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
}, [stopPolling]);
const startLogin = useCallback(async () => {
+ if (!canManageAccessMembers) return;
setStarting(true);
setLoginState('idle');
setMessage('');
@@ -137,18 +141,18 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
} finally {
setStarting(false);
}
- }, [api, stopPolling, t]);
+ }, [api, stopPolling, t, canManageAccessMembers]);
useEffect(() => {
if (autoStartedRef.current) return;
- if (!autoStartLogin) return;
+ if (!autoStartLogin || !canManageAccessMembers) return;
if (starting) return;
if (loginState !== 'idle') return;
if (hasSavedBotToken) return;
autoStartedRef.current = true;
void startLogin();
- }, [autoStartLogin, loginState, startLogin, starting, hasSavedBotToken]);
+ }, [autoStartLogin, loginState, startLogin, starting, hasSavedBotToken, canManageAccessMembers]);
const startPolling = (key: string) => {
stopPolling();
@@ -363,6 +367,15 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
</div>
<div className="space-y-4">
+ {!canManageAccessMembers && (
+ <div className="space-y-3 rounded-xl border border-border bg-background px-5 py-4">
+ <p className="text-sm text-muted">{t('wechatConfig.ownerBindingRequired')}</p>
+ <label className="block space-y-2 text-sm">
+ <span>{t('wechatConfig.botToken')}</span>
+ <Input type="password" value={botToken} onChange={(event) => setBotToken(event.target.value)} />
+ </label>
+ </div>
+ )}
{/* Already bound */}
{isAlreadyBound && (
<div className="rounded-xl border border-border bg-background px-6 py-6">
@@ -391,7 +404,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
autoStartedRef.current = true;
void startLogin();
}}
- disabled={starting}
+ disabled={starting || !canManageAccessMembers}
>
<RefreshCw size={14} className={starting ? 'animate-spin' : ''} />
{t('wechatConfig.rebind')}
@@ -404,7 +417,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
{loginState === 'idle' && !botToken && !isAlreadyBound && (
<div className="rounded-xl border border-border bg-background px-6 py-8 text-center">
<div className="mx-auto flex size-14 items-center justify-center rounded-full border border-cyan/30 bg-cyan/[0.06] text-cyan-ink">
- {starting || autoStartLogin ? (
+ {starting || (autoStartLogin && canManageAccessMembers) ? (
<Loader2 size={26} className="animate-spin" />
) : (
<Smartphone size={26} />
@@ -414,7 +427,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
{starting ? t('wechatConfig.starting') : t('wechatConfig.startDescription')}
</p>
{!autoStartLogin && !starting && (
- <Button type="button" variant="brand" size="sm" className="mt-4" onClick={startLogin}>
+ <Button type="button" variant="brand" size="sm" className="mt-4" onClick={startLogin} disabled={!canManageAccessMembers}>
<RefreshCw size={14} strokeWidth={2.25} />
{t('wechatConfig.startLogin')}
</Button>
@@ -503,7 +516,7 @@ export const WeChatConfig: React.FC<WeChatConfigProps> = ({
<h3 className="text-[14px] font-semibold text-foreground">{t('wechatConfig.errorTitle')}</h3>
<p className="mt-1 text-[12px] text-destructive-ink">{message}</p>
</div>
- <Button variant="brand" size="sm" onClick={startLogin} disabled={starting}>
+ <Button variant="brand" size="sm" onClick={startLogin} disabled={starting || !canManageAccessMembers}>
<RefreshCw size={14} strokeWidth={2.25} />
{t('wechatConfig.retry')}
</Button>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b1e2b79e0..ef460fe9c 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2944,6 +2944,8 @@
"step5OpenLink": "Open Version Management"
},
"wechatConfig": {
+ "ownerBindingRequired": "QR login also grants user access and requires the instance Owner. You can update an existing bot token and connection settings here.",
+ "botToken": "Bot token",
"eyebrow": "WeChat",
"title": "WeChat Setup",
"subtitle": "Scan the QR code with your WeChat to connect.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 91dea846b..b71bef299 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2944,6 +2944,8 @@
"step5OpenLink": "打开版本管理"
},
"wechatConfig": {
+ "ownerBindingRequired": "扫码登录会同时授予用户访问权限,需要实例所有者操作。你可以在这里更新已有的机器人令牌和连接设置。",
+ "botToken": "机器人令牌",
"eyebrow": "微信",
"title": "微信设置",
"subtitle": "使用微信扫描二维码以连接。",
diff --git a/vibe/api.py b/vibe/api.py
index 54065eef8..ca1caa548 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1148,10 +1148,16 @@ def save_config(
*,
validate_remote_access_network: bool = True,
generic_remote_access: bool = False,
+ user_context: Any = None,
) -> V2Config:
"""Save general settings while preserving Memory's dedicated settings block."""
if not isinstance(payload, dict):
raise ValueError("Config payload must be an object")
+ from vibe.authorization import require_instance_role
+
+ context = require_instance_role(user_context, "editor")
+ if not context.can_manage_instance:
+ payload = editor_config_write_payload(payload)
# This read-only projection is returned by GET /api/config so the browser
# can explain a recovered load; it must never become persisted config data.
@@ -1231,6 +1237,10 @@ def save_config(
merged_payload = _merge_legacy_discord_guild_scope_fields(merged_payload, payload, base_config)
sanitized_payload, guild_scope_update = _extract_settings_scopes_from_config_payload(merged_payload)
config = V2Config.from_payload(sanitized_payload)
+ if not context.can_manage_access_members:
+ from core.services.settings import default_config
+
+ _require_preserved_config_access(base_config or default_config(), config)
connector_controls_changed = (
base_config is not None
and _remote_access_connector_control_signature(config)
@@ -1257,13 +1267,13 @@ def save_config(
)
_validate_enabled_platform_runtime_credentials(config, payload, base_config)
if guild_scope_update is not None:
- _save_discord_guild_scope_update(*guild_scope_update)
+ _save_discord_guild_scope_update(*guild_scope_update, user_context=context)
elif base_config is not None:
store = SettingsStore.get_instance()
if not store.has_guild_scope_for_platform("discord"):
existing_update = _discord_guild_scope_from_config(base_config)
if existing_update is not None:
- _save_discord_guild_scope_update(*existing_update, store=store)
+ _save_discord_guild_scope_update(*existing_update, store=store, user_context=context)
config.save()
try:
from core.message_mirror import reset_activity_flag_cache
@@ -1292,6 +1302,26 @@ def save_config(
return persisted
+def _require_preserved_config_access(current: V2Config, candidate: V2Config) -> None:
+ """Generic manager saves cannot change admission or pairing, even via aliases."""
+ from vibe.authorization import InstanceAuthorizationError
+
+ def policy(config):
+ return (
+ config.remote_access,
+ config.ui.trusted_public_origins,
+ tuple(
+ bool(getattr(getattr(config, p), "require_bind", False))
+ for p in ("slack", "discord", "telegram", "lark", "wechat")
+ ),
+ getattr(config.telegram, "allowed_user_ids", None) or [],
+ getattr(config.telegram, "allowed_chat_ids", None) or [],
+ )
+
+ if policy(current) != policy(candidate):
+ raise InstanceAuthorizationError("owner")
+
+
def save_memory_config(
memory_payload: dict,
*,
@@ -5248,85 +5278,97 @@ def _normalize_show_message_types_for_platform(show_message_types: Optional[list
return normalized
-def save_settings(payload: dict) -> dict:
- store = SettingsStore.get_instance()
- platform = payload.get("platform") or _current_platform()
-
- if "channels" in payload:
- channels = {}
- for channel_id, channel_payload in (payload.get("channels") or {}).items():
- channels[channel_id] = ChannelSettings(
- enabled=channel_payload.get("enabled", True),
- show_message_types=_normalize_show_message_types_for_platform(
- channel_payload.get("show_message_types"), platform
- ),
- custom_cwd=channel_payload.get("custom_cwd"),
- routing=_parse_routing(_normalize_backend_routing_payload(channel_payload.get("routing") or {})),
- require_mention=channel_payload.get("require_mention"),
- require_bind=channel_payload.get("require_bind"),
- _agent_name_at_load=channel_payload.get(
- "expected_agent_name", _UNSET_AGENT_BINDING
- ),
- )
- store.set_channels_for_platform(platform, channels)
- if "guilds" in payload or "guild_allowlist" in payload:
- guilds, default_enabled = _guild_scope_update_from_settings_payload(store, platform, payload)
- store.set_guilds_for_platform(platform, guilds, default_enabled=default_enabled)
- store.save()
- return _settings_to_payload(store, platform=platform)
+def save_settings(payload: dict, *, user_context: Any = None) -> dict:
+ from vibe.authorization import require_instance_role
+ require_instance_role(user_context, "member")
+ # Keep unvalidated request candidates out of the process-wide cache.
+ with contextlib.closing(SettingsStore()) as store:
+ platform = payload.get("platform") or _current_platform()
+
+ if "channels" in payload:
+ channels = {}
+ for channel_id, channel_payload in (payload.get("channels") or {}).items():
+ existing = store.find_channel(channel_id, platform=platform)
+ channels[channel_id] = ChannelSettings(
+ enabled=channel_payload.get("enabled", True),
+ show_message_types=_normalize_show_message_types_for_platform(
+ channel_payload.get("show_message_types"), platform
+ ),
+ custom_cwd=channel_payload.get("custom_cwd"),
+ routing=_parse_routing(_normalize_backend_routing_payload(channel_payload.get("routing") or {})),
+ require_mention=channel_payload.get("require_mention"),
+ require_bind=channel_payload.get("require_bind", existing.require_bind if existing else None),
+ _agent_name_at_load=channel_payload.get(
+ "expected_agent_name", _UNSET_AGENT_BINDING
+ ),
+ )
+ store.set_channels_for_platform(platform, channels)
+ if "guilds" in payload or "guild_allowlist" in payload:
+ guilds, default_enabled = _guild_scope_update_from_settings_payload(store, platform, payload)
+ store.set_guilds_for_platform(platform, guilds, default_enabled=default_enabled)
+ store.save(user_context=user_context)
+ return _settings_to_payload(store, platform=platform)
-def save_thread_settings(payload: dict) -> dict:
+
+def save_thread_settings(payload: dict, *, user_context: Any = None) -> dict:
"""Create or replace one child-thread settings override."""
- store = SettingsStore.get_instance()
- platform = str(payload.get("platform") or _current_platform())
- channel_id = str(payload.get("channel_id") or "").strip()
- thread_id = str(payload.get("thread_id") or "").strip()
- settings_payload = payload.get("settings")
- if platform != "telegram":
- return {"ok": False, "error": "thread settings currently support Telegram only"}
- if not channel_id or not thread_id or not isinstance(settings_payload, dict):
- return {"ok": False, "error": "channel_id, thread_id, and settings are required"}
-
- existing = store.find_thread(channel_id, thread_id, platform=platform)
- base = existing
- if base is None:
- base = store.find_channel(channel_id, platform=platform) or ChannelSettings()
- routing_payload = settings_payload.get("routing")
- routing = (
- _parse_routing(_normalize_backend_routing_payload(routing_payload))
- if isinstance(routing_payload, dict)
- else base.routing
- )
- require_mention = settings_payload.get("require_mention", base.require_mention)
- if existing is None and require_mention is None:
- platform_config = _stored_platform_config(platform)
- require_mention = bool(getattr(platform_config, "require_mention", True))
- settings = ChannelSettings(
- enabled=bool(settings_payload.get("enabled", base.enabled)),
- show_message_types=_normalize_show_message_types_for_platform(
- settings_payload.get("show_message_types", base.show_message_types),
- platform,
- ),
- custom_cwd=settings_payload.get("custom_cwd", base.custom_cwd),
- routing=routing,
- require_mention=require_mention,
- require_bind=settings_payload.get("require_bind", base.require_bind),
- _agent_name_at_load=settings_payload.get(
- "expected_agent_name", _UNSET_AGENT_BINDING
- ),
- )
- store.update_thread(channel_id, thread_id, settings, platform=platform)
- return {
- "ok": True,
- "channel_id": channel_id,
- "thread_id": thread_id,
- "settings": _scope_settings_payload(settings, platform),
- }
+ from vibe.authorization import require_instance_role
+
+ require_instance_role(user_context, "member")
+ # Keep unvalidated request candidates out of the process-wide cache.
+ with contextlib.closing(SettingsStore()) as store:
+ platform = str(payload.get("platform") or _current_platform())
+ channel_id = str(payload.get("channel_id") or "").strip()
+ thread_id = str(payload.get("thread_id") or "").strip()
+ settings_payload = payload.get("settings")
+ if platform != "telegram":
+ return {"ok": False, "error": "thread settings currently support Telegram only"}
+ if not channel_id or not thread_id or not isinstance(settings_payload, dict):
+ return {"ok": False, "error": "channel_id, thread_id, and settings are required"}
+
+ existing = store.find_thread(channel_id, thread_id, platform=platform)
+ base = existing
+ if base is None:
+ base = store.find_channel(channel_id, platform=platform) or ChannelSettings()
+ routing_payload = settings_payload.get("routing")
+ routing = (
+ _parse_routing(_normalize_backend_routing_payload(routing_payload))
+ if isinstance(routing_payload, dict)
+ else base.routing
+ )
+ require_mention = settings_payload.get("require_mention", base.require_mention)
+ if existing is None and require_mention is None:
+ platform_config = _stored_platform_config(platform)
+ require_mention = bool(getattr(platform_config, "require_mention", True))
+ settings = ChannelSettings(
+ enabled=bool(settings_payload.get("enabled", base.enabled)),
+ show_message_types=_normalize_show_message_types_for_platform(
+ settings_payload.get("show_message_types", base.show_message_types),
+ platform,
+ ),
+ custom_cwd=settings_payload.get("custom_cwd", base.custom_cwd),
+ routing=routing,
+ require_mention=require_mention,
+ require_bind=settings_payload.get("require_bind", base.require_bind),
+ _agent_name_at_load=settings_payload.get(
+ "expected_agent_name", _UNSET_AGENT_BINDING
+ ),
+ )
+ store.update_thread(channel_id, thread_id, settings, platform=platform, user_context=user_context)
+ return {
+ "ok": True,
+ "channel_id": channel_id,
+ "thread_id": thread_id,
+ "settings": _scope_settings_payload(settings, platform),
+ }
-def delete_thread_settings(platform: str, channel_id: str, thread_id: str) -> dict:
+def delete_thread_settings(platform: str, channel_id: str, thread_id: str, *, user_context: Any = None) -> dict:
"""Remove one child-thread override so it inherits its parent channel again."""
+ from vibe.authorization import require_instance_role
+
+ require_instance_role(user_context, "member")
platform = str(platform or "").strip()
channel_id = str(channel_id or "").strip()
thread_id = str(thread_id or "").strip()
@@ -5334,9 +5376,10 @@ def delete_thread_settings(platform: str, channel_id: str, thread_id: str) -> di
return {"ok": False, "error": "thread settings currently support Telegram only"}
if not channel_id or not thread_id:
return {"ok": False, "error": "channel_id and thread_id are required"}
- store = SettingsStore.get_instance()
- removed = store.delete_thread(channel_id, thread_id, platform=platform)
- return {"ok": True, "removed": removed, "channel_id": channel_id, "thread_id": thread_id}
+ # Keep unvalidated request candidates out of the process-wide cache.
+ with contextlib.closing(SettingsStore()) as store:
+ removed = store.delete_thread(channel_id, thread_id, platform=platform, user_context=user_context)
+ return {"ok": True, "removed": removed, "channel_id": channel_id, "thread_id": thread_id}
def _guild_scope_update_from_settings_payload(
@@ -5420,10 +5463,16 @@ def _save_discord_guild_scope_update(
guilds: dict[str, GuildSettings],
default_enabled: bool,
store: Optional[SettingsStore] = None,
+ *,
+ user_context: Any = None,
) -> None:
- target_store = store or SettingsStore.get_instance()
- target_store.set_guilds_for_platform("discord", guilds, default_enabled=default_enabled)
- target_store.save()
+ # Config writes and legacy migrations need the same private candidate as
+ # channel/DM writes; another Owner request must never commit this draft.
+ with contextlib.closing(SettingsStore(store.settings_path if store else None)) as candidate:
+ candidate.set_guilds_for_platform("discord", guilds, default_enabled=default_enabled)
+ candidate.save(user_context=user_context)
+ if store is not None:
+ store.maybe_reload()
def _extract_settings_scopes_from_config_payload(
@@ -5634,7 +5683,9 @@ async def telegram_auth_test_async(bot_token: str, proxy_url: str | None = None)
return {"ok": False, "error": str(exc)}
-def delete_channel_scope(platform: str, native_id: str, scope_type: str = "channel") -> dict:
+def delete_channel_scope(
+ platform: str, native_id: str, scope_type: str = "channel", *, user_context: Any = None,
+) -> dict:
"""Permanently remove a discovered channel/chat scope and its settings.
Restricted to ``channel`` scopes: this endpoint exists only to clear stale
@@ -5643,6 +5694,7 @@ def delete_channel_scope(platform: str, native_id: str, scope_type: str = "chann
so any non-channel scope type is rejected.
"""
from core import chat_discovery
+ from vibe.authorization import InstanceAuthorizationError
platform = str(platform or "").strip()
native_id = str(native_id or "").strip()
@@ -5652,7 +5704,9 @@ def delete_channel_scope(platform: str, native_id: str, scope_type: str = "chann
if scope_type != "channel":
return {"ok": False, "error": "only channel scopes can be removed here"}
try:
- outcome = chat_discovery.delete_scope(platform, native_id, scope_type="channel")
+ outcome = chat_discovery.delete_scope(platform, native_id, scope_type="channel", user_context=user_context)
+ except InstanceAuthorizationError:
+ raise
except Exception as exc:
logger.warning("Failed to delete %s scope %s: %s", platform, native_id, exc, exc_info=True)
return {"ok": False, "error": str(exc)}
@@ -13800,38 +13854,42 @@ def get_users(platform: Optional[str] = None) -> dict:
return {"ok": True, "users": users}
-def save_users(payload: dict) -> dict:
+def save_users(payload: dict, *, user_context: Any = None) -> dict:
"""Save user settings (bulk update from UI)."""
- store = SettingsStore.get_instance()
- platform = payload.get("platform") or _current_platform()
+ from vibe.authorization import require_instance_role
- users = {}
- for user_id, up in (payload.get("users") or {}).items():
- if not isinstance(up, dict):
- continue
- # Preserve dm_chat_id from existing user (not editable via UI)
- existing = store.get_user(user_id, platform=platform)
- users[user_id] = UserSettings(
- display_name=up.get("display_name", ""),
- is_admin=up.get("is_admin", False),
- bound_at=up.get("bound_at", ""),
- enabled=up.get("enabled", True),
- show_message_types=_normalize_show_message_types_for_platform(up.get("show_message_types"), platform),
- custom_cwd=up.get("custom_cwd"),
- routing=_parse_routing(_normalize_backend_routing_payload(up.get("routing") or {})),
- dm_chat_id=existing.dm_chat_id if existing else "",
- pending_bind_menu_hint=existing.pending_bind_menu_hint if existing else False,
- _agent_name_at_load=up.get("expected_agent_name", _UNSET_AGENT_BINDING),
- )
-
- # Merge instead of replace: update existing users and add new ones,
- # but preserve users not included in the payload (e.g. concurrently bound)
- current_users = store.get_users_for_platform(platform)
- for uid, user_settings in users.items():
- current_users[uid] = user_settings
- store.set_users_for_platform(platform, current_users)
- store.save()
- return get_users(platform)
+ require_instance_role(user_context, "member")
+ # Keep unvalidated request candidates out of the process-wide cache.
+ with contextlib.closing(SettingsStore()) as store:
+ platform = payload.get("platform") or _current_platform()
+
+ users = {}
+ for user_id, up in (payload.get("users") or {}).items():
+ if not isinstance(up, dict):
+ continue
+ # Preserve dm_chat_id from existing user (not editable via UI)
+ existing = store.get_user(user_id, platform=platform)
+ users[user_id] = UserSettings(
+ display_name=up.get("display_name", ""),
+ is_admin=up.get("is_admin", existing.is_admin if existing else False),
+ bound_at=up.get("bound_at", existing.bound_at if existing else ""),
+ enabled=up.get("enabled", existing.enabled if existing else True),
+ show_message_types=_normalize_show_message_types_for_platform(up.get("show_message_types"), platform),
+ custom_cwd=up.get("custom_cwd"),
+ routing=_parse_routing(_normalize_backend_routing_payload(up.get("routing") or {})),
+ dm_chat_id=existing.dm_chat_id if existing else "",
+ pending_bind_menu_hint=existing.pending_bind_menu_hint if existing else False,
+ _agent_name_at_load=up.get("expected_agent_name", _UNSET_AGENT_BINDING),
+ )
+
+ # Merge instead of replace: update existing users and add new ones,
+ # but preserve users not included in the payload (e.g. concurrently bound)
+ current_users = store.get_users_for_platform(platform)
+ for uid, user_settings in users.items():
+ current_users[uid] = user_settings
+ store.set_users_for_platform(platform, current_users)
+ store.save(user_context=user_context)
+ return get_users(platform)
def toggle_admin(user_id: str, is_admin: bool, platform: Optional[str] = None) -> dict:
diff --git a/vibe/authorization.py b/vibe/authorization.py
index a45886e5f..aad344ad7 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -402,9 +402,8 @@ _VIEWER_HTTP_MUTATION_RULES = (
)
# Pairing identity, member set, and ownership stay Owner-only. Writes under
-# /api/remote-access default to owner so a newly added pair/unpair/settings
-# sibling cannot slip through as member. The ops below cannot change instance
-# id, backend URL, or secrets, so member keeps them.
+# /api/remote-access default to Owner. Explicit tunnel operations below preserve
+# pairing identity; the settings writer accepts only transport/recovery fields.
_REMOTE_ACCESS_HTTP_NAMESPACE = "/api/remote-access"
_REMOTE_ACCESS_MEMBER_HTTP_RULES = tuple(
(method, re.compile(pattern))
@@ -413,68 +412,44 @@ _REMOTE_ACCESS_MEMBER_HTTP_RULES = tuple(
("GET", r"^/api/remote-access/network-interfaces$"),
("POST", r"^/api/remote-access/optimize-route$"),
("POST", r"^/api/remote-access/diagnostics$"),
+ ("POST", r"^/api/remote-access/(?:start|stop|settings)$"),
)
)
-# The member surface is an allow-list, and the unknown-route default is Owner.
-#
-# Enumerating the Owner exceptions instead was tried and does not converge: with
-# an unknown route defaulting to member, adding the member rank silently widened
-# every `/api/*` route that no other table classified -- 112 of them, including
-# `POST /api/control`, `POST /api/upgrade`, every `/api/backend/*/auth` route,
-# and the resource/project ACL PUTs. Review found members of that set one head at
-# a time because a list of exceptions is only ever as complete as the last audit.
-#
-# Inverting makes the omission safe in the other direction: a route absent from
-# this table keeps exactly the role it had before the member rank existed, so a
-# newly added management route cannot become member-reachable by accident and the
-# blast radius of this capability is bounded by what is written here.
-#
-# What belongs here: the routes backing the capabilities the member rank is
-# defined to grant -- ``can_manage_agents`` (Agent CRUD and the model routing an
-# Agent is configured against) and ``can_manage_projects``, plus read-only
-# instance state. What deliberately does not, and is therefore Owner:
-# * anything that mints, revokes, or promotes instance access -- the cloud
-# allowlist, IM bound users, and bind codes. A bind code is a bearer
-# credential, so *listing* them is equivalent to minting and stays Owner
-# while ``GET /api/users`` is a member read.
-# * anything holding or minting a credential -- `/api/backend/*/auth`, model
-# source credentials and OAuth, and the platform `auth_test`/channel probes
-# that take a bot token.
-# * instance lifecycle and host reach -- control, upgrade, ui/reload, logs,
-# doctor writes, dependency installs, and the filesystem browse routes.
-# * anything that changes an ACL or the IM access boundary -- the resource and
-# project access PUTs, and the channel/thread settings writes that carry
-# ``require_bind``.
-# * bulk Agent onboarding, a one-way instance-wide migration whose GET
-# discloses every Agent row and whose POST claims every policy-less one under
-# the caller's private ACL.
+# Instance management follows Member capabilities, using an explicit method/path
+# inventory. Unknown APIs remain Owner-only. Access-member/role administration,
+# pairing identity, Project/Resource ACL changes, WeChat's combined login/binding,
+# and bulk Agent ownership migration deliberately remain outside this table.
+# Mixed config/scope writers also preserve access policy at their locked commit.
_MEMBER_HTTP_RULES = tuple(
(method, re.compile(pattern))
for method, pattern in (
- # can_manage_agents: Agent CRUD and instance-wide default selection.
- # /api/agent-onboarding is a bulk migration and stays Owner by default.
- #
- # ``/api/agent/<name>/install`` is absent on purpose, and so is its job
- # status sibling: the handler runs a package manager, a self-update, or a
- # curl script on the host, persists the resulting CLI path, and may
- # restart the backend. That is the "dependency installs" bullet above --
- # host lifecycle, not Agent CRUD -- and it reached member only because
- # this table was written by hand while the policy sat in a comment. There
- # is no owner exception listed for it because none is needed: an absent
- # route keeps the role it had before the member rank existed, which is
- # Owner.
+ # Agent CRUD and instance-wide default selection.
("POST", r"^/api/agents$"),
("PATCH", r"^/api/agents/[^/]+$"),
("DELETE", r"^/api/agents/[^/]+$"),
("POST", r"^/api/agents/import$"),
("POST", r"^/api/agents/default$"),
- # can_manage_agents: selecting among already-authenticated model sources.
- # Adding or re-authenticating a source is credential work and stays Owner.
+ # Model Hub management. Keep this method/path allow-list aligned with
+ # its registered API contract; unknown siblings remain Owner-only.
+ # GET /agents/<backend>/models stays in the Editor model-picker rules.
+ ("GET", r"^/api/models/sources$"),
+ ("POST", r"^/api/models/sources$"),
+ ("POST", r"^/api/models/sources/observe$"),
+ ("PATCH", r"^/api/models/sources/[^/]+$"),
+ ("DELETE", r"^/api/models/sources/[^/]+$"),
+ ("PUT", r"^/api/models/sources/[^/]+/credential$"),
+ ("POST", r"^/api/models/sources/[^/]+/(?:reauth|refresh|probe)$"),
+ ("POST", r"^/api/models/sources/[^/]+/models$"),
+ # Model IDs are path parameters and may contain vendor/model slashes.
+ ("PATCH", r"^/api/models/sources/[^/]+/models/.+$"),
+ ("DELETE", r"^/api/models/sources/[^/]+/models/.+$"),
("GET", r"^/api/models/agents$"),
("GET", r"^/api/models/agents/[^/]+/chains$"),
("GET", r"^/api/models/agents/[^/]+/chain$"),
("PUT", r"^/api/models/agents/[^/]+/chain$"),
+ ("DELETE", r"^/api/models/agents/[^/]+/chain$"),
+ ("POST", r"^/api/models/agents/[^/]+/chain/preview$"),
("GET", r"^/api/models/agents/[^/]+/sources$"),
("PUT", r"^/api/models/agents/[^/]+/sources$"),
("GET", r"^/api/models/agents/[^/]+/models/candidates$"),
@@ -482,7 +457,15 @@ _MEMBER_HTTP_RULES = tuple(
("GET", r"^/api/models/catalog/models-dev$"),
("PATCH", r"^/api/models/agents/[^/]+/mode$"),
("POST", r"^/api/models/agents/[^/]+/chains/reorder$"),
- ("GET", r"^/api/models/sources$"),
+ ("POST", r"^/api/models/agents/[^/]+/probe$"),
+ ("GET", r"^/api/models/agents/[^/]+/provenance$"),
+ ("GET", r"^/api/models/(?:events|usage)$"),
+ ("POST", r"^/api/models/oauth/(?:start|submit|cancel)$"),
+ ("GET", r"^/api/models/oauth/status/[^/]+$"),
+ ("POST", r"^/api/models/migration/(?:scan|apply)$"),
+ ("GET", r"^/api/models/turns/[^/]+/provenance$"),
+ ("GET", r"^/api/models/runtime/status$"),
+ ("POST", r"^/api/models/runtime/(?:install|start|stop)$"),
# can_manage_agents: instance-wide prompt text, not a credential.
("GET", r"^/api/global-prompts$"),
("PUT", r"^/api/global-prompts$"),
@@ -494,7 +477,69 @@ _MEMBER_HTTP_RULES = tuple(
("DELETE", r"^/api/projects/[^/]+$"),
("GET", r"^/api/projects/[^/]+/agents-md$"),
("PUT", r"^/api/projects/[^/]+/agents-md$"),
- # Read-only instance state. The member set is readable, not writable.
+ # General instance settings; mixed writes retain access-administration guards.
+ ("GET", r"^/api/doctor$"),
+ ("PUT", r"^/api/workbench/prefs$"),
+ ("GET", r"^/api/cli/detect$"),
+ ("GET", r"^/api/slack/manifest$"),
+ ("POST", r"^/api/control$"),
+ ("POST", r"^/api/ui/reload$"),
+ ("POST", r"^/api/settings$"),
+ ("POST", r"^/api/settings/thread$"),
+ ("DELETE", r"^/api/settings/thread$"),
+ ("POST", r"^/api/slack/auth_test$"),
+ ("POST", r"^/api/slack/channels$"),
+ ("POST", r"^/api/discord/auth_test$"),
+ ("POST", r"^/api/discord/guilds$"),
+ ("POST", r"^/api/discord/channels$"),
+ ("POST", r"^/api/channels/delete$"),
+ ("POST", r"^/api/telegram/auth_test$"),
+ ("POST", r"^/api/telegram/chats$"),
+ ("POST", r"^/api/lark/auth_test$"),
+ ("POST", r"^/api/lark/chats$"),
+ ("POST", r"^/api/lark/temp_ws/start$"),
+ ("POST", r"^/api/lark/temp_ws/stop$"),
+ ("POST", r"^/api/doctor$"),
+ ("POST", r"^/api/logs$"),
+ ("POST", r"^/api/opencode/options$"),
+ ("POST", r"^/api/upgrade$"),
+ ("POST", r"^/api/opencode/setup-permission$"),
+ ("GET", r"^/api/opencode/permission-status$"),
+ ("GET", r"^/api/claude/agents$"),
+ ("GET", r"^/api/codex/agents$"),
+ ("POST", r"^/api/agent/[^/]+/install$"),
+ ("GET", r"^/api/agent/[^/]+/install/[^/]+$"),
+ ("GET", r"^/api/backend/[^/]+/runtime$"),
+ ("POST", r"^/api/backend/[^/]+/restart$"),
+ ("GET", r"^/api/dependencies$"),
+ ("POST", r"^/api/dependencies/[^/]+/install$"),
+ ("GET", r"^/api/dependencies/[^/]+/install/[^/]+$"),
+ ("GET", r"^/api/backend/codex/auth$"),
+ ("POST", r"^/api/backend/codex/auth$"),
+ ("GET", r"^/api/backend/claude/auth$"),
+ ("POST", r"^/api/backend/claude/auth$"),
+ ("POST", r"^/api/backend/[^/]+/auth/oauth/start$"),
+ ("GET", r"^/api/backend/[^/]+/auth/oauth/status/[^/]+$"),
+ ("POST", r"^/api/backend/[^/]+/auth/oauth/submit-code$"),
+ ("POST", r"^/api/backend/[^/]+/auth/oauth/cancel$"),
+ ("POST", r"^/api/backend/[^/]+/auth/oauth/remove$"),
+ ("POST", r"^/api/backend/claude/auth/oauth/credentials/remove$"),
+ ("POST", r"^/api/backend/[^/]+/auth/api-key/remove$"),
+ ("POST", r"^/api/backend/[^/]+/auth/test$"),
+ ("GET", r"^/api/backend/opencode/providers$"),
+ ("POST", r"^/api/backend/opencode/custom-provider$"),
+ ("DELETE", r"^/api/backend/opencode/custom-provider/[^/]+$"),
+ ("POST", r"^/api/backend/opencode/provider/[^/]+/auth/oauth/start$"),
+ ("POST", r"^/api/backend/opencode/provider/[^/]+/auth$"),
+ ("DELETE", r"^/api/backend/opencode/provider/[^/]+/auth$"),
+ ("POST", r"^/api/backend/opencode/provider/[^/]+/test$"),
+ ("POST", r"^/api/backend/opencode/default-provider$"),
+ ("POST", r"^/api/backend/opencode/provider/[^/]+/models$"),
+ ("DELETE", r"^/api/backend/opencode/provider/[^/]+/models/.+$"),
+ ("POST", r"^/api/browse$"),
+ ("POST", r"^/api/browse/mkdir$"),
+ ("POST", r"^/api/users$"),
+ # Read-only instance state.
("GET", r"^/api/settings$"),
("GET", r"^/api/users$"),
)
@@ -519,7 +564,7 @@ _EDITOR_HTTP_RULES = tuple(
# live endpoint is `/api/backend/opencode/providers`, a Settings surface --
# base URLs, masked API keys, active auth type, tool-call permission
# state -- and reaching it runs `ensure_running()`, which can install a
- # plugin, restart, or launch the daemon. Both stay Owner; the model
+ # plugin, restart, or launch the daemon. This stays Member; the Editor model
# picker treats the refusal as "no catalog" instead.
("GET", r"^/api/models/agents/[^/]+/models$"),
("GET", r"^/api/claude/models$"),
@@ -527,7 +572,7 @@ _EDITOR_HTTP_RULES = tuple(
("GET", r"^/api/running-agents$"),
("POST", r"^/api/running-agents/end$"),
# Files favorites live under /api/browse, not /api/files. Admit only this
- # shared dependency — POST /api/browse and /mkdir stay Owner project-picker
+ # shared dependency — POST /api/browse and /mkdir are Member project-picker
# routes.
("GET", r"^/api/browse/favorites$"),
("GET", r"^/api/cloud/token$"),
@@ -617,10 +662,9 @@ def required_instance_role(method: str, path: str) -> str | None:
Non-API page/static reads are handled by the authenticated shell. Unknown
API routes deliberately default to owner, so a newly added management route
is never reachable by a role that predates it. The member rank widens only
- the routes listed in ``_MEMBER_HTTP_RULES`` plus the read/ops quartet under
- ``/api/remote-access``; access administration, credential and lifecycle
- routes, ACL writes, and bulk Agent migration are Owner by that default
- rather than by per-route exception.
+ the routes listed in ``_MEMBER_HTTP_RULES`` plus the explicit tunnel operations under
+ ``/api/remote-access``. Access administration, ACL writes, pairing, WeChat
+ login/binding and bulk Agent ownership migration remain Owner by default.
"""
return http_authorization_policy(method, path).minimum_role
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f24bc562d..3ff1914e3 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3189,6 +3189,10 @@ def _resolve_log_sources() -> list[dict[str, Any]]:
@app.errorhandler(Exception)
def handle_exception(e):
"""Global exception handler - ensures all errors return JSON."""
+ from vibe.authorization import InstanceAuthorizationError
+
+ if isinstance(e, InstanceAuthorizationError):
+ return jsonify({"ok": False, "error": e.code, "required_role": e.minimum_role}), 403
# Preserve HTTP status codes for client errors (4xx)
status_code = getattr(e, "status_code", None)
detail = getattr(e, "detail", None)
@@ -6622,13 +6626,15 @@ def _schedule_service_restart_for_config_fallback() -> dict[str, Any]:
return {"ok": True, "restart": restart}
-def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, bool, bool, list[str]]:
+def _save_config_and_runtime_decisions(
+ payload: dict, *, user_context: Any = None,
+) -> tuple[V2Config, bool, bool, bool, list[str]]:
from vibe import api
from vibe import remote_access
with CONFIG_LOCK:
previous_config = _load_remote_access_config()
- config = api.save_config(payload, generic_remote_access=True)
+ config = api.save_config(payload, generic_remote_access=True, user_context=user_context)
previous_cloud = previous_config.remote_access.vibe_cloud if previous_config is not None else None
current_cloud = config.remote_access.vibe_cloud
old_instance_id = str(previous_cloud.instance_id or "") if previous_cloud is not None else ""
@@ -6743,24 +6749,10 @@ async def config_post():
# falsy shapes that happen to exist today.
payload = request.json
authorization_context = getattr(g, "authorization_context", None)
- # Persisting a credential is an Owner act, so the write schema is selected
- # by ownership and by nothing else. ``can_manage_instance`` used to pick it,
- # which stopped being an owner test the moment a member acquired that
- # capability: a member fell past this branch into a filter that removed only
- # ``remote_access``, and every other section — ``slack.bot_token``,
- # ``discord.bot_token``, ``lark.app_secret``, gateway secrets — reached the
- # save path and was reconciled onto the live platform.
- #
- # There is one non-owner write schema and it is ``_EDITOR_CONFIG_WRITE_FIELDS``,
- # a closed allowlist of non-secret preferences. Closed is the whole point:
- # no credential-bearing section has to be enumerated here, and a secret
- # added to ``api._PLATFORM_SECRET_FIELDS`` (or to any config section) is
- # unreachable below Owner by construction rather than by remembering to add
- # it to a strip list. Pairing identity is covered by the same rule —
- # ``remote_access`` is not on the allowlist, so it is refused outright
- # instead of silently dropped.
+ # Editors keep their preference-only schema; managers can save ordinary
+ # settings. api.save_config protects admission/pairing at the locked writer.
non_owner_write = (
- authorization_context is not None and not authorization_context.can_manage_access_members
+ authorization_context is not None and not authorization_context.can_manage_instance
)
if non_owner_write:
try:
@@ -6779,6 +6771,7 @@ async def config_post():
) = await asyncio.to_thread(
_save_config_and_runtime_decisions,
payload,
+ user_context=authorization_context,
)
except ValueError as exc:
# Same chokepoint as the allowlist rejection above: a non-owner write
@@ -7410,7 +7403,7 @@ def settings_post():
payload = request.json or {}
try:
- return jsonify(api.save_settings(payload))
+ return jsonify(api.save_settings(payload, user_context=_request_authorization_context()))
except StaleScopeAgentBindingError as exc:
return _settings_conflict_response(exc)
except ScopeAgentUnavailableError as exc:
@@ -7426,7 +7419,10 @@ async def thread_settings_post(starlette_request: FastAPIRequest):
body = await starlette_request.body()
payload = await starlette_request.json() if body else {}
try:
- return api.save_thread_settings(payload if isinstance(payload, dict) else {})
+ return api.save_thread_settings(
+ payload if isinstance(payload, dict) else {},
+ user_context=_request_authorization_context(),
+ )
except StaleScopeAgentBindingError as exc:
return _settings_conflict_response(exc)
except ScopeAgentUnavailableError as exc:
@@ -7445,6 +7441,7 @@ async def thread_settings_delete(starlette_request: FastAPIRequest):
query.get("platform", ""),
query.get("channel_id", ""),
query.get("thread_id", ""),
+ user_context=_request_authorization_context(),
)
return await _dispatch_native_ui_request(starlette_request, handler)
@@ -7526,6 +7523,7 @@ def channels_delete():
payload.get("platform", ""),
payload.get("id", ""),
scope_type=payload.get("scope_type", "channel"),
+ user_context=_request_authorization_context(),
)
)
@@ -12667,12 +12665,9 @@ def users_post():
from vibe import api
from storage.settings_service import ScopeAgentUnavailableError, StaleScopeAgentBindingError
- forbidden = _access_administration_forbidden()
- if forbidden is not None:
- return forbidden
payload = request.json or {}
try:
- return jsonify(api.save_users(payload))
+ return jsonify(api.save_users(payload, user_context=_request_authorization_context()))
except StaleScopeAgentBindingError as exc:
return _settings_conflict_response(exc)
except ScopeAgentUnavailableError as exc:
@@ -15505,7 +15500,7 @@ async def serve_private_show_page(session_id, asset_path):
from core.show_pages import ShowPageError, ShowPageStore, ensure_show_page_dir
authorization_context = _request_authorization_context()
- runtime_retry_authorized = _has_runtime_owner_access(authorization_context)
+ runtime_retry_authorized = bool(authorization_context and authorization_context.can_manage_instance)
markdown_requested = _is_show_page_markdown_request(asset_path, request._request)
store = ShowPageStore()
try: