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(vaults): align controls with management tiers (#2732)

Call White7e966739de4e
diff --git a/docs/plans/editor-permission-audit.md b/docs/plans/editor-permission-audit.md
index 275022fb8..74a84609a 100644
--- a/docs/plans/editor-permission-audit.md
+++ b/docs/plans/editor-permission-audit.md
@@ -336,7 +336,7 @@ correct here is not a claim that its whole surface was exercised.
| Standalone and IM Sessions | E/V effective Session role is None without a Project, including Personal | Boundary retained. **Fixed:** the alternate CLI producer that bypassed it |
| Harness Task/Watch/Run | E namespace; producers use `ensure_harness_definition_write`; execution checks Agent, current binding and the final Session boundary | **Fixed:** class A refresh, class C Run/callback producers. The proposed org-aware Harness ACL is not shipped and was not used to manufacture a finding |
| Skills | E; `core/services/skills.py` grants Editor use/management, project-scoped mutation also needs Project Editor | Correct as shipped |
-| Vault secrets/request/grant/audit/settings/pin/reveal/sign | E is only the HTTP floor; metadata/pin/rotation/deletion add M; proof and approval rules stand | **Fixed:** class B Personal use, class C deferred auto-resume and the request-target pre-check, direct CLI metadata |
+| Vault secrets/request/grant/audit/settings/pin/reveal/sign | E is only the HTTP floor; metadata/pin/rotation/deletion and instance-wide protection settings add M; `last_grant_ttl` and grant revocation stay E; proof and approval rules stand | **Fixed:** class B Personal use, class C deferred auto-resume and the request-target pre-check, direct CLI metadata. Vaults controls follow their consuming capability, not the route floor |
| Memory | V namespace with the Memory principal and its identity isolation | Correct; no Owner-like Memory principal for E/M |
| Files | E namespace; `file_browser_service` retains path/OS/size/symlink/write-race rules | Correct. No per-Project filesystem sandbox is shipped or proposed here |
| Terminal websocket and DELETE | WS E with signed context/origin, terminal id subject-scoped; DELETE V so a downgraded user can close their own terminal | Correct |
@@ -350,6 +350,16 @@ correct here is not a claim that its whole surface was exercised.
| Access/identity/pairing/bind codes/onboarding/users admin | O exact routes; IM admin identity separate | No new grants. **Fixed:** `vibe remote pair` now refuses at the CLI before soliciting a key |
| SQL/CLI diagnostics | Read-only SQL `skill_usage_daily` and `agent_events` at M; raw Vault data denied | Retained. The CLI families are covered by the floor table, not by a universal Owner exception |
+Vault settings retain their Editor GET/PATCH route tier. The service checks
+`can_manage_instance` before any write when a payload contains `strict_approvals`
+or `unlock_window_seconds`, rejecting mixed payloads atomically. The settings
+gear/dialog are therefore management-only. `last_grant_ttl` stays Editor-writable
+because approval cards remember the grant duration for every approver. Revoke
+also stays Editor-tier by design: `_require_secret_names_access` admits Editors
+before its management branch. The HTTP role table in
+`test_member_management_parity.py` and the VaultsPage capability table pin these
+boundaries; the existing route-tier parity fixture is unchanged.
+
## Scenario coverage
Registered in `tests/scenarios/permissions/catalog.yaml`, with
diff --git a/storage/vault_service.py b/storage/vault_service.py
index 3d891b193..fed562a89 100644
--- a/storage/vault_service.py
+++ b/storage/vault_service.py
@@ -440,9 +440,15 @@ def get_vault_settings(conn: Connection) -> dict[str, Any]:
return _normalize_vault_settings(_loads(raw))
-def save_vault_settings(conn: Connection, payload: dict[str, Any]) -> dict[str, Any]:
+def save_vault_settings(conn: Connection, payload: dict[str, Any], *, user_context: Any = None) -> dict[str, Any]:
if not isinstance(payload, dict):
raise VaultServiceError("vault settings payload must be an object")
+ # Instance-wide protection is management-only; approvers may still remember a grant TTL.
+ # Check the whole payload before writing so mixed updates cannot partially succeed.
+ if "unlock_window_seconds" in payload or "strict_approvals" in payload:
+ context = resolve_resource_access_context(user_context)
+ if not context.can_manage_instance:
+ raise VaultSecretAccessError("Vault settings access is not permitted.")
current = get_vault_settings(conn)
updates: dict[str, Any] = {}
if "unlock_window_seconds" in payload:
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index f4a21d497..1520440d9 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -121,6 +121,9 @@ def test_complete_registered_api_management_inventory():
assert len(endpoints) == 289
assert ("GET", "/api/sessions/main") in endpoints
assert http_authorization_policy("POST", "/api/vault/requests/{request_id}/approve-delete").minimum_role == "editor"
+ # Approvers still read policy and remember duration; protection fields add a service check.
+ for method in ("GET", "PATCH"):
+ assert http_authorization_policy(method, "/api/vault/settings").minimum_role == "editor"
for method in ("PUT", "DELETE"):
assert (method, "/api/vault/secrets/{name}/fields/{field}") in endpoints
assert http_authorization_policy(method, "/api/vault/secrets/LOGIN/fields/username").minimum_role == "editor"
@@ -227,6 +230,62 @@ def test_backend_connection_native_route_preserves_management_roles(management_h
ipc.assert_not_awaited()
+ "role, payload, status",
+ [
+ ("editor", {"strict_approvals": True}, 403),
+ ("editor", {"unlock_window_seconds": 1800}, 403),
+ ("editor", {"last_grant_ttl": 900}, 200),
+ ("editor", {"last_grant_ttl": "one-time"}, 200),
+ ("editor", {"strict_approvals": True, "unlock_window_seconds": 1800, "last_grant_ttl": 900}, 403),
+ ("member", {"strict_approvals": True}, 200),
+ ("owner", {"strict_approvals": True}, 200),
+ ],
+)
+def test_vault_settings_patch_http_splits_field_authority(management_http, role, payload, status):
+ """The route remains Editor-tier, but protected settings fields require management."""
+ from sqlalchemy import select
+ from storage import vault_service
+ from storage.models import state_meta
+
+ request = management_http(role)
+ before = request("GET", "/api/vault/settings")
+ assert before.status_code == 200, before.get_json()
+ before_settings = before.get_json()["settings"]
+ engine = api._vault_engine()
+ try:
+ with engine.connect() as conn:
+ stored_before = conn.execute(
+ select(state_meta).where(state_meta.c.key == vault_service.VAULT_SETTINGS_META_KEY)
+ ).first()
+ finally:
+ engine.dispose()
+
+ response = request("PATCH", "/api/vault/settings", payload=payload)
+ assert response.status_code == status, response.get_json()
+ body = response.get_json()
+ after = request("GET", "/api/vault/settings")
+ assert after.status_code == 200, after.get_json()
+ if status == 403:
+ assert body["ok"] is False
+ assert body["code"] == "resource_access_forbidden"
+ assert after.get_json()["settings"] == before_settings
+ engine = api._vault_engine()
+ try:
+ with engine.connect() as conn:
+ stored_after = conn.execute(
+ select(state_meta).where(state_meta.c.key == vault_service.VAULT_SETTINGS_META_KEY)
+ ).first()
+ assert stored_after == stored_before # Not even a normalized/default settings row was written.
+ finally:
+ engine.dispose()
+ else:
+ expected = dict(before_settings)
+ expected.update(payload)
+ assert body["ok"] is True
+ assert body["settings"] == after.get_json()["settings"] == expected
+
+
@pytest.mark.parametrize("role", ["member", "owner"])
def test_manager_saves_config_credentials_and_reads_masked_result(management_http, role):
request = management_http(role)
diff --git a/ui/src/components/workbench/VaultsPage.test.tsx b/ui/src/components/workbench/VaultsPage.test.tsx
index 7dc1a483c..601127ecc 100644
--- a/ui/src/components/workbench/VaultsPage.test.tsx
+++ b/ui/src/components/workbench/VaultsPage.test.tsx
@@ -6,13 +6,15 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testi
import userEvent from '@testing-library/user-event';
import { MemoryRouter, useLocation, useNavigate, useNavigationType } from 'react-router-dom';
import { createInstance } from 'i18next';
+import { initReactI18next } from 'react-i18next';
import en from '../../i18n/en.json';
import zh from '../../i18n/zh.json';
-import type { VaultSecret } from '../../context/ApiContext';
+import type { VaultGrant, VaultSecret } from '../../context/ApiContext';
import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
-import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
+import { InstanceAuthorizationContext, type InstanceAuthorizationValue } from '../../context/InstanceAuthorizationContext';
import { OWNER_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';
+import { capabilitiesFor } from '../../lib/testing/instanceRoleCapabilities';
import { VaultsPage } from './VaultsPage';
type WorkbenchEventHandlers = {
@@ -28,12 +30,15 @@ const api = vi.hoisted(() => ({
getVaultGrants: vi.fn(),
getVaultRequests: vi.fn(),
listVaultSecrets: vi.fn(),
+ listDependencies: vi.fn(),
+ listSkills: vi.fn(),
}));
const showToast = vi.hoisted(() => vi.fn());
const revealProtectedValue = vi.hoisted(() => vi.fn());
const useVaultSandboxWarm = vi.hoisted(() => vi.fn((_enabled: boolean) => true));
const remoteOwner = {
remote: true,
+ instanceKind: 'organization' as const,
instanceRole: 'owner' as const,
capabilities: {
...OWNER_INSTANCE_CAPABILITIES,
@@ -41,15 +46,18 @@ const remoteOwner = {
},
};
-const activeOrgMember = {
+const editor: InstanceAuthorizationValue = {
remote: true,
- instanceRole: 'editor' as const,
- capabilities: {
- ...OWNER_INSTANCE_CAPABILITIES,
- can_manage_instance: false,
- can_use_vault_secrets: true,
- can_use_system: false,
- },
+ instanceKind: 'organization',
+ instanceRole: 'editor',
+ capabilities: capabilitiesFor('editor'),
+};
+
+const member: InstanceAuthorizationValue = {
+ remote: true,
+ instanceKind: 'organization',
+ instanceRole: 'member',
+ capabilities: capabilitiesFor('member'),
};
vi.mock('../../context/ApiContext', async (loadOriginal) => {
@@ -62,14 +70,16 @@ vi.mock('../../context/ToastContext', () => ({
}));
vi.mock('../../lib/useProtectedVault', () => ({
- useProtectedVault: () => ({ revealProtectedValue }),
+ useProtectedVault: () => ({ revealProtectedValue, status: 'locked', refresh: vi.fn(), hasPasskey: () => false }),
+ webauthnAvailable: () => false,
useVaultSandboxWarm,
useVaultLock: () => ({ unlocked: false, remainingMs: 0, lockNow: vi.fn() }),
}));
const testI18n = createInstance();
-void testI18n.init({ lng: 'en', resources: { en: { translation: en }, zh: { translation: zh } }, initAsync: false });
-vi.mock('react-i18next', () => ({
+void testI18n.use(initReactI18next).init({ lng: 'en', resources: { en: { translation: en }, zh: { translation: zh } }, initAsync: false });
+vi.mock('react-i18next', async (loadOriginal) => ({
+ ...await loadOriginal<typeof import('react-i18next')>(),
useTranslation: () => ({ t: testI18n.t }),
}));
@@ -97,7 +107,7 @@ function LocationProbe() {
</>;
}
-function renderPage(context = remoteOwner, entry = '/vaults', active = true) {
+function renderPage(context: InstanceAuthorizationValue = remoteOwner, entry = '/vaults', active = true) {
return render(
<InstanceAuthorizationContext.Provider value={context}>
<MemoryRouter initialEntries={[entry]}>
@@ -118,6 +128,8 @@ beforeEach(async () => {
if (at >= 0) eventHandlers.splice(at, 1);
};
});
+ api.listDependencies.mockResolvedValue({ deps: [] });
+ api.listSkills.mockResolvedValue({ ok: true, skills: [] });
api.getVaultRequests.mockResolvedValue({ requests: [] });
api.listVaultSecrets.mockResolvedValue({ secrets: [] });
api.getVaultGrants.mockResolvedValue({ grants: [] });
@@ -150,14 +162,93 @@ describe('VaultsPage remote audit history', () => {
expect(await screen.findByText('alpha')).toBeTruthy();
});
- it('shows Vault management controls to an Editor', async () => {
- renderPage(activeOrgMember);
+ it('keeps Add secret available to an Editor', async () => {
+ renderPage(editor);
expect(await screen.findByRole('button', { name: 'Add secret' })).toBeTruthy();
expect(screen.queryByText('Read-only')).toBeNull();
});
});
+describe('PERMISSIONS-013 VaultsPage capability-gated management actions', () => {
+ const protectedSecret: VaultSecret = {
+ name: 'protected-secret', description: 'protected deployment', tags: [], kind: 'static', protection: 'protected',
+ signer_kind: null, source: 'user', policy: {}, last_used_at: null, use_count: 0,
+ created_at: '2026-10-01T00:00:00Z', updated_at: '2026-10-01T00:00:00Z',
+ };
+ const standardSecret: VaultSecret = {
+ name: 'standard-secret', description: 'standard deployment', tags: [], kind: 'static', protection: 'standard',
+ signer_kind: null, source: 'user', policy: {}, last_used_at: null, use_count: 0,
+ created_at: '2026-10-02T00:00:00Z', updated_at: '2026-10-02T00:00:00Z',
+ };
+ const keypairSecret: VaultSecret = { ...protectedSecret, name: 'keypair-secret', kind: 'keypair' };
+ const activeGrant: VaultGrant = {
+ id: 'grant-1', source_selector: { env: ['PROD_KEY'] }, session_id: null, purpose: 'run', status: 'active',
+ request_id: null, created_at: '2026-10-01T00:00:00Z', expires_at: '2026-12-31T00:00:00Z', revoked_at: null,
+ member_snapshot: ['protected-secret'], member_count: 1, runtime_member_count: 1,
+ };
+ const cases = [
+ {
+ label: 'Editor', context: editor, canRevoke: true, hasSettings: false,
+ protectedMenu: ['Show value', 'Copy value'], standardMenu: null,
+ },
+ {
+ label: 'Member', context: member, canRevoke: true, hasSettings: true,
+ protectedMenu: ['Show value', 'Copy value', 'Edit secret', 'Delete'], standardMenu: ['Edit secret', 'Delete'],
+ },
+ ] as const;
+
+ const rowFor = (name: string) => {
+ const row = screen.getByText(name, { exact: true }).closest('li');
+ if (!row) throw new Error(`missing row for ${name}`);
+ return row as HTMLElement;
+ };
+
+ it.each(cases)('$label sees only the Vault controls its capability tier permits', async ({ context, canRevoke, hasSettings, protectedMenu, standardMenu }) => {
+ const user = userEvent.setup();
+ api.listVaultSecrets.mockResolvedValue({ secrets: [protectedSecret, standardSecret, keypairSecret] });
+ api.getVaultGrants.mockResolvedValue({ grants: [activeGrant] });
+ renderPage(context);
+
+ expect(await screen.findByRole('button', { name: 'Add secret' })).toBeTruthy();
+ expect(Boolean(screen.queryByRole('button', { name: 'Vault settings' }))).toBe(hasSettings);
+ await screen.findByText('PROD_KEY');
+ // _require_secret_names_access admits Editors before its management branch.
+ expect(Boolean(screen.queryByRole('button', { name: 'Revoke' }))).toBe(canRevoke);
+
+ const protectedRow = rowFor('protected-secret');
+ const protectedTrigger = within(protectedRow).queryByRole('button', { name: 'More actions' });
+ expect(protectedTrigger).toBeTruthy();
+ await user.click(protectedTrigger!);
+ expect(screen.getAllByRole('menuitem').map((item) => item.textContent?.trim())).toEqual(protectedMenu);
+ await user.keyboard('{Escape}');
+
+ for (const name of ['standard-secret', 'keypair-secret']) {
+ const trigger = within(rowFor(name)).queryByRole('button', { name: 'More actions' });
+ if (standardMenu === null) {
+ expect(trigger).toBeNull();
+ } else {
+ expect(trigger).toBeTruthy();
+ await user.click(trigger!);
+ expect(screen.getAllByRole('menuitem').map((item) => item.textContent?.trim())).toEqual(standardMenu);
+ await user.keyboard('{Escape}');
+ }
+ }
+ });
+
+ it('keeps an Editor edit handoff in the list instead of opening a manager-only dialog', async () => {
+ const editorSecret = { ...protectedSecret };
+ api.listVaultSecrets.mockResolvedValue({ secrets: [editorSecret] });
+ renderPage(editor, '/vaults?edit=protected-secret');
+ await screen.findAllByText('protected-secret');
+
+ // Wait for the handoff effect, not the initially absent dialog, before checking its result.
+ await waitFor(() => expect(screen.getByTestId('location').textContent).not.toContain('edit='));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(screen.getByRole('list', { name: 'Vaults' })).toBeTruthy();
+ });
+});
+
describe('VaultsPage list discovery', () => {
const makeSecret = (name: string, overrides: Partial<VaultSecret> = {}): VaultSecret => ({
name, description: `${name} deployment`, tags: [], kind: 'static', protection: 'standard',
@@ -396,7 +487,7 @@ describe('VaultsPage list discovery', () => {
// asserted on the stream stub.
describe('PERMISSIONS-016 VaultsPage wakes an Editor on the bare vaults.updated frame', () => {
it('refetches pending requests from the signal alone', async () => {
- renderPage(activeOrgMember);
+ renderPage(editor);
await waitFor(() => expect(api.getVaultRequests).toHaveBeenCalled());
const before = api.getVaultRequests.mock.calls.length;
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index c0db79c5f..f2b4cae28 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -87,17 +87,18 @@ const SecretRow: React.FC<{
revealField: string | null;
onRevealFieldChange: (field: string) => void;
canManage: boolean;
+ canUse: boolean;
menuOpen: boolean;
onMenuOpenChange: (open: boolean) => void;
/** The open menu's reveal context or sandbox client is not ready yet. */
revealPreparing: boolean;
-}> = ({ secret: s, terms, now, selected, onToggleTag, onEdit, onDelete, onReveal, revealField, onRevealFieldChange, canManage, menuOpen, onMenuOpenChange: setMenuOpen, revealPreparing }) => {
+}> = ({ secret: s, terms, now, selected, onToggleTag, onEdit, onDelete, onReveal, revealField, onRevealFieldChange, canManage, canUse, menuOpen, onMenuOpenChange: setMenuOpen, revealPreparing }) => {
const { t } = useTranslation();
const isKeypair = s.kind === 'keypair';
const isProtected = s.protection === 'protected';
// Reveal is only meaningful for a protected static secret: its plaintext lives sealed and can be
// shown in-sandbox. Standard values aren't sandbox-sealed, and a keypair has no plaintext value.
- const canReveal = isProtected && !isKeypair;
+ const canReveal = canUse && isProtected && !isKeypair;
const fields = vaultFieldNames(s);
const selectedField = revealField === null
? vaultDefaultField(s)
@@ -105,6 +106,7 @@ const SecretRow: React.FC<{
const staleRevealField = canReveal && selectedField === null;
// The sandbox reveal needs its authorization window, which only a browser can pair with.
const revealInBrowser = canReveal && vaultPasskeyNeedsBrowser();
+ const hasMenu = canManage || canReveal;
return (
<li className="flex flex-wrap items-center gap-x-3.5 gap-y-2 rounded-xl border border-border bg-surface px-4 py-3 md:flex-nowrap">
<div
@@ -154,7 +156,7 @@ const SecretRow: React.FC<{
</Badge>
) : null}
</div>
- {canManage ? <div className="shrink-0">
+ {hasMenu ? <div className="shrink-0">
<Popover open={menuOpen} onOpenChange={setMenuOpen}>
<PopoverTrigger asChild>
<Button variant="ghost" size="icon" aria-label={t('vaults.rowActions')} aria-haspopup="menu">
@@ -193,7 +195,6 @@ const SecretRow: React.FC<{
<ExternalLink className="size-4 text-muted" />
{t('vaults.reveal.showInBrowser')}
</button>
- <div className="my-1 h-px bg-border" />
</>
) : !staleRevealField && canReveal ? (
<>
@@ -228,9 +229,10 @@ const SecretRow: React.FC<{
{revealPreparing ? <Loader2 className="size-4 animate-spin text-muted" /> : <Copy className="size-4 text-muted" />}
{t('vaults.reveal.copy')}
</button>
- <div className="my-1 h-px bg-border" />
</>
) : null}
+ {canManage ? <>
+ {canReveal && !staleRevealField ? <div className="my-1 h-px bg-border" /> : null}
<button
type="button"
role="menuitem"
@@ -255,6 +257,7 @@ const SecretRow: React.FC<{
<Trash2 className="size-4" />
{t('vaults.delete')}
</button>
+ </> : null}
</PopoverContent>
</Popover>
</div> : null}
@@ -592,8 +595,9 @@ export const VaultsPage: React.FC = () => {
const { showToast } = useToast();
const vault = useProtectedVault();
const { capabilities } = useInstanceAuthorization();
- const canManage = capabilities.can_use_vault_secrets;
- const canReadVaultState = capabilities.can_use_vault_secrets;
+ const canManageVaultSecrets = capabilities.can_manage_instance;
+ const canUseVaultSecrets = capabilities.can_use_vault_secrets;
+ const canReadVaultState = canUseVaultSecrets;
const [searchParams, setSearchParams] = useSearchParams();
const [secrets, setSecrets] = useState<VaultSecret[]>([]);
const [grants, setGrants] = useState<VaultGrant[]>([]);
@@ -641,10 +645,10 @@ export const VaultsPage: React.FC = () => {
}, [setSearchParams]);
useEffect(() => {
- if (!canManage || step?.kind !== 'add') return;
+ if (!canUseVaultSecrets || step?.kind !== 'add') return;
setAdding({ name: step.name, startProtected: true });
clearStep();
- }, [canManage, step, clearStep]);
+ }, [canUseVaultSecrets, step, clearStep]);
const refresh = useCallback(async () => {
setLoading(true);
@@ -782,16 +786,17 @@ export const VaultsPage: React.FC = () => {
}, [secrets, activeTags, activeSkills, quick, sort, terms, t]);
// Explicit row handoffs win over a hiding view. Clear only the view filters,
- // preserve sort/unrelated params, and consume reveal/edit atomically.
+ // preserve sort/unrelated params, and consume reveal/edit atomically. An Editor's
+ // edit handoff reveals the row, not the manager-only edit dialog.
useEffect(() => {
- if (!canManage || (step?.kind !== 'reveal' && step?.kind !== 'edit')) return;
+ if (!canUseVaultSecrets || (step?.kind !== 'reveal' && step?.kind !== 'edit')) return;
const secret = secrets.find((entry) => entry.name === step.secretName);
if (!secret) return;
const hidden = !visibleSecrets.some((entry) => entry.name === secret.name);
if (step.kind === 'reveal') {
setMenuSecret(secret.name);
setMenuField(step.field ?? null);
- } else {
+ } else if (canManageVaultSecrets) {
setEditTarget(secret);
}
setSearchParams((prev) => {
@@ -799,7 +804,7 @@ export const VaultsPage: React.FC = () => {
if (hidden) for (const key of ['q', 'tag', 'skill', 'filter']) next.delete(key);
return next;
}, { replace: true });
- }, [canManage, step, secrets, visibleSecrets, setSearchParams]);
+ }, [canManageVaultSecrets, canUseVaultSecrets, step, secrets, visibleSecrets, setSearchParams]);
const toggleTag = (tag: string) => {
const key = isSkillTag(tag) ? 'skill' : 'tag';
@@ -842,6 +847,7 @@ export const VaultsPage: React.FC = () => {
[api, t],
);
const menuRevealKey = useMemo(() => {
+ if (!canUseVaultSecrets) return null;
const secret = secrets.find((entry) => entry.name === menuSecret);
if (secret?.protection !== 'protected' || secret.kind === 'keypair' || vaultPasskeyNeedsBrowser()) return null;
if (menuField !== null && !vaultFieldNames(secret).includes(menuField)) return null;
@@ -850,7 +856,7 @@ export const VaultsPage: React.FC = () => {
field: menuField ?? vaultDefaultField(secret),
version: vaultFieldFingerprint(secret),
};
- }, [secrets, menuSecret, menuField]);
+ }, [canUseVaultSecrets, secrets, menuSecret, menuField]);
const revealContext = usePreparedRequest(menuRevealKey, requestRevealContext, revealContextIssued, PREPARED_REVEAL);
const revealSandboxReady = useVaultSandboxWarm(menuRevealKey !== null);
// Show and Copy wait for both, so their click never waits on either.
@@ -922,7 +928,7 @@ export const VaultsPage: React.FC = () => {
stackActionsOnMobile
actions={
<>
- {canManage ? <VaultLockIndicator className="max-sm:order-last max-sm:w-full max-sm:justify-between" /> : null}
+ {canUseVaultSecrets ? <VaultLockIndicator className="max-sm:order-last max-sm:w-full max-sm:justify-between" /> : null}
{canReadVaultState ? <Button
variant={showAudit ? 'secondary' : 'ghost'}
size="icon"
@@ -932,7 +938,7 @@ export const VaultsPage: React.FC = () => {
>
<History className="size-4" />
</Button> : null}
- {canManage ? <Button
+ {canManageVaultSecrets ? <Button
variant={showSettings ? 'secondary' : 'ghost'}
size="icon"
className="max-sm:border max-sm:border-border max-sm:bg-surface"
@@ -950,7 +956,7 @@ export const VaultsPage: React.FC = () => {
>
<RefreshCw className="size-4" />
</Button>
- {canManage ? (
+ {canUseVaultSecrets ? (
<Button className="max-sm:flex-1" onClick={() => setAdding({ startProtected: false })}>
<Plus className="size-4" />
{t('vaults.add')}
@@ -967,7 +973,7 @@ export const VaultsPage: React.FC = () => {
{error && (
<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">{error}</div>
)}
- {canManage ? (
+ {canUseVaultSecrets ? (
<PendingRequestsSection
onResolved={refresh}
focusRequestId={step?.kind === 'request' ? step.requestId : null}
@@ -985,7 +991,7 @@ export const VaultsPage: React.FC = () => {
</div>
<div className="flex flex-wrap gap-2">
{grants.map((g) => (
- <GrantChip key={g.id} grant={g} now={now} onRevoke={canManage ? onRevokeGrant : undefined} />
+ <GrantChip key={g.id} grant={g} now={now} onRevoke={canUseVaultSecrets ? onRevokeGrant : undefined} />
))}
</div>
</div>
@@ -1059,7 +1065,8 @@ export const VaultsPage: React.FC = () => {
onReveal={revealSecret}
revealField={s.name === menuSecret ? menuField : null}
onRevealFieldChange={setMenuField}
- canManage={canManage}
+ canManage={canManageVaultSecrets}
+ canUse={canUseVaultSecrets}
menuOpen={s.name === menuSecret}
revealPreparing={s.name === menuRevealKey?.name && revealPreparing}
onMenuOpenChange={(open) => {
@@ -1088,8 +1095,8 @@ export const VaultsPage: React.FC = () => {
)}
</div>
)}
- {canManage ? <VaultSettingsDialog open={showSettings} onOpenChange={setShowSettings} /> : null}
- {canManage ? <VaultSecretDialog
+ {canManageVaultSecrets ? <VaultSettingsDialog open={showSettings} onOpenChange={setShowSettings} /> : null}
+ {canUseVaultSecrets ? <VaultSecretDialog
open={adding != null}
name={adding?.name}
startProtected={adding?.startProtected}
@@ -1103,7 +1110,7 @@ export const VaultsPage: React.FC = () => {
refresh();
}}
/> : null}
- {canManage ? <VaultSecretDialog
+ {canManageVaultSecrets ? <VaultSecretDialog
open={editTarget != null}
editSecret={activeEditSecret}
onOpenChange={(o) => {
@@ -1118,7 +1125,7 @@ export const VaultsPage: React.FC = () => {
}}
/> : null}
<ConfirmDialog
- open={deleteTarget != null}
+ open={canManageVaultSecrets && deleteTarget != null}
onOpenChange={(open) => {
if (!open) setDeleteTarget(null);
}}
diff --git a/ui/src/lib/vaultBrowserHandoff.test.tsx b/ui/src/lib/vaultBrowserHandoff.test.tsx
index df50feac5..bbd3f478a 100644
--- a/ui/src/lib/vaultBrowserHandoff.test.tsx
+++ b/ui/src/lib/vaultBrowserHandoff.test.tsx
@@ -9,6 +9,8 @@ import { MemoryRouter } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { VaultRequest, VaultSecret } from '@/context/ApiContext';
+import { InstanceAuthorizationContext } from '@/context/InstanceAuthorizationContext';
+import { capabilitiesFor } from '@/lib/testing/instanceRoleCapabilities';
import { VaultApprovalCard } from '@/components/ui/vault-approval-card';
import { VaultRequestCard } from '@/components/ui/vault-request-card';
import { VaultSecretForm } from '@/components/ui/vault-secret-form';
@@ -47,9 +49,6 @@ const vault = vi.hoisted(() => ({
vi.mock('@/context/ApiContext', () => ({ useApi: () => api }));
vi.mock('@/context/ToastContext', () => ({ useToast: () => ({ showToast: vi.fn() }) }));
-vi.mock('@/context/InstanceAuthorizationContext', () => ({
- useInstanceAuthorization: () => ({ capabilities: { can_use_vault_secrets: true } }),
-}));
vi.mock('@/lib/useProtectedVault', () => ({
useProtectedVault: () => vault,
useVaultLock: () => ({ unlocked: false, remainingMs: 0, lockNow: vi.fn() }),
@@ -161,6 +160,7 @@ const cases: Array<{
requests?: VaultRequest[];
secrets?: VaultSecret[];
vaultStatus?: string;
+ role?: 'editor' | 'member';
resumed: () => Promise<void>;
}> = [
{
@@ -228,6 +228,7 @@ const cases: Array<{
},
{
surface: 'protected field edit',
+ role: 'member', // Editing is management-only; other handoffs remain Editor use.
desktop: () => <VaultSecretForm editSecret={protectedSecret} onCancel={vi.fn()} onCreated={vi.fn()} />,
clicks: [openInBrowser],
secrets: [protectedSecret],
@@ -240,11 +241,15 @@ const cases: Array<{
const ceremonies = [vault.setupPasskey, vault.unlockPasskey, vault.approveProtectedRelease, vault.signProtectedRequest, vault.revealProtectedValue];
-function renderAt(path: string, ui: ReactElement) {
+function renderAt(path: string, ui: ReactElement, role: 'editor' | 'member' = 'editor') {
return render(
- <I18nextProvider i18n={i18n}>
- <MemoryRouter initialEntries={[path]}>{ui}</MemoryRouter>
- </I18nextProvider>,
+ <InstanceAuthorizationContext.Provider value={{
+ remote: true, instanceKind: 'organization', instanceRole: role, capabilities: capabilitiesFor(role),
+ }}>
+ <I18nextProvider i18n={i18n}>
+ <MemoryRouter initialEntries={[path]}>{ui}</MemoryRouter>
+ </I18nextProvider>
+ </InstanceAuthorizationContext.Provider>,
);
}
@@ -304,7 +309,7 @@ describe('desktop shell protected-vault browser handoff', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null);
Object.defineProperty(window, '__AVIBE_DESKTOP_SHELL__', { configurable: true, value: true });
- renderAt('/vaults', c.desktop());
+ renderAt('/vaults', c.desktop(), c.role);
for (const click of c.clicks) await user.click(await screen.findByRole(click.role, { name: click.name }));
expect(open).toHaveBeenCalledTimes(1);
@@ -318,7 +323,7 @@ describe('desktop shell protected-vault browser handoff', () => {
cleanup();
delete (window as { __AVIBE_DESKTOP_SHELL__?: true }).__AVIBE_DESKTOP_SHELL__;
- renderAt(`${target.pathname}${target.search}`, <VaultsPage />);
+ renderAt(`${target.pathname}${target.search}`, <VaultsPage />, c.role);
await c.resumed();
expect(open).toHaveBeenCalledTimes(1);
diff --git a/vibe/api.py b/vibe/api.py
index 53936f014..a9a860049 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -3305,7 +3305,7 @@ def get_vault_settings() -> dict:
return {"ok": True, "settings": settings, "policy": vault_service.vault_session_policy(settings)}
-def save_vault_settings(payload: dict) -> dict:
+def save_vault_settings(payload: dict, *, user_context: Any = None) -> dict:
from storage import vault_service
if not isinstance(payload, dict):
@@ -3317,7 +3317,9 @@ def save_vault_settings(payload: dict) -> dict:
engine = _vault_engine()
try:
with engine.begin() as conn:
- settings = vault_service.save_vault_settings(conn, payload)
+ settings = vault_service.save_vault_settings(conn, payload, user_context=user_context)
+ except vault_service.VaultSecretAccessError as exc:
+ raise _vault_secret_access_forbidden(exc) from exc
except vault_service.InvalidGrantError as exc:
raise VaultApiError(str(exc), code="invalid_grant") from exc
except vault_service.VaultServiceError as exc:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index cf5553412..f35bab263 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5836,7 +5836,10 @@ def vault_settings_patch():
from vibe import api
try:
- return jsonify(api.save_vault_settings(request.json or {}))
+ return jsonify(api.save_vault_settings(
+ request.json or {},
+ user_context=getattr(g, "authorization_context", None),
+ ))
except ValueError as exc:
return _vault_error_response(exc)