diff --git a/.test_durations_slm b/.test_durations_slm index 05ccf0ec21..8614f43739 100644 --- a/.test_durations_slm +++ b/.test_durations_slm @@ -4630,4 +4630,4 @@ "autobot-slm-backend/user_management/services/sso_secrets_test.py::TestSSOSecretsManagerIntegration::test_store_secrets_handles_empty_secret_values": 0.052052079000077356, "autobot-slm-backend/user_management/services/sso_secrets_test.py::TestSSOSecretsManagerIntegration::test_store_secrets_handles_multiple_sensitive_fields": 0.07525764299998627, "autobot-slm-backend/user_management/services/sso_secrets_test.py::TestSSOSecretsManagerIntegration::test_store_secrets_updates_existing_secret": 0.0896826289999808 -} \ No newline at end of file +} diff --git a/autobot-backend/security/session_ownership_org_review_audit_17832_test.py b/autobot-backend/security/session_ownership_org_review_audit_17832_test.py new file mode 100644 index 0000000000..92c35780cb --- /dev/null +++ b/autobot-backend/security/session_ownership_org_review_audit_17832_test.py @@ -0,0 +1,77 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Org conversation review audits every transcript open and stops at the org boundary (#17832). + +The org-review screen only calls ``GET /chat/sessions/{id}``; the gate and the audit trail +are ``SessionOwnershipValidator``'s. These pin the two claims the screen relies on instead of +assuming them: an org admin opening a session in their own org writes a +``conversation_accessed`` audit record naming them, and a session in another org is not +served and writes no success record. +""" + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from security.session_ownership import SessionOwnershipValidator + +SESSION_ID = "0123456789abcdef0123456789abcdef" + + +def _validator(session_org: str) -> SessionOwnershipValidator: + validator = SessionOwnershipValidator.__new__(SessionOwnershipValidator) + validator.get_session_context = AsyncMock(return_value={"org_id": session_org}) + validator.is_shared_with_user = AsyncMock(return_value=False) + validator._handle_unauthorized_access = AsyncMock(return_value={"authorized": False}) + return validator + + +async def _open(validator: SessionOwnershipValidator, role: str, org_id: str): + audit = MagicMock() + middleware = MagicMock() + middleware.security_layer.audit_log = audit + request = MagicMock() + request.client.host = "203.0.113.7" + enforcement = MagicMock(mode="enforced") + user = {"username": "reviewer", "user_id": "u-1", "role": role, "org_id": org_id} + with patch("security.session_ownership.get_auth_middleware", return_value=middleware): + result = await validator._check_ownership_mismatch( + "reviewer", SESSION_ID, "someone-else", user, request, enforcement + ) + return result, audit + + +@pytest.mark.asyncio +@pytest.mark.parametrize("role", ["admin", "org_admin"]) +async def test_org_admin_open_is_audit_logged_with_the_reviewer(role): + result, audit = await _open(_validator("org-1"), role, "org-1") + + assert result["authorized"] is True + assert result["reason"] == "org_admin" + audit.assert_called_once() + kwargs = audit.call_args.kwargs + assert kwargs["action"] == "conversation_accessed" + assert kwargs["user"] == "reviewer" + assert kwargs["outcome"] == "success" + assert kwargs["details"]["session_id"].startswith(SESSION_ID[:16]) + + +@pytest.mark.asyncio +async def test_a_session_in_another_org_is_not_served_and_not_logged_as_a_success(): + validator = _validator("org-2") + result, audit = await _open(validator, "admin", "org-1") + + assert result == {"authorized": False} + validator._handle_unauthorized_access.assert_awaited_once() + assert all(call.kwargs.get("action") != "conversation_accessed" for call in audit.call_args_list) + + +@pytest.mark.asyncio +async def test_a_non_admin_role_is_not_served_even_inside_its_own_org(): + validator = _validator("org-1") + result, audit = await _open(validator, "user", "org-1") + + assert result == {"authorized": False} + assert all(call.kwargs.get("action") != "conversation_accessed" for call in audit.call_args_list) diff --git a/autobot-frontend/src/composables/useOrgConversationReview.ts b/autobot-frontend/src/composables/useOrgConversationReview.ts new file mode 100644 index 0000000000..8603000251 --- /dev/null +++ b/autobot-frontend/src/composables/useOrgConversationReview.ts @@ -0,0 +1,58 @@ +// Copyright 2025-2026 mrveiss +// SPDX-License-Identifier: Apache-2.0 +// AutoBot - AI-Powered Automation Platform +// Author: mrveiss +/** + * Org-scoped conversation review (#17832). + * + * Two existing, server-gated reads, typed from the generated contract (`paths`): + * - `GET /api/chat/sessions?scope=org` the caller's own organization's sessions + * - `GET /api/chat/sessions/{session_id}` one transcript, page by page + * The server is the authority for both: the list refuses a caller without an + * administrative role, a transcript is served only when the session's org matches + * the caller's, and every transcript open is written to the audit trail by + * `SessionOwnershipValidator`. This module adds no access of its own. + */ +import type { paths } from '@/types/generated/api' +import { useApiClient } from '@/plugins/api' +import { getApiBase } from '@/config/ssot-config' + +type Body

= paths[P] extends { + get: { responses: { 200: { content: { 'application/json': infer J } } } } +} + ? J + : never + +const SESSIONS_PATH = '/api/chat/sessions' as const +const SESSION_PATH = '/api/chat/sessions/{session_id}' as const + +/** The contract path, rebased on the configured API base (the SSOT, never a literal). */ +const url = (contractPath: string): string => `${getApiBase()}${contractPath.slice('/api'.length)}` + +export type OrgSessionsResponse = Body +export type TranscriptResponse = Body +export type OrgSessionsData = NonNullable +export type OrgSession = OrgSessionsData['sessions'][number] +export type TranscriptData = NonNullable +export type TranscriptMessage = TranscriptData['messages'][number] + +/** Messages per transcript page; the backend accepts a caller-chosen size. */ +export const TRANSCRIPT_PAGE_SIZE = 50 + +export function useOrgConversationReview() { + const api = useApiClient() + + async function listOrgSessions(): Promise { + const body = (await api.get(`${url(SESSIONS_PATH)}?scope=org`)) as OrgSessionsResponse + return body?.data ?? null + } + + async function openTranscript(sessionId: string, page: number): Promise { + const path = SESSION_PATH.replace('{session_id}', encodeURIComponent(sessionId)) + const query = `page=${page}&per_page=${TRANSCRIPT_PAGE_SIZE}` + const body = (await api.get(`${url(path)}?${query}`)) as TranscriptResponse + return body?.data ?? null + } + + return { listOrgSessions, openTranscript } +} diff --git a/autobot-frontend/src/config/navItems.ts b/autobot-frontend/src/config/navItems.ts index 3b6aedc953..7c466cc1e4 100644 --- a/autobot-frontend/src/config/navItems.ts +++ b/autobot-frontend/src/config/navItems.ts @@ -183,6 +183,8 @@ export const adminMenuItems: NavItem[] = [ { to: '/admin/mcp-servers', labelKey: 'nav.adminMcpServers', icon: 'M21.75 17.25v-.228a4.5 4.5 0 00-.12-1.03l-2.268-9.64a3.375 3.375 0 00-3.285-2.602H7.923a3.375 3.375 0 00-3.285 2.602l-2.268 9.64a4.5 4.5 0 00-.12 1.03v.228m19.5 0a3 3 0 01-3 3H5.25a3 3 0 01-3-3m19.5 0a3 3 0 00-3-3H5.25a3 3 0 00-3 3', iconViewBox: '0 0 24 24', iconStroke: true }, // Issue #16825: permission scopes -- a "coming in a later release" panel, not a working // feature yet, unlike the two entries above. + // Issue #17832: org conversation review -- the server gates and audits; this entry is presentation only. + { to: '/admin/conversations', labelKey: 'nav.adminConversations', icon: 'M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z', iconViewBox: '0 0 24 24', iconStroke: true }, { to: '/admin/permission-scopes', labelKey: 'nav.adminPermissionScopes', icon: 'M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z', iconViewBox: '0 0 24 24', iconStroke: true }, ]; diff --git a/autobot-frontend/src/i18n/locales/en.json b/autobot-frontend/src/i18n/locales/en.json index eb466942e1..cf6ac1baf9 100644 --- a/autobot-frontend/src/i18n/locales/en.json +++ b/autobot-frontend/src/i18n/locales/en.json @@ -8321,7 +8321,8 @@ "degradedMessage": "Some backend services are slow or failing. Features may not work as expected.", "criticalTitle": "Backend unreachable", "criticalMessage": "AutoBot cannot reach its backend. Changes may not be saved until it is back." - } + }, + "adminConversations": "Conversation Review" }, "llcCompanyStatus": { "showArchived": "Show archived", @@ -9889,6 +9890,36 @@ "title": "Administration", "subtitle": "Back-office tools for administrators", "ariaLabel": "Administration section" + }, + "conversations": { + "title": "Conversation Review", + "subtitle": "Review conversations in your organization. Access is decided by the server.", + "auditNotice": "Every transcript you open is recorded in the audit trail. You see only sessions that belong to your own organization.", + "openAudited": "Opening this transcript has been recorded in the audit trail.", + "colTitle": "Conversation", + "colMessages": "Messages", + "colUpdated": "Last updated", + "colId": "Session ID", + "untitled": "Untitled conversation", + "openTranscript": "Open transcript", + "transcript": "Transcript", + "loading": "Loading organization conversations", + "emptyTitle": "No conversations in your organization", + "emptyBody": "Sessions that belong to your organization appear here once they exist.", + "noOrgTitle": "Your account is not part of an organization", + "noOrgBody": "Organization review is not available because the server found no organization for your account.", + "refusedTitle": "The server refused this request", + "refusedBody": "Listing organization conversations needs an administrative role. Your role does not allow it.", + "failedTitle": "Could not load", + "failedBody": "The conversation list could not be loaded. Try again.", + "transcriptRefusedTitle": "The server refused access to this conversation", + "transcriptRefusedBody": "A transcript opens only for an administrator of the organization that owns the session.", + "transcriptMissing": "This conversation no longer exists.", + "transcriptFailedBody": "The transcript could not be loaded. Try again.", + "noMessagesTitle": "No messages", + "noMessagesBody": "This conversation has no messages on this page.", + "unknownSender": "Unknown sender", + "transcriptPages": "Transcript pages" } }, "components": { diff --git a/autobot-frontend/src/router/__tests__/adminRoutes.test.ts b/autobot-frontend/src/router/__tests__/adminRoutes.test.ts index 95f07df935..daa2c552a8 100644 --- a/autobot-frontend/src/router/__tests__/adminRoutes.test.ts +++ b/autobot-frontend/src/router/__tests__/adminRoutes.test.ts @@ -39,6 +39,7 @@ const OLD_ADMIN_PATHS: Record = { '/admin/pricing': 'admin-pricing', '/admin/mcp-servers': 'admin-mcp-servers', '/admin/permission-scopes': 'admin-permission-scopes', + '/admin/conversations': 'admin-conversations', } const OLD_COMPONENT_FILES: Record = { @@ -51,6 +52,7 @@ const OLD_COMPONENT_FILES: Record = { 'admin-pricing': 'AdminPricingView.vue', 'admin-mcp-servers': 'AdminMcpServersView.vue', 'admin-permission-scopes': 'AdminPermissionScopesView.vue', + 'admin-conversations': 'AdminConversationsView.vue', } function adminTo(): RouteLocationNormalized { diff --git a/autobot-frontend/src/router/adminRoutes.ts b/autobot-frontend/src/router/adminRoutes.ts index ff8f2a3645..2787ff3dae 100644 --- a/autobot-frontend/src/router/adminRoutes.ts +++ b/autobot-frontend/src/router/adminRoutes.ts @@ -98,6 +98,14 @@ export const adminChildren: RouteRecordRaw[] = [ component: () => import('@/views/AdminMcpServersView.vue'), meta: adminMeta('MCP Servers'), }, + { + path: 'conversations', // Issue #17832: org-scoped conversation review (server-gated, audited) + name: 'admin-conversations', + component: () => import('@/views/AdminConversationsView.vue'), + meta: adminMeta('Conversation Review', { + description: 'Review conversations in your organization', + }), + }, { path: 'permission-scopes', // Issue #16825: "coming later" panel name: 'admin-permission-scopes', diff --git a/autobot-frontend/src/views/AdminConversationsView.vue b/autobot-frontend/src/views/AdminConversationsView.vue new file mode 100644 index 0000000000..253b18ec14 --- /dev/null +++ b/autobot-frontend/src/views/AdminConversationsView.vue @@ -0,0 +1,250 @@ + + + + + + diff --git a/autobot-frontend/src/views/__tests__/AdminConversationsView.spec.ts b/autobot-frontend/src/views/__tests__/AdminConversationsView.spec.ts new file mode 100644 index 0000000000..a57be7b21a --- /dev/null +++ b/autobot-frontend/src/views/__tests__/AdminConversationsView.spec.ts @@ -0,0 +1,139 @@ +// Copyright 2025-2026 mrveiss +// SPDX-License-Identifier: Apache-2.0 +// AutoBot - AI-Powered Automation Platform +// Author: mrveiss +// +// Tests for AdminConversationsView.vue (#17832): data, empty, failed, refused and +// not-available states for the org session list and the transcript drawer. The +// composable is mocked, so no HTTP is made; the server remains the authority. + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' +import { mount, flushPromises, type VueWrapper } from '@vue/test-utils' +import { createI18n } from 'vue-i18n' +import { HttpError } from '@autobot/ui' +import en from '@/i18n/locales/en.json' + +const mockList = vi.fn() +const mockOpen = vi.fn() + +vi.mock('@/composables/useOrgConversationReview', () => ({ + TRANSCRIPT_PAGE_SIZE: 50, + useOrgConversationReview: () => ({ listOrgSessions: mockList, openTranscript: mockOpen }), +})) + +import AdminConversationsView from '../AdminConversationsView.vue' + +const i18n = createI18n({ legacy: false, locale: 'en', fallbackLocale: 'en', messages: { en } }) +const copy = en.admin.conversations + +let wrapper: VueWrapper | null = null + +async function mountView(): Promise { + wrapper = mount(AdminConversationsView, { global: { plugins: [i18n] }, attachTo: document.body }) + await flushPromises() + return wrapper +} + +const orgList = (sessions: unknown[]) => ({ sessions, count: sessions.length, scope: 'org', org_id: 'org-1' }) + +describe('AdminConversationsView.vue', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + afterEach(() => { + wrapper?.unmount() + wrapper = null + }) + + it('asks the server for the org list once and lists the sessions it returns', async () => { + mockList.mockResolvedValue( + orgList([{ id: 's-1', title: 'Quarterly plan', messageCount: 7, lastModified: '2026-10-30T10:00:00Z' }]), + ) + const view = await mountView() + + expect(mockList).toHaveBeenCalledTimes(1) + expect(view.text()).toContain('Quarterly plan') + expect(view.text()).toContain('s-1') + expect(view.text()).toContain(copy.auditNotice) + }) + + it('opens one transcript through the server and shows its messages', async () => { + mockList.mockResolvedValue(orgList([{ id: 's-1', title: 'Quarterly plan' }])) + mockOpen.mockResolvedValue({ + messages: [{ id: 'm-1', sender: 'user', text: 'hello there', timestamp: '2026-10-30T10:00:00Z' }], + session_id: 's-1', + total_count: 1, + page: 1, + per_page: 50, + }) + const view = await mountView() + + await view.findAll('button').find((b) => b.text() === copy.openTranscript)!.trigger('click') + await flushPromises() + + expect(mockOpen).toHaveBeenCalledWith('s-1', 1) + expect(document.body.textContent).toContain(copy.openAudited) + // Message text is rendered as text, never as markup. + expect(document.body.textContent).toContain('hello there') + expect(document.body.querySelector('li b')).toBeNull() + }) + + it('shows the empty state when the org has no sessions', async () => { + mockList.mockResolvedValue(orgList([])) + const view = await mountView() + + expect(view.text()).toContain(copy.emptyTitle) + }) + + it('says organization review is not available when the account has no organization', async () => { + mockList.mockResolvedValue({ sessions: [], count: 0, scope: 'org' }) + const view = await mountView() + + expect(view.text()).toContain(copy.noOrgTitle) + expect(view.text()).not.toContain(copy.emptyTitle) + }) + + it('shows a failure with retry when the list cannot be loaded, and retries', async () => { + mockList.mockRejectedValueOnce(new HttpError(500)).mockResolvedValueOnce(orgList([{ id: 's-2', title: 'Recovered' }])) + const view = await mountView() + + expect(view.text()).toContain(copy.failedTitle) + await view.findAll('button').find((b) => b.text() === en.common.retry)!.trigger('click') + await flushPromises() + + expect(mockList).toHaveBeenCalledTimes(2) + expect(view.text()).toContain('Recovered') + expect(view.text()).not.toContain(copy.failedTitle) + }) + + it('reports the server refusing the list, not a generic failure', async () => { + mockList.mockRejectedValue(new HttpError(403)) + const view = await mountView() + + expect(view.text()).toContain(copy.refusedTitle) + expect(view.text()).not.toContain(copy.failedTitle) + }) + + it('reports the server refusing a transcript', async () => { + mockList.mockResolvedValue(orgList([{ id: 's-9', title: 'Other org' }])) + mockOpen.mockRejectedValue(new HttpError(403)) + const view = await mountView() + + await view.findAll('button').find((b) => b.text() === copy.openTranscript)!.trigger('click') + await flushPromises() + + expect(document.body.textContent).toContain(copy.transcriptRefusedTitle) + }) + + it('shows an empty transcript state when a session has no messages', async () => { + mockList.mockResolvedValue(orgList([{ id: 's-3', title: 'Empty one' }])) + mockOpen.mockResolvedValue({ messages: [], session_id: 's-3', total_count: 0, page: 1, per_page: 50 }) + const view = await mountView() + + await view.findAll('button').find((b) => b.text() === copy.openTranscript)!.trigger('click') + await flushPromises() + + expect(document.body.textContent).toContain(copy.noMessagesTitle) + }) +})