diff --git a/.changeset/36981-setup-doors-bearer.md b/.changeset/36981-setup-doors-bearer.md new file mode 100644 index 00000000000..edb47650f7c --- /dev/null +++ b/.changeset/36981-setup-doors-bearer.md @@ -0,0 +1,15 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +--- + +fix(console): Settings, Packages, Audit Log and the connector pages send the stored bearer token, so a session the rest of the console accepts works there too + +Clause-②: no +Metadata-protocol: none + +These Setup surfaces called their endpoints with the session cookie only (`credentials: 'include'`), while the rest of the console sends the stored bearer token through its authenticated fetch. A session held by its bearer token alone (a second local runtime on the same host replaced the cookie, the cookie was blocked as a third-party cookie, or the cookie jar was cleared) therefore worked everywhere except here, where each page printed the server's `401` instead: "Authentication is required to access this endpoint.", a bare `UNAUTHENTICATED`, or, on the Audit Log, the raw response body followed by "No audit entries". + +They now go through `createAuthenticatedFetch` from `@object-ui/auth`, the path every other console request takes: every `/api/settings` call and the judged client-address read of the Authentication and Access policy pages, the Audit Log read, the connector credential and connection doors, the Packages list (the Installed Apps address included), and this runtime's own install ledger (`/api/v1/marketplace/install-local*`) and cloud-connection reads (`installed`, `org-packages`). The session cookie still rides along (`credentials: 'include'` is unchanged), so a cookie session behaves exactly as before, and a `401` now reaches the console's session-ended check as it does on every other page. Nothing changes in what the server accepts. + +A failed Audit Log read no longer draws the "No audit entries" empty state, and its alert shows the refusal's own sentence when the response envelope carries one, or "Failed to load audit log" otherwise, never the raw response body. diff --git a/ui/apps/console/src/pages/consoleFaces.displayLocale-9909.test.tsx b/ui/apps/console/src/pages/consoleFaces.displayLocale-9909.test.tsx index e17d303b239..8849a855625 100644 --- a/ui/apps/console/src/pages/consoleFaces.displayLocale-9909.test.tsx +++ b/ui/apps/console/src/pages/consoleFaces.displayLocale-9909.test.tsx @@ -101,7 +101,10 @@ vi.mock('@object-ui/i18n', async (importOriginal) => ({ })); vi.mock('@object-ui/auth', async (importOriginal) => { - const authFetch = async () => new Response('{}', { status: 200 }); + // A case that stubs the wire (the audit log's ledger read, which goes through + // the authenticated fetch) is answered by its stub; every other read gets `{}`. + const authFetch = async (input: RequestInfo | URL, init?: RequestInit) => + vi.isMockFunction(globalThis.fetch) ? globalThis.fetch(input, init) : new Response('{}', { status: 200 }); return { ...(await importOriginal>()), useAuth: () => AUTH, diff --git a/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx b/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx index 89c8c16fbf0..fd9332c13b7 100644 --- a/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/FirstRunChecklist.test.tsx @@ -158,7 +158,7 @@ let extraManifests: unknown[] = []; let aiPayload: Record | null = null; function ok(data: unknown) { - return { ok: true, status: 200, statusText: 'OK', json: async () => ({ success: true, data }) } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => ({ success: true, data }) } as unknown as Response; } const fetchMock = vi.fn(); @@ -177,14 +177,14 @@ function routeFetch() { } if (url === '/api/settings/localization' && method === 'PUT') { if (putRefusal) { - return { ok: false, status: 400, statusText: 'Bad Request', json: async () => putRefusal } as unknown as Response; + return { ok: false, status: 400, statusText: 'Bad Request', headers: new Headers(), json: async () => putRefusal } as unknown as Response; } const body = JSON.parse(String(init?.body)) as Record; const written = Object.fromEntries(Object.entries(body).map(([k, v]) => [k, resolved(v, 'tenant')])); localizationValues = { ...localizationValues, ...written }; return ok({ values: written }); } - return { ok: false, status: 404, statusText: 'Not Found', json: async () => ({}) } as unknown as Response; + return { ok: false, status: 404, statusText: 'Not Found', headers: new Headers(), json: async () => ({}) } as unknown as Response; }); } diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsField.actionRowOneLabel-12610.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsField.actionRowOneLabel-12610.test.tsx index 51004f58e10..6e0096d45eb 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsField.actionRowOneLabel-12610.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsField.actionRowOneLabel-12610.test.tsx @@ -52,7 +52,7 @@ afterEach(() => { }); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } function withI18n(ui: ReactElement) { diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsHub.adminManaged-29085.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsHub.adminManaged-29085.test.tsx index 8764b41280b..2630ee71cc1 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsHub.adminManaged-29085.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsHub.adminManaged-29085.test.tsx @@ -48,6 +48,7 @@ function serveManifests(manifests: unknown[]) { ok: true, status: 200, statusText: 'OK', + headers: new Headers(), json: async () => ({ success: true, data: { manifests } }), })), ); diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsHub.pageHeader-12553.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsHub.pageHeader-12553.test.tsx index 9c92eff2725..a130417d7a0 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsHub.pageHeader-12553.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsHub.pageHeader-12553.test.tsx @@ -42,6 +42,7 @@ beforeEach(() => { ok: true, status: 200, statusText: 'OK', + headers: new Headers(), json: async () => ({ success: true, data: { manifests: MANIFESTS } }), })), ); diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsIcons.knownName-11679.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsIcons.knownName-11679.test.tsx index 37729e8dac1..6043d0110f5 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsIcons.knownName-11679.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsIcons.knownName-11679.test.tsx @@ -62,7 +62,7 @@ afterEach(() => { }); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.clearBeneathPin-30665.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.clearBeneathPin-30665.test.tsx index 87ae254d262..3ce6c42cea8 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.clearBeneathPin-30665.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.clearBeneathPin-30665.test.tsx @@ -105,7 +105,7 @@ const REREAD_IP_RANGES = pinned('', 'OS_AUTH_ALLOWED_IP_RANGES', [ const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** GET answers the page; a PUT answers `putValues` and the next GET reads `rereadValues`. */ @@ -256,6 +256,7 @@ describe('clear the value saved beneath an env pin (objectstack#30665)', () => { ok: false, status: 409, statusText: 'Conflict', + headers: new Headers(), json: async () => ({ success: false, error: { diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.clientAddress-30313.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.clientAddress-30313.test.tsx index 25ff77a2f80..c8c8a41b7fd 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.clientAddress-30313.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.clientAddress-30313.test.tsx @@ -69,13 +69,14 @@ const LOCALIZATION = { }; const ok = (data: unknown) => - ({ ok: true, status: 200, statusText: 'OK', json: async () => ({ success: true, data }) }) as unknown as Response; + ({ ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => ({ success: true, data }) }) as unknown as Response; const refused = (status: number, code: string) => ({ ok: false, status, statusText: status === 401 ? 'Unauthorized' : 'Forbidden', + headers: new Headers(), json: async () => ({ success: false, error: { code, message: 'Platform admin required.' } }), }) as unknown as Response; @@ -192,6 +193,7 @@ describe('SettingsView — Allowed IP ranges shows the address the server judges ok: false, status: 400, statusText: 'Bad Request', + headers: new Headers(), json: async () => ({ success: false, error: { @@ -319,6 +321,7 @@ describe('SettingsView — Access policy shows the address the server judges (ob ok: false, status: 404, statusText: 'Not Found', + headers: new Headers(), json: async () => ({ success: false, error: { code: 'NOT_FOUND', message: 'Not found.' } }), }) as unknown as Response, ], diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.confirmOff-30500.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.confirmOff-30500.test.tsx index 766fd60d069..1fe7ca872fb 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.confirmOff-30500.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.confirmOff-30500.test.tsx @@ -79,7 +79,7 @@ function payloadOf(passwordOn: boolean, extra: Partial = {}) { const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** GET answers the page; PUT answers the values it was sent. */ diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.envelope.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.envelope.test.tsx index 44e3287cbda..44b7e2dfd17 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.envelope.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.envelope.test.tsx @@ -78,7 +78,7 @@ afterEach(() => { }); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } function renderView() { diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.i18n-4024.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.i18n-4024.test.tsx index 039eb8b30b9..3e1c4c3af6b 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.i18n-4024.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.i18n-4024.test.tsx @@ -124,6 +124,7 @@ beforeEach(() => { ok: true, status: 200, statusText: 'OK', + headers: new Headers(), json: async () => ({ success: true, data: PAYLOAD }), } as unknown as Response); }); @@ -241,6 +242,7 @@ describe('SettingsView refusal toasts interpolate through the bundle (objectui#4 ok: false, status: 409, statusText: 'Conflict', + headers: new Headers(), json: async () => ({ success: false, error: { code: 'SETTINGS_LOCKED', message: 'locked', details: { key: 'timezone' } }, @@ -267,6 +269,7 @@ describe('SettingsView refusal toasts interpolate through the bundle (objectui#4 ok: false, status: 503, statusText: 'Service Unavailable', + headers: new Headers(), json: async () => ({ success: false, error: { @@ -302,6 +305,7 @@ async function saveRefusedWith(status: number, error: Record, s ok: false, status, statusText: 'Refused', + headers: new Headers(), json: async () => ({ success: false, error }), } as unknown as Response); fireEvent.click(await screen.findByText(saveLabel)); @@ -316,6 +320,7 @@ function serveNamespace(payload: unknown) { ok: true, status: 200, statusText: 'OK', + headers: new Headers(), json: async () => ({ success: true, data: payload }), } as unknown as Response); } diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.languageKeepsDraft-13254.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.languageKeepsDraft-13254.test.tsx index 7d3d08d023c..f1773f00244 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.languageKeepsDraft-13254.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.languageKeepsDraft-13254.test.tsx @@ -62,7 +62,7 @@ const PAYLOADS: Record = { const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** @@ -254,6 +254,7 @@ describe('the load-failure card (objectui#13254: translated at render, not in th ok: false, status: 403, statusText: 'Forbidden', + headers: new Headers(), json: async () => ({ success: false, error: { code: 'FORBIDDEN', message: 'Not allowed to read localization' } }), })); renderPage(); diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.leaveGuard-13163.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.leaveGuard-13163.test.tsx index 9cadaeb76ba..bc04e660168 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.leaveGuard-13163.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.leaveGuard-13163.test.tsx @@ -62,7 +62,7 @@ const PAYLOADS: Record = { const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** GET answers the namespace named in the URL; PUT answers the values it was sent. */ diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.pageHeader-12553.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.pageHeader-12553.test.tsx index a5fdce746cf..3c071c1e8c0 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.pageHeader-12553.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.pageHeader-12553.test.tsx @@ -73,6 +73,7 @@ beforeEach(() => { ok: true, status: 200, statusText: 'OK', + headers: new Headers(), json: async () => ({ success: true, data: payload }), })), ); diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.refusalToast-13146.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.refusalToast-13146.test.tsx index 3ac13c4e5ce..7b17b8d82d6 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.refusalToast-13146.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.refusalToast-13146.test.tsx @@ -92,6 +92,7 @@ function refusal(namespace: string, fields: Refused[]) { ok: false, status: 400, statusText: 'Bad Request', + headers: new Headers(), json: async () => ({ success: false, error: { @@ -112,6 +113,7 @@ function serve(payload: unknown) { ok: true, status: 200, statusText: 'OK', + headers: new Headers(), json: async () => ({ success: true, data: payload }), } as unknown as Response); } @@ -292,6 +294,7 @@ describe('a refusal with no field errors keeps its message (objectui#13146)', () ok: false, status: 500, statusText: 'Internal Server Error', + headers: new Headers(), json: async () => ({ success: false, error: { code: 'INTERNAL_ERROR', message: 'Failed to write namespace' }, diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.rereadAfterSave-13382.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.rereadAfterSave-13382.test.tsx index f8c5dce2e23..7219f6df47d 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.rereadAfterSave-13382.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.rereadAfterSave-13382.test.tsx @@ -68,7 +68,7 @@ function mailPayload(bannerText: string, host: string) { const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** The `sms` GET payload: a second namespace to move to. */ @@ -120,6 +120,7 @@ function serve() { ok: false, status: 503, statusText: 'Service Unavailable', + headers: new Headers(), json: async () => ({ success: false, error: { code: 'UNAVAILABLE', message: 'Settings unavailable' } }), } as unknown as Response; } diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.shellLeave-13231.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.shellLeave-13231.test.tsx index 9e8dda41732..7e6e3d8ef27 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.shellLeave-13231.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.shellLeave-13231.test.tsx @@ -54,7 +54,7 @@ const LOCALIZATION = { const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** GET answers the namespace; PUT answers the values it was sent. */ diff --git a/ui/apps/console/src/pages/settings/__tests__/SettingsView.unsetAndReset-13145.test.tsx b/ui/apps/console/src/pages/settings/__tests__/SettingsView.unsetAndReset-13145.test.tsx index 58ef54383e8..7dc96407f93 100644 --- a/ui/apps/console/src/pages/settings/__tests__/SettingsView.unsetAndReset-13145.test.tsx +++ b/ui/apps/console/src/pages/settings/__tests__/SettingsView.unsetAndReset-13145.test.tsx @@ -85,7 +85,7 @@ const PAYLOAD = { const fetchMock = vi.fn(); function ok(body: unknown): Response { - return { ok: true, status: 200, statusText: 'OK', json: async () => body } as unknown as Response; + return { ok: true, status: 200, statusText: 'OK', headers: new Headers(), json: async () => body } as unknown as Response; } /** diff --git a/ui/apps/console/src/pages/settings/api.bearer.test.ts b/ui/apps/console/src/pages/settings/api.bearer.test.ts new file mode 100644 index 00000000000..abdb0662a0d --- /dev/null +++ b/ui/apps/console/src/pages/settings/api.bearer.test.ts @@ -0,0 +1,96 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Every `/api/settings` call — and the judged-address read the auth and + * access-policy namespaces make — goes out through the console's authenticated + * fetch (`createAuthenticatedFetch` in `@object-ui/auth`), so it carries the + * session's bearer token as every other console request does, beside the + * session cookie. + * + * The state this protects: a session held by its bearer token alone (the + * cookie was replaced by a second runtime on the same host, blocked as a + * third-party cookie, or cleared). The rest of the console works there; a + * cookie-only call answers `401`. + * + * The control: with no token stored, the same calls go out exactly as a + * cookie session needs them — `credentials: 'include'`, no `Authorization`. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { TokenStorage } from '@object-ui/auth'; +import { + getJudgedClientAddress, + getSettingsNamespace, + listSettingsManifests, + runSettingsAction, + saveSettingsNamespace, +} from './api'; + +const TOKEN = 'stored-session-token'; + +const reply = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +/** One fake per route: the body each call reads as success. */ +function answer(url: string, method: string): Response { + const path = new URL(url, 'http://console.test').pathname; + if (path.startsWith('/api/v1/auth/')) return reply({ clientAddress: '203.0.113.7', trustProxy: false }); + if (path === '/api/settings') return reply({ success: true, data: { manifests: [] } }); + if (method === 'PUT') return reply({ success: true, data: { values: {} } }); + if (method === 'POST') return reply({ success: true, data: { ok: true } }); + return reply({ success: true, data: { manifest: { namespace: 'company' }, values: {} } }); +} + +type Sent = { url: string; method: string; credentials: RequestCredentials | undefined; authorization: string | null }; +let sent: Sent[] = []; + +beforeEach(() => { + sent = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const method = (init?.method ?? 'GET').toUpperCase(); + sent.push({ + url, + method, + credentials: init?.credentials, + authorization: new Headers(init?.headers).get('Authorization'), + }); + return answer(url, method); + }), + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + TokenStorage.clear(); +}); + +/** Every call this module makes, each driven once. */ +const CALLS: Array<[string, () => Promise]> = [ + ['GET /api/settings', () => listSettingsManifests()], + ['GET /api/settings/:namespace', () => getSettingsNamespace('company')], + ['PUT /api/settings/:namespace', () => saveSettingsNamespace('company', { name: 'Acme' })], + ['POST /api/settings/:namespace/:action', () => runSettingsAction('mail', 'send_test')], + ['GET /api/v1/auth/admin/client-address', () => getJudgedClientAddress('/admin/client-address')], + ['GET /api/v1/auth/client-address', () => getJudgedClientAddress('/client-address')], +]; + +describe('the settings client sends the stored bearer token', () => { + it.each(CALLS)('%s carries `Authorization: Bearer ` and the cookie', async (_name, call) => { + TokenStorage.set(TOKEN); + await call(); + expect(sent).toHaveLength(1); + expect(sent[0].authorization).toBe(`Bearer ${TOKEN}`); + expect(sent[0].credentials).toBe('include'); + }); + + it.each(CALLS)('%s with no token stored goes out cookie-only, as before', async (_name, call) => { + TokenStorage.clear(); + await call(); + expect(sent).toHaveLength(1); + expect(sent[0].authorization).toBeNull(); + expect(sent[0].credentials).toBe('include'); + }); +}); diff --git a/ui/apps/console/src/pages/settings/api.envelope.test.ts b/ui/apps/console/src/pages/settings/api.envelope.test.ts index 827c5cec920..162835f9cd1 100644 --- a/ui/apps/console/src/pages/settings/api.envelope.test.ts +++ b/ui/apps/console/src/pages/settings/api.envelope.test.ts @@ -35,11 +35,12 @@ import { saveSettingsNamespace, } from './api'; -/** A `Response` double — only the three members this client touches. */ +/** A `Response` double — only the members this client and the authenticated fetch touch. */ function jsonResponse(body: unknown, status = 200, statusText?: string): Response { return { ok: status >= 200 && status < 300, status, + headers: new Headers(), statusText: statusText ?? (status === 200 ? 'OK' : 'Bad Request'), json: async () => body, } as unknown as Response; @@ -51,6 +52,7 @@ function brokenResponse(status = 502, statusText = 'Bad Gateway'): Response { ok: false, status, statusText, + headers: new Headers(), json: async () => { throw new SyntaxError('Unexpected token < in JSON at position 0'); }, diff --git a/ui/apps/console/src/pages/settings/api.ts b/ui/apps/console/src/pages/settings/api.ts index d12bee2a3bf..dac332ffd11 100644 --- a/ui/apps/console/src/pages/settings/api.ts +++ b/ui/apps/console/src/pages/settings/api.ts @@ -8,11 +8,23 @@ import type { SettingsListResponse, SettingsNamespacePayload, } from './types'; +import { createAuthenticatedFetch } from '@object-ui/auth'; import { isPlatformManagedRefusal } from './platformManaged'; const SERVER_URL = (import.meta.env.VITE_SERVER_URL || '').replace(/\/$/, ''); const BASE = `${SERVER_URL}/api/settings`; +/** + * The console's authenticated fetch: the stored bearer token beside the session + * cookie (`credentials: 'include'` is still passed on every call), the one every + * other console request goes through. A session held by its bearer token alone + * reads and writes settings like the rest of the console, and a `401` reaches + * the console's session-ended check. + */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + /** * Unwrap the platform's declared success envelope, `{ success, data }` * (framework#3843). @@ -42,8 +54,8 @@ const BASE = `${SERVER_URL}/api/settings`; * server generation it was carrying, not a silent regression. * * This is deliberately a local copy rather than an import: the console talks to - * `/api/settings` with raw `fetch` and does not construct an `ObjectStackClient`, - * and `unwrapResponse` is private to it. + * `/api/settings` through its authenticated fetch and does not construct an + * `ObjectStackClient`, and `unwrapResponse` is private to it. */ function unwrapEnvelope(body: unknown): unknown { if ( @@ -162,13 +174,13 @@ export function lockedKeyOf(apiError: unknown): string | undefined { } export async function listSettingsManifests(): Promise { - const res = await fetch(BASE, { credentials: 'include', headers: jsonHeaders() }); + const res = await authFetch(BASE, { credentials: 'include', headers: jsonHeaders() }); const body = await jsonOrThrow(res); return assertShape(body, ['manifests'], 'GET /api/settings'); } export async function getSettingsNamespace(namespace: string): Promise { - const res = await fetch(`${BASE}/${encodeURIComponent(namespace)}`, { + const res = await authFetch(`${BASE}/${encodeURIComponent(namespace)}`, { credentials: 'include', headers: jsonHeaders(), }); @@ -184,7 +196,7 @@ export async function saveSettingsNamespace( namespace: string, patch: Record, ): Promise<{ values: SettingsNamespacePayload['values'] }> { - const res = await fetch(`${BASE}/${encodeURIComponent(namespace)}`, { + const res = await authFetch(`${BASE}/${encodeURIComponent(namespace)}`, { method: 'PUT', credentials: 'include', headers: jsonHeaders(), @@ -206,7 +218,7 @@ export async function runSettingsAction( actionId: string, payload?: unknown, ): Promise { - const res = await fetch(`${BASE}/${encodeURIComponent(namespace)}/${encodeURIComponent(actionId)}`, { + const res = await authFetch(`${BASE}/${encodeURIComponent(namespace)}/${encodeURIComponent(actionId)}`, { method: 'POST', credentials: 'include', headers: jsonHeaders(), @@ -280,7 +292,7 @@ export type JudgedClientAddressRoute = '/admin/client-address' | '/client-addres * decides what a failure shows. */ export async function getJudgedClientAddress(route: JudgedClientAddressRoute): Promise { - const res = await fetch(`${AUTH_BASE}${route}`, { + const res = await authFetch(`${AUTH_BASE}${route}`, { credentials: 'include', headers: { Accept: 'application/json' }, }); diff --git a/ui/apps/console/src/pages/settings/platformManaged.test.ts b/ui/apps/console/src/pages/settings/platformManaged.test.ts index 7665da61889..51ab645a49d 100644 --- a/ui/apps/console/src/pages/settings/platformManaged.test.ts +++ b/ui/apps/console/src/pages/settings/platformManaged.test.ts @@ -50,7 +50,7 @@ describe('aiProviderManagedByPlatform', () => { describe('runSettingsAction and the hosted refusal', () => { const fetchMock = vi.fn(); const answer = (body: unknown, status: number): Response => - ({ ok: status < 300, status, statusText: 'Conflict', json: async () => body }) as unknown as Response; + ({ ok: status < 300, status, statusText: 'Conflict', headers: new Headers(), json: async () => body }) as unknown as Response; beforeEach(() => { fetchMock.mockReset(); diff --git a/ui/apps/console/src/pages/system/AuditLogPage.bearerAndFailure.test.tsx b/ui/apps/console/src/pages/system/AuditLogPage.bearerAndFailure.test.tsx new file mode 100644 index 00000000000..27fe39b9667 --- /dev/null +++ b/ui/apps/console/src/pages/system/AuditLogPage.bearerAndFailure.test.tsx @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Audit Log — the ledger read and its failure state. + * + * - The `/data/sys_audit_log` read goes through the console's authenticated + * fetch, so a session held by its bearer token alone reads the ledger like + * every other console page; with no token stored it goes out cookie-only, + * as before. + * - A read that failed is not "no audit records": the empty state is drawn + * only for a read that answered with no rows. + * - The failure text is the refusal's own sentence when the envelope carries + * one, and the page's own "Failed to load audit log" otherwise — never the + * raw response body or a bare machine code. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { TokenStorage } from '@object-ui/auth'; + +const { ADAPTER } = vi.hoisted(() => ({ + ADAPTER: { + find: async () => ({ data: [], total: 0 }), + findOne: async () => null, + getObjectSchema: async () => undefined, + }, +})); + +vi.mock('@object-ui/app-shell', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => ADAPTER, +})); + +import { AuditLogPage } from './AuditLogPage'; + +const TOKEN = 'stored-session-token'; +/** The REST seam's anonymous-deny body, verbatim. */ +const ANONYMOUS_DENY = { + error: 'UNAUTHENTICATED', + code: 'UNAUTHENTICATED', + message: 'Authentication is required to access this endpoint.', +}; +const ROW = { id: 'a1', created_at: '2026-11-24T10:00:00.000Z', action: 'create', object_name: 'account', record_id: 'r1' }; + +const reply = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +type Sent = { credentials: RequestCredentials | undefined; authorization: string | null }; +let sent: Sent[] = []; + +/** A ledger that answers only a request carrying the bearer, as a server with no session cookie does. */ +function serveBearerOnly() { + sent = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + const authorization = new Headers(init?.headers).get('Authorization'); + sent.push({ credentials: init?.credentials, authorization }); + return authorization === `Bearer ${TOKEN}` + ? reply({ object: 'sys_audit_log', records: [ROW], total: 1 }) + : reply(ANONYMOUS_DENY, 401); + }), + ); +} + +function serve(response: () => Response) { + sent = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => { + sent.push({ credentials: init?.credentials, authorization: new Headers(init?.headers).get('Authorization') }); + return response(); + }), + ); +} + +const renderPage = () => render(); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + TokenStorage.clear(); +}); + +describe('Audit Log — the ledger read carries the stored bearer token', () => { + it('with a token stored, the read sends `Authorization: Bearer ` and lists the ledger', async () => { + TokenStorage.set(TOKEN); + serveBearerOnly(); + renderPage(); + expect(await screen.findByText('account')).toBeInTheDocument(); + expect(sent[0].authorization).toBe(`Bearer ${TOKEN}`); + expect(sent[0].credentials).toBe('include'); + expect(screen.queryByRole('alert')).toBeNull(); + }); + + it('with no token stored, the read goes out cookie-only, as before', async () => { + serve(() => reply({ object: 'sys_audit_log', records: [ROW], total: 1 })); + renderPage(); + expect(await screen.findByText('account')).toBeInTheDocument(); + expect(sent[0].authorization).toBeNull(); + expect(sent[0].credentials).toBe('include'); + }); +}); + +describe('Audit Log — a failed read is not the empty state', () => { + it('a 401 shows the page\'s own failure sentence, not the raw body, and no "No audit entries"', async () => { + serve(() => reply(ANONYMOUS_DENY, 401)); + renderPage(); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('Failed to load audit log'); + expect(alert.textContent).not.toMatch(/HTTP 401/); + expect(alert.textContent).not.toMatch(/\{/); + expect(alert.textContent).not.toMatch(/UNAUTHENTICATED/); + expect(screen.queryByText('No audit entries')).toBeNull(); + }); + + it('a refusal in the declared envelope shows its own sentence', async () => { + serve(() => reply({ success: false, error: { code: 'PERMISSION_DENIED', message: 'You cannot read the audit log.' } }, 403)); + renderPage(); + const alert = await screen.findByRole('alert'); + expect(alert).toHaveTextContent('You cannot read the audit log.'); + expect(screen.queryByText('No audit entries')).toBeNull(); + }); + + it('a read that answered with no rows still draws the empty state', async () => { + serve(() => reply({ object: 'sys_audit_log', records: [], total: 0 })); + renderPage(); + expect(await screen.findByText('No audit entries')).toBeInTheDocument(); + expect(screen.queryByRole('alert')).toBeNull(); + }); +}); diff --git a/ui/apps/console/src/pages/system/AuditLogPage.tsx b/ui/apps/console/src/pages/system/AuditLogPage.tsx index 0a1ca1381eb..152b32fcec0 100644 --- a/ui/apps/console/src/pages/system/AuditLogPage.tsx +++ b/ui/apps/console/src/pages/system/AuditLogPage.tsx @@ -76,13 +76,23 @@ import { } from '@object-ui/components'; import { LookupField, getLazyFieldWidget, objectRefOptionLabel } from '@object-ui/fields'; import { RecordPointerCell } from '@object-ui/plugin-grid'; -import { ConsolePageHeader, useAdapter, useMetadata } from '@object-ui/app-shell'; +import { ConsolePageHeader, readEnvelopeFailureText, useAdapter, useMetadata } from '@object-ui/app-shell'; +import { createAuthenticatedFetch } from '@object-ui/auth'; import { Search, X, AlertCircle, ScrollText, ExternalLink } from 'lucide-react'; import { actionBadgeVariant, actionFilterOptionsOf, actionLabelOf } from './auditLogActions'; const SERVER_URL = (import.meta.env.VITE_SERVER_URL || '').replace(/\/$/, ''); const API_BASE = `${SERVER_URL}/api/v1`; +/** + * The console's authenticated fetch: the stored bearer token beside the session + * cookie, as every other console data read sends it; a `401` reaches the + * console's session-ended check. + */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + interface AuditRow { id: string; created_at?: string; @@ -440,12 +450,15 @@ export function AuditLogPage() { params.set('$top', String(PAGE_SIZE + 1)); // +1 to detect hasMore params.set('$skip', String(page * PAGE_SIZE)); - const res = await fetch(`${API_BASE}/data/sys_audit_log?${params.toString()}`, { + const res = await authFetch(`${API_BASE}/data/sys_audit_log?${params.toString()}`, { credentials: 'include', }); if (!res.ok) { - const body = await res.text().catch(() => ''); - throw new Error(`HTTP ${res.status}: ${body.slice(0, 200) || res.statusText}`); + // The refusal's own sentence when the envelope carries one; otherwise + // an empty message, which the alert draws as the page's own failure + // text. Never the raw body or a bare machine code. + const body = await res.json().catch(() => null); + throw new Error(readEnvelopeFailureText(body) ?? ''); } const json = await res.json(); // REST envelope: { object, records, total, hasMore } @@ -460,7 +473,7 @@ export function AuditLogPage() { setRows(items.slice(0, PAGE_SIZE)); } catch (err: any) { console.warn('[AuditLogPage] load failed:', err); - setError(err?.message || ''); + setError(typeof err?.message === 'string' ? err.message : ''); setRows([]); setHasMore(false); } finally { @@ -673,7 +686,9 @@ export function AuditLogPage() { )} - {/* Table */} + {/* Table — a read that failed is not "no audit entries": the alert above + says why, and the empty state is drawn only for a read that answered. */} + {(error === null || loading || rows.length > 0) && ( {loading && rows.length === 0 ? ( @@ -744,6 +759,7 @@ export function AuditLogPage() { )} + )} {/* Pagination */} {(rows.length > 0 || page > 0) && ( diff --git a/ui/packages/app-shell/src/console/marketplace/__tests__/ConnectorCredentialsStep-27238.test.tsx b/ui/packages/app-shell/src/console/marketplace/__tests__/ConnectorCredentialsStep-27238.test.tsx index e0b07727e7d..8fe779d6877 100644 --- a/ui/packages/app-shell/src/console/marketplace/__tests__/ConnectorCredentialsStep-27238.test.tsx +++ b/ui/packages/app-shell/src/console/marketplace/__tests__/ConnectorCredentialsStep-27238.test.tsx @@ -64,7 +64,7 @@ beforeEach(() => { const method = (init?.method ?? 'GET').toUpperCase(); calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); const answer = url === DOOR && method === 'GET' ? listing : writes.shift() ?? { status: 500, body: {} }; - return { ok: answer.status >= 200 && answer.status < 300, status: answer.status, json: async () => answer.body } as unknown as Response; + return { ok: answer.status >= 200 && answer.status < 300, status: answer.status, headers: new Headers(), json: async () => answer.body } as unknown as Response; }), ); }); diff --git a/ui/packages/app-shell/src/console/marketplace/__tests__/MarketplacePackagePage.offlineLocalMenu-11627.test.tsx b/ui/packages/app-shell/src/console/marketplace/__tests__/MarketplacePackagePage.offlineLocalMenu-11627.test.tsx index 77b06f86eea..fd43a5c4d9e 100644 --- a/ui/packages/app-shell/src/console/marketplace/__tests__/MarketplacePackagePage.offlineLocalMenu-11627.test.tsx +++ b/ui/packages/app-shell/src/console/marketplace/__tests__/MarketplacePackagePage.offlineLocalMenu-11627.test.tsx @@ -98,6 +98,7 @@ const answer = (status: number, body: unknown) => ({ ok: status >= 200 && status < 300, status, statusText: '', + headers: new Headers(), json: async () => body, }); diff --git a/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts b/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts index be39f9884f2..265444006aa 100644 --- a/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts +++ b/ui/packages/app-shell/src/console/marketplace/marketplaceApi.ts @@ -15,11 +15,23 @@ import { getCloudBase } from '../../runtime-config.js'; import { forgetPackageListReads } from '../../views/studio-design/packages-io.js'; -import { TokenStorage } from '@object-ui/auth'; +import { TokenStorage, createAuthenticatedFetch } from '@object-ui/auth'; const SERVER_URL = (import.meta.env.VITE_SERVER_URL || '').replace(/\/$/, ''); const API_BASE = `${SERVER_URL}/api/v1/marketplace`; +/** + * The console's authenticated fetch — the stored bearer token beside the + * session cookie — for the calls to THIS runtime's own server: the local + * install ledger (`/marketplace/install-local*`) and the cloud-connection + * reads the Packages page makes. ⛔ Never for a request to the cloud control + * plane's own origin (`getCloudBase()`), which must not see this runtime's + * bearer; the browse calls keep `credentials: 'omit'` in {@link call}. + */ +function serverFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + /** * Attach the Bearer token to same-origin `/api/v1/cloud-connection/*` calls. * @@ -1087,7 +1099,7 @@ export interface OrgPackagesResult { } export async function listOrgPackages(): Promise { try { - const res = await fetch(`${SERVER_URL}/api/v1/cloud-connection/org-packages`, { + const res = await serverFetch(`${SERVER_URL}/api/v1/cloud-connection/org-packages`, { credentials: 'include', headers: { Accept: 'application/json' }, }); @@ -1129,7 +1141,7 @@ export async function installLocal(input: { installMode?: LocalInstallMode; }): Promise { // objectstack#29119 — an install changes this environment's package list. - const res = await fetch(`${API_BASE}/install-local`, { + const res = await serverFetch(`${API_BASE}/install-local`, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, @@ -1164,7 +1176,7 @@ export async function installLocal(input: { * each row's served `source`. */ export async function fetchLocalInstalls(): Promise { - const res = await fetch(`${API_BASE}/install-local`, { + const res = await serverFetch(`${API_BASE}/install-local`, { credentials: 'include', headers: { 'Accept': 'application/json' }, }); @@ -1210,7 +1222,7 @@ export interface InstalledPackagesResult { export async function listInstalledPackages(): Promise { try { - const res = await fetch(`${SERVER_URL}/api/v1/cloud-connection/installed`, { + const res = await serverFetch(`${SERVER_URL}/api/v1/cloud-connection/installed`, { credentials: 'include', headers: { Accept: 'application/json' }, }); @@ -1259,7 +1271,7 @@ export async function readMarketplaceInstalls(): Promise<{ source: 'cloud' | 'lo export async function uninstallLocal(manifestId: string): Promise { // objectstack#29119 — an uninstall changes this environment's package list. - const res = await fetch(`${API_BASE}/install-local/${encodeURIComponent(manifestId)}`, { + const res = await serverFetch(`${API_BASE}/install-local/${encodeURIComponent(manifestId)}`, { method: 'DELETE', credentials: 'include', headers: { 'Accept': 'application/json' }, @@ -1282,7 +1294,7 @@ export interface LocalSampleDataResult { async function postLocalSampleAction(manifestId: string, action: 'reseed' | 'purge'): Promise { const path = action === 'reseed' ? 'reseed-sample-data' : 'purge-sample-data'; - const res = await fetch(`${API_BASE}/install-local/${encodeURIComponent(manifestId)}/${path}`, { + const res = await serverFetch(`${API_BASE}/install-local/${encodeURIComponent(manifestId)}/${path}`, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json' }, @@ -1321,7 +1333,7 @@ export interface LocalSampleDataCount { /** {@link LocalSampleDataCount}, or `null` when the count could not be read (refused, failed, or no count in the answer). */ export async function countLocalSampleData(manifestId: string): Promise { try { - const res = await fetch(`${API_BASE}/install-local/${encodeURIComponent(manifestId)}/sample-data`, { + const res = await serverFetch(`${API_BASE}/install-local/${encodeURIComponent(manifestId)}/sample-data`, { credentials: 'include', headers: { 'Accept': 'application/json' }, }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx index c3283216199..8f273cd1c69 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.adoptLooseItems-13339.test.tsx @@ -29,6 +29,9 @@ import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testi import { MemoryRouter } from 'react-router-dom'; import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; +// Loaded at import so their first load is not paid inside a test's clocked window. +import '@objectstack/formula'; +import '@objectstack/lint'; const PKG_ID = 'com.acme.crm'; const PKG_NAME = 'Acme CRM'; @@ -60,6 +63,7 @@ function respond(body: unknown, status = 200) { return { ok: status >= 200 && status < 300, status, + headers: new Headers(), text: async () => text, json: async () => JSON.parse(text), } as unknown as Response; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.bearerSession.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.bearerSession.test.tsx new file mode 100644 index 00000000000..e356f8f21ba --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.bearerSession.test.tsx @@ -0,0 +1,131 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Setup → Packages (the Installed Apps address included) reads its list and + * the marketplace install ledger through the console's authenticated fetch, so + * a session held by its bearer token alone lists the installed packages as + * every other console page reads its data. With no token stored the reads go + * out cookie-only, as before. + * + * The wire is stubbed as a server with no session cookie: a request that does + * not carry the stored bearer is refused with the REST seam's `401`. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import { I18nProvider } from '@object-ui/i18n'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +import { TokenStorage } from '@object-ui/auth'; +import { PackagesPage, type InstalledPackageRow } from './PackagesPage'; +// Loaded at import so their first load is not paid inside a test's clocked window. +import '@objectstack/formula'; +import '@objectstack/lint'; +import { initRuntimeConfig, resetRuntimeConfigForTesting } from '../../runtime-config'; + +const TOKEN = 'stored-session-token'; +const MARKET: InstalledPackageRow = { + manifest: { id: 'com.example.todo', name: 'Todo', version: '1.0.0' }, + enabled: true, + source: 'marketplace', + writable: false, +}; +const LEDGER_TODO = { + packageId: 'com.example.todo', + versionId: 'ver_todo_1', + manifestId: 'com.example.todo', + version: '1.0.0', + installedAt: '2026-10-05T09:00:00.000Z', + withSampleData: false, +}; +const ANONYMOUS_DENY = { + error: 'UNAUTHENTICATED', + code: 'UNAUTHENTICATED', + message: 'Authentication is required to access this endpoint.', +}; + +const reply = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +type Sent = { path: string; credentials: RequestCredentials | undefined; authorization: string | null }; +let sent: Sent[] = []; + +/** Boot the runtime config with the marketplace capability, then serve the package doors. */ +async function serve({ requireBearer }: { requireBearer: boolean }) { + resetRuntimeConfigForTesting(); + vi.stubGlobal('fetch', vi.fn(async () => reply(200, { features: { installLocal: true } }))); + await initRuntimeConfig(); + sent = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: unknown, init?: RequestInit) => { + const path = new URL(String(input), 'http://console.test').pathname; + const authorization = new Headers(init?.headers).get('Authorization'); + sent.push({ path, credentials: init?.credentials, authorization }); + if (requireBearer && authorization !== `Bearer ${TOKEN}`) return reply(401, ANONYMOUS_DENY); + if (path === '/api/v1/packages') return reply(200, { success: true, data: { packages: [MARKET] } }); + if (path === '/api/v1/cloud-connection/installed') return reply(200, { success: true, data: { connected: false } }); + if (path === '/api/v1/marketplace/install-local') return reply(200, { success: true, data: { items: [LEDGER_TODO] } }); + return reply(404, { success: false, error: { code: 'NOT_FOUND', message: `no route ${path}` } }); + }), + ); +} + +function renderInstalledApps() { + return render( + + + + + , + ); +} + +/** The package doors this page reads on load. */ +const DOORS = ['/api/v1/packages', '/api/v1/cloud-connection/installed', '/api/v1/marketplace/install-local']; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + resetRuntimeConfigForTesting(); + TokenStorage.clear(); +}); + +describe('Packages — the list reads carry the stored bearer token', () => { + it('with a token stored and no session cookie, the installed package is listed', async () => { + TokenStorage.set(TOKEN); + await serve({ requireBearer: true }); + renderInstalledApps(); + + expect(await screen.findByTestId('pkg-row-com.example.todo')).toBeInTheDocument(); + for (const door of DOORS) { + const reads = sent.filter((r) => r.path === door); + expect(reads.length, door).toBeGreaterThan(0); + for (const read of reads) { + expect(read.authorization, door).toBe(`Bearer ${TOKEN}`); + expect(read.credentials, door).toBe('include'); + } + } + }); + + it('with no token stored, the reads go out cookie-only, as before', async () => { + await serve({ requireBearer: false }); + renderInstalledApps(); + + expect(await screen.findByTestId('pkg-row-com.example.todo')).toBeInTheDocument(); + for (const door of DOORS) { + const reads = sent.filter((r) => r.path === door); + expect(reads.length, door).toBeGreaterThan(0); + for (const read of reads) { + expect(read.authorization, door).toBeNull(); + expect(read.credentials, door).toBe('include'); + } + } + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.confirmFlows-11784.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.confirmFlows-11784.test.tsx index 8c6528db8b2..869cf774ff3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.confirmFlows-11784.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.confirmFlows-11784.test.tsx @@ -81,6 +81,7 @@ function respond(body: unknown, status = 200) { return { ok: status >= 200 && status < 300, status, + headers: new Headers(), text: async () => text, json: async () => JSON.parse(text), } as unknown as Response; diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.envelopeUserMessage.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.envelopeUserMessage.test.tsx index 1940c9db52f..570fd4dd7aa 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.envelopeUserMessage.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.envelopeUserMessage.test.tsx @@ -31,6 +31,9 @@ import { cleanup, render, screen, waitFor } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { PackagesPage } from './PackagesPage'; +// Loaded at import so their first load is not paid inside a test's clocked window. +import '@objectstack/formula'; +import '@objectstack/lint'; /** The generic sentence the 5xx prose withhold substitutes (`INTERNAL_ERROR_MESSAGE`). */ const GENERIC = 'Internal server error'; @@ -49,6 +52,7 @@ function stubBody(status: number, body: unknown) { vi.fn(async () => ({ ok: status >= 200 && status < 300, status, + headers: new Headers(), text: async () => JSON.stringify(body), })) as unknown as typeof fetch, ); diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.pendingHeaderMarkup-11804.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.pendingHeaderMarkup-11804.test.tsx index a337d57eb87..4cf39db564d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.pendingHeaderMarkup-11804.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.pendingHeaderMarkup-11804.test.tsx @@ -22,6 +22,9 @@ import { act, cleanup, render, screen } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { PackageDetailSheet, type InstalledPackageRow } from './PackagesPage'; +// Loaded at import so their first load is not paid inside a test's clocked window. +import '@objectstack/formula'; +import '@objectstack/lint'; const PKG: InstalledPackageRow = { manifest: { id: 'com.acme.crm', name: 'Acme CRM', version: '1.0.0', type: 'app' }, @@ -39,7 +42,7 @@ let errors: string[]; function respond(body: unknown) { const text = JSON.stringify(body); - return { ok: true, status: 200, text: async () => text, json: async () => JSON.parse(text) } as unknown as Response; + return { ok: true, status: 200, text: async () => text, headers: new Headers(), json: async () => JSON.parse(text) } as unknown as Response; } beforeEach(() => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx index f991b9b1dd1..c579393476d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/PackagesPage.tsx @@ -105,7 +105,7 @@ import { RefusalMessage } from '../../components/RefusalMessage.js'; import { emitMetadataRefresh } from '../../assistant/assistantBus.js'; import { duplicatePackage, forgetPackageListReads, isSpecPackageId } from '../studio-design/packages-io.js'; import { PackageIdInput } from '../studio-design/PackageIdInput.js'; -import { useWorkspaceAdminStatus } from '@object-ui/auth'; +import { createAuthenticatedFetch, useWorkspaceAdminStatus } from '@object-ui/auth'; import { getRuntimeConfig, isMarketplaceEnabled } from '../../runtime-config.js'; import { getMarketplacePackage, @@ -223,6 +223,11 @@ type UncheckedPackageRow = Omit & { const API = '/api/v1/packages'; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + /** * The code `PATCH /packages/:id/disable` answers, with `409`, while a * validation rule of an enabled package reads a field the package adds through @@ -237,7 +242,7 @@ async function apiJson(path: string, init?: RequestInit): Promise { // list reads from before it are forgotten however it ends, the session's // held list the app → Studio entries read included. const writes = (init?.method ?? 'GET').toUpperCase() !== 'GET'; - const res = await fetch(path, { + const res = await authFetch(path, { credentials: 'include', headers: { Accept: 'application/json', ...(init?.headers || {}) }, ...init, diff --git a/ui/packages/app-shell/src/views/setup/ConnectorConnectionsPage.test.tsx b/ui/packages/app-shell/src/views/setup/ConnectorConnectionsPage.test.tsx index 46f95a13420..0687da028ff 100644 --- a/ui/packages/app-shell/src/views/setup/ConnectorConnectionsPage.test.tsx +++ b/ui/packages/app-shell/src/views/setup/ConnectorConnectionsPage.test.tsx @@ -98,7 +98,7 @@ beforeEach(() => { calls.push({ url, method, body: init?.body }); const queue = answers.get(`${method} ${url}`); const next = queue ? (queue.length > 1 ? queue.shift()! : queue[0]) : { status: 500, body: errorEnvelope('X', `unexpected ${method} ${url}`) }; - return { ok: next.status >= 200 && next.status < 300, status: next.status, json: async () => next.body } as unknown as Response; + return { ok: next.status >= 200 && next.status < 300, status: next.status, headers: new Headers(), json: async () => next.body } as unknown as Response; }), ); fakeWindow = { closed: false, opener: window, location: { href: 'about:blank' }, close: vi.fn(() => { if (fakeWindow) fakeWindow.closed = true; }) }; diff --git a/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.navContribution.test.tsx b/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.navContribution.test.tsx index a26cbabaeb7..c45bc078d27 100644 --- a/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.navContribution.test.tsx +++ b/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.navContribution.test.tsx @@ -29,6 +29,8 @@ import { } from '../../services/componentRegistry.js'; import { ComponentNavView } from '../ComponentNavView.js'; import { CONNECTOR_CREDENTIALS_REF, connectorCredentialsPagePath } from './connectorCredentials.js'; +// Loaded at import so its first load is not paid inside a test's clocked window. +import '@objectstack/lint'; beforeEach(() => { vi.stubGlobal( @@ -36,6 +38,7 @@ beforeEach(() => { vi.fn(async () => ({ ok: true, status: 200, + headers: new Headers(), json: async () => ({ success: true, data: { credentialRefs: [], total: 0 } }), }) as unknown as Response), ); diff --git a/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.test.tsx b/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.test.tsx index db40c90a611..0fbe7438f60 100644 --- a/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.test.tsx +++ b/ui/packages/app-shell/src/views/setup/ConnectorCredentialsPage.test.tsx @@ -88,6 +88,7 @@ beforeEach(() => { return { ok: answer.status >= 200 && answer.status < 300, status: answer.status, + headers: new Headers(), json: async () => answer.body, } as unknown as Response; }), diff --git a/ui/packages/app-shell/src/views/setup/connectorConnections.ts b/ui/packages/app-shell/src/views/setup/connectorConnections.ts index 9f6b80727bf..b9b9feea631 100644 --- a/ui/packages/app-shell/src/views/setup/connectorConnections.ts +++ b/ui/packages/app-shell/src/views/setup/connectorConnections.ts @@ -38,6 +38,7 @@ import type { ConnectorConnectionState } from '@objectstack/spec/contracts'; import type { ConnectorDescriptor } from '@objectstack/spec/integration'; import { actionErrorDetail } from '@object-ui/core'; +import { createAuthenticatedFetch } from '@object-ui/auth'; import { apiBase } from '../../utils/apiBase.js'; import { componentRefToUrlSegments } from '../../services/componentRegistry.js'; import { readMetadataItems } from './packagedFlows.js'; @@ -98,6 +99,11 @@ export type ConnectionListing = | { kind: 'failed'; message: string }; const JSON_HEADERS = { Accept: 'application/json' } as const; + +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} const STATUSES = new Set(['not_connected', 'connected', 'reconnect_required']); function dataOf(payload: unknown): Record | undefined { @@ -178,7 +184,7 @@ async function bodyOf(res: Response): Promise { async function call(url: string, init: RequestInit): Promise<{ status: number; body: unknown }> { try { - const res = await fetch(url, { credentials: 'include', headers: JSON_HEADERS, cache: 'no-store', ...init }); + const res = await authFetch(url, { credentials: 'include', headers: JSON_HEADERS, cache: 'no-store', ...init }); return { status: res.status, body: await bodyOf(res) }; } catch (err) { if ((err as { name?: unknown })?.name === 'AbortError') throw err; diff --git a/ui/packages/app-shell/src/views/setup/connectorCredentials.test.ts b/ui/packages/app-shell/src/views/setup/connectorCredentials.test.ts index e61ea411689..c5a512102d7 100644 --- a/ui/packages/app-shell/src/views/setup/connectorCredentials.test.ts +++ b/ui/packages/app-shell/src/views/setup/connectorCredentials.test.ts @@ -54,7 +54,7 @@ beforeEach(() => { 'fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { calls.push({ url: String(input), method: (init?.method ?? 'GET').toUpperCase(), body: init?.body }); - return { ok: next.status >= 200 && next.status < 300, status: next.status, json: async () => next.body } as unknown as Response; + return { ok: next.status >= 200 && next.status < 300, status: next.status, headers: new Headers(), json: async () => next.body } as unknown as Response; }), ); }); diff --git a/ui/packages/app-shell/src/views/setup/connectorCredentials.ts b/ui/packages/app-shell/src/views/setup/connectorCredentials.ts index 082e52c298a..990fa86d583 100644 --- a/ui/packages/app-shell/src/views/setup/connectorCredentials.ts +++ b/ui/packages/app-shell/src/views/setup/connectorCredentials.ts @@ -23,6 +23,7 @@ import type { ConnectorCredentialRef } from '@objectstack/spec/contracts'; import { actionErrorDetail } from '@object-ui/core'; +import { createAuthenticatedFetch } from '@object-ui/auth'; import { apiBase } from '../../utils/apiBase.js'; import { componentRefToUrlSegments } from '../../services/componentRegistry.js'; @@ -113,6 +114,11 @@ export function readCredentialWrite(status: number, payload: unknown): Credentia const JSON_HEADERS = { Accept: 'application/json' } as const; +/** The console's authenticated fetch: the stored bearer token beside the session cookie. */ +function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise { + return createAuthenticatedFetch()(input, init); +} + function doorUrl(ref?: string): string { const base = `${apiBase()}/automation/connectors/credential-refs`; return ref === undefined ? base : `${base}/${encodeURIComponent(ref)}`; @@ -126,7 +132,7 @@ async function bodyOf(res: Response): Promise { export async function fetchCredentialListing(signal?: AbortSignal): Promise { let res: Response; try { - res = await fetch(doorUrl(), { credentials: 'include', headers: JSON_HEADERS, cache: 'no-store', signal }); + res = await authFetch(doorUrl(), { credentials: 'include', headers: JSON_HEADERS, cache: 'no-store', signal }); } catch (err) { if ((err as { name?: unknown })?.name === 'AbortError') throw err; return { kind: 'failed', message: (err as Error)?.message ?? String(err) }; @@ -142,7 +148,7 @@ export async function putConnectorCredential(ref: string, value: string): Promis if (value.length === 0) return null; let res: Response; try { - res = await fetch(doorUrl(ref), { + res = await authFetch(doorUrl(ref), { method: 'PUT', credentials: 'include', headers: { ...JSON_HEADERS, 'Content-Type': 'application/json' }, @@ -158,7 +164,7 @@ export async function putConnectorCredential(ref: string, value: string): Promis export async function clearConnectorCredential(ref: string): Promise { let res: Response; try { - res = await fetch(doorUrl(ref), { method: 'DELETE', credentials: 'include', headers: JSON_HEADERS }); + res = await authFetch(doorUrl(ref), { method: 'DELETE', credentials: 'include', headers: JSON_HEADERS }); } catch (err) { return { ok: false, status: 0, message: (err as Error)?.message ?? String(err) }; } diff --git a/ui/packages/app-shell/src/views/setup/setupDoorsBearer.test.ts b/ui/packages/app-shell/src/views/setup/setupDoorsBearer.test.ts new file mode 100644 index 00000000000..02b2710e22b --- /dev/null +++ b/ui/packages/app-shell/src/views/setup/setupDoorsBearer.test.ts @@ -0,0 +1,122 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Setup doors that read and write through their own modules — Connector + * Credentials, Connector Connections, and the installed / org package reads of + * the Packages page — go out through the console's authenticated fetch + * (`createAuthenticatedFetch` in `@object-ui/auth`), the one every other + * console request goes through. + * + * - With a token stored, every call carries `Authorization: Bearer ` + * beside the cookie (`credentials: 'include'`), so a session held by its + * bearer token alone works here as it does on every other page. + * - With no token stored (a cookie session), the same calls go out + * cookie-only, as before. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { TokenStorage } from '@object-ui/auth'; +import { clearConnectorCredential, fetchCredentialListing, putConnectorCredential } from './connectorCredentials'; +import { beginConnection, fetchConnection, fetchConnectionListing, revokeConnection } from './connectorConnections'; +import { + fetchLocalInstalls, + listInstalledPackages, + listOrgPackages, +} from '../../console/marketplace/marketplaceApi'; + +const TOKEN = 'stored-session-token'; + +const reply = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +type Sent = { path: string; method: string; credentials: RequestCredentials | undefined; authorization: string | null }; +let sent: Sent[] = []; + +/** One connectable instance, so the connection listing reaches every read it makes. */ +const META_CONNECTOR = { + items: [ + { name: 'crm_api', label: 'CRM', provider: 'rest', auth: { type: 'oauth2', grant: 'authorization_code' } }, + ], +}; + +function answer(path: string, method: string): Response { + if (path.endsWith('/credential-refs')) return reply({ success: true, data: { credentialRefs: [] } }); + if (path.includes('/credential-refs/')) { + return reply({ success: true, data: { ref: 'crm_key', status: 'set', connectors: [] } }); + } + if (path.endsWith('/meta/connector')) return reply(META_CONNECTOR); + if (path.endsWith('/automation/connectors')) return reply({ success: true, data: { connectors: [] } }); + if (path.endsWith('/connection') && method === 'POST') { + return reply({ success: true, data: { authorizationUrl: 'https://vendor.test/authorize', expiresAt: '' } }); + } + if (path.endsWith('/connection')) return reply({ success: true, data: { connector: 'crm_api', status: 'not_connected' } }); + if (path.endsWith('/cloud-connection/org-packages')) return reply({ success: true, data: { connected: true, items: [] } }); + if (path.endsWith('/cloud-connection/installed')) return reply({ success: true, data: { connected: true, packages: [] } }); + if (path.endsWith('/marketplace/install-local')) return reply({ success: true, data: { items: [] } }); + return reply({ success: false, error: { code: 'NOT_FOUND', message: `no route ${method} ${path}` } }, 404); +} + +beforeEach(() => { + sent = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), 'http://console.test').pathname; + const method = (init?.method ?? 'GET').toUpperCase(); + sent.push({ path, method, credentials: init?.credentials, authorization: new Headers(init?.headers).get('Authorization') }); + return answer(path, method); + }), + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + TokenStorage.clear(); +}); + +/** Each surface's calls, driven once; every request a call makes is asserted. */ +const CALLS: Array<[string, () => Promise]> = [ + ['connector credentials: list', () => fetchCredentialListing()], + ['connector credentials: set', () => putConnectorCredential('crm_key', 'secret-value')], + ['connector credentials: clear', () => clearConnectorCredential('crm_key')], + ['connector connections: list', () => fetchConnectionListing()], + ['connector connections: status', () => fetchConnection('crm_api')], + ['connector connections: begin', () => beginConnection('crm_api')], + ['connector connections: begin with an installer client', () => beginConnection('crm_api', { clientId: 'cid', clientSecret: 'cs' })], + ['connector connections: revoke', () => revokeConnection('crm_api')], + ['packages: org packages', () => listOrgPackages()], + ['packages: cloud-installed list', () => listInstalledPackages()], + ['packages: local install ledger', () => fetchLocalInstalls()], +]; + +describe('the Setup doors send the stored bearer token', () => { + it.each(CALLS)('%s carries `Authorization: Bearer ` and the cookie', async (_name, call) => { + TokenStorage.set(TOKEN); + await call(); + expect(sent.length).toBeGreaterThan(0); + for (const request of sent) { + expect(request.authorization, `${request.method} ${request.path}`).toBe(`Bearer ${TOKEN}`); + expect(request.credentials, `${request.method} ${request.path}`).toBe('include'); + } + }); + + it.each(CALLS)('%s with no token stored goes out cookie-only, as before', async (_name, call) => { + TokenStorage.clear(); + await call(); + expect(sent.length).toBeGreaterThan(0); + for (const request of sent) { + expect(request.authorization, `${request.method} ${request.path}`).toBeNull(); + expect(request.credentials, `${request.method} ${request.path}`).toBe('include'); + } + }); + + it('the connection listing reaches every read it makes (declarations, registry, status)', async () => { + TokenStorage.set(TOKEN); + await fetchConnectionListing(); + expect(sent.map((r) => r.path)).toEqual([ + '/api/v1/meta/connector', + '/api/v1/automation/connectors', + '/api/v1/automation/connectors/crm_api/connection', + ]); + }); +});