diff --git a/docs/chat-ao-component.md b/docs/chat-ao-component.md index e1c743332..291b0585c 100644 --- a/docs/chat-ao-component.md +++ b/docs/chat-ao-component.md @@ -41,12 +41,11 @@ send is scheduled, and a warning toast asks the user to wait for the response. `coworker/` owns AO endpoint resolution and the on-demand `checkCoworkerAccess()` helper. It checks chat access for the current IMS user -and organization, returning `{ allowed }` or `{ error, status? }`. ACS uses -the AO region with a VA7 fallback; only production is supported. - -Entitlement enforcement is temporarily bypassed during Coworker startup; no ACS -request is made. The helper and access handling remain intact. The flow below -applies when `checkAccess({ enforceEntitlement: true })` is used. +and organization, returning `{ allowed }` or `{ error, status? }`. It calls +`GET /api/access` on the same regional/environment AO host as chat, using +the shared bearer-token and tenant headers plus the active IMS client ID as `x-api-key`. +AO's boolean `allowed` field determines permission; malformed responses are +verification errors. Coworker session startup checks access before loading history or skills and opening connections. The standalone input stays hidden until access is permitted, @@ -62,7 +61,7 @@ Switching org reloads the page and checks access again. CMA startup is unchanged. The full panel uses the presentation-only `renderChatStatus()` renderer in `shared/chat/status/status.js`. Default status mapping and wording live in `shared/chat/access.js` for either harness to reuse; -the ACS request remains Coworker-specific. +the access request remains Coworker-specific. ## Input ownership diff --git a/nx2/blocks/chat-ao/coworker/access.js b/nx2/blocks/chat-ao/coworker/access.js index 3ca0b583d..12b8cd2be 100644 --- a/nx2/blocks/chat-ao/coworker/access.js +++ b/nx2/blocks/chat-ao/coworker/access.js @@ -1,33 +1,25 @@ -import { loadIms } from '../../../utils/ims.js'; -import { getOrgId } from '../utils/uploads.js'; -import { resolveCoworkerAccessBase } from './endpoints.js'; +import { aoContext } from '../utils/uploads.js'; const pendingChecks = new Map(); -async function requestAccess({ base, orgId, token }) { - const uri = `/orgs/${orgId}/apps/coworker/chat/*`; +async function requestAccess({ base, headers, imsClientId }) { try { - const resp = await fetch(`${base}/enforcement/cx-coworker`, { - method: 'POST', + const resp = await fetch(`${base}/api/access`, { + method: 'GET', headers: { - authorization: `Bearer ${token}`, - 'x-gw-ims-org-id': orgId, - 'content-type': 'application/json', + ...headers, + 'x-api-key': imsClientId, accept: 'application/json', }, - body: JSON.stringify({ requests: [{ resource: { uri }, action: 'use' }] }), cache: 'no-store', }); if (resp.status !== 200) return { error: 'http', status: resp.status }; const json = await resp.json().catch(() => null); - const decision = json?.responses?.[0]; - if (!Array.isArray(json?.responses) || json.responses.length !== 1 - || decision?.resource?.uri !== uri || decision?.action !== 'use' - || !['permit', 'deny'].includes(decision?.effect)) { + if (typeof json?.allowed !== 'boolean') { return { error: 'invalid-response', status: resp.status }; } - return { allowed: decision.effect === 'permit' }; + return { allowed: json.allowed }; } catch { return { error: 'network' }; } @@ -35,16 +27,15 @@ async function requestAccess({ base, orgId, token }) { export async function checkCoworkerAccess() { try { - const { accessToken, userId, projectedProductContext } = await loadIms(); - const orgId = getOrgId(projectedProductContext); - if (!accessToken?.token || !orgId) return { error: 'identity' }; + const { + base, tenantId: orgId, userId, token, headers, imsClientId, + } = await aoContext(); + if (!token || !orgId) return { error: 'identity' }; + if (!imsClientId) return { error: 'configuration' }; - const base = resolveCoworkerAccessBase(projectedProductContext); - if (!base) return { error: 'configuration' }; - - const key = JSON.stringify([userId, orgId, base, accessToken.token]); + const key = JSON.stringify([userId, orgId, base, token, imsClientId]); if (!pendingChecks.has(key)) { - pendingChecks.set(key, requestAccess({ base, orgId, token: accessToken.token }) + pendingChecks.set(key, requestAccess({ base, headers, imsClientId }) .finally(() => pendingChecks.delete(key))); } return await pendingChecks.get(key); diff --git a/nx2/blocks/chat-ao/coworker/controller.js b/nx2/blocks/chat-ao/coworker/controller.js index f474c550e..23170f92f 100644 --- a/nx2/blocks/chat-ao/coworker/controller.js +++ b/nx2/blocks/chat-ao/coworker/controller.js @@ -27,7 +27,7 @@ const STALE_EPISODE_MS = 24 * 60 * 60 * 1000; // AO-direct / CX Coworker harness: episode history comes from the orchestrator // REST API (list + messages + warm session). See docs/chat-ao-controller-decoupling.md. export default class CoworkerChatController extends BaseChatController { - async checkAccess({ enforceEntitlement = false } = {}) { + async checkAccess({ enforceEntitlement = true } = {}) { this._access = CHECKING_CHAT_ACCESS; this._update(); const result = enforceEntitlement ? await checkCoworkerAccess() : { allowed: true }; diff --git a/nx2/blocks/chat-ao/coworker/endpoints.js b/nx2/blocks/chat-ao/coworker/endpoints.js index e3d025402..5cee17d5f 100644 --- a/nx2/blocks/chat-ao/coworker/endpoints.js +++ b/nx2/blocks/chat-ao/coworker/endpoints.js @@ -1,4 +1,4 @@ -import { DEFAULT_AO_LOCATION, AO_HTTP_BASE, AO_WS_BASE } from './constants.js'; +import { AO_HTTP_BASE, AO_WS_BASE } from './constants.js'; export function resolveAoLocation(projectedProductContext) { const found = projectedProductContext?.find(({ prodCtx } = {}) => prodCtx?.statusCode === 'ACTIVE' @@ -21,9 +21,3 @@ export function resolveAoWsBase(projectedProductContext) { const loc = resolveAoLocation(projectedProductContext); return loc ? `wss://agent-orchestrator-${loc.environment}-${loc.region}.adobe.io` : AO_WS_BASE; } - -export function resolveCoworkerAccessBase(projectedProductContext) { - const loc = resolveAoLocation(projectedProductContext) ?? DEFAULT_AO_LOCATION; - if (loc.environment !== 'prod') return undefined; - return `https://cx-accesscontrol-${loc.region}.adobe.io`; -} diff --git a/nx2/blocks/chat-ao/utils/uploads.js b/nx2/blocks/chat-ao/utils/uploads.js index b2b2aea7c..62e27fe03 100644 --- a/nx2/blocks/chat-ao/utils/uploads.js +++ b/nx2/blocks/chat-ao/utils/uploads.js @@ -9,13 +9,17 @@ export function getOrgId(projectedProductContext) { // Shared IMS -> {base, headers} composition every AO REST call needs. export async function aoContext() { - const { accessToken, userId, projectedProductContext } = await loadIms(); + const { + accessToken, userId, projectedProductContext, imsClientId, + } = await loadIms(); const tenantId = getOrgId(projectedProductContext); return { base: resolveAoHttpBase(projectedProductContext), projectedProductContext, tenantId, userId, + token: accessToken?.token, + imsClientId, headers: { authorization: `Bearer ${accessToken?.token}`, 'x-tenant-id': tenantId, diff --git a/nx2/utils/ims.js b/nx2/utils/ims.js index bdd0d98e0..dc276bcd1 100644 --- a/nx2/utils/ims.js +++ b/nx2/utils/ims.js @@ -104,7 +104,9 @@ async function loadDetails(accessToken) { const tenantId = getTenantId(profile); const getIo = getIoFactory(accessToken); const getOrgs = getOrgsFactory(accessToken); - return { ...profile, tenantId, accessToken, getIo, getOrgs }; + return { + ...profile, tenantId, accessToken, imsClientId, getIo, getOrgs, + }; } function settleWithTimeout(resolve, reject) { diff --git a/test/nx2/blocks/chat-ao/coworker/access.test.js b/test/nx2/blocks/chat-ao/coworker/access.test.js index 9956c6061..dc625ef09 100644 --- a/test/nx2/blocks/chat-ao/coworker/access.test.js +++ b/test/nx2/blocks/chat-ao/coworker/access.test.js @@ -1,8 +1,6 @@ import { expect } from '@esm-bundle/chai'; import { checkCoworkerAccess } from '../../../../../nx2/blocks/chat-ao/coworker/access.js'; -import { - resolveCoworkerAccessBase, resolveAoHttpBase, -} from '../../../../../nx2/blocks/chat-ao/coworker/endpoints.js'; +import { resolveAoHttpBase } from '../../../../../nx2/blocks/chat-ao/coworker/endpoints.js'; import { resetMockIms, setMockIms } from '../../../mocks/ims.js'; const orgId = 'selected@AdobeOrg'; @@ -19,24 +17,21 @@ function context({ org = orgId, region = 'CAN2', environment = 'PROD' } = {}) { }]; } -function response(effect = 'permit', overrides = {}) { - return { responses: [{ resource: { uri }, action: 'use', effect, ...overrides }] }; +function response(allowed = true) { + return { allowed, reason: null, message: null }; } describe('Coworker access endpoints', () => { ['can2', 'new1'].forEach((region) => { - it(`derives the ACS host from the AO region (${region}) without an allowlist`, () => { + it(`resolves the AO region (${region}) without an allowlist`, () => { const profile = context({ region: region.toUpperCase() }); expect(resolveAoHttpBase(profile)) .to.equal(`https://agent-orchestrator-prod-${region}.adobe.io`); - expect(resolveCoworkerAccessBase(profile)) - .to.equal(`https://cx-accesscontrol-${region}.adobe.io`); }); }); it('uses the same production VA7 fallback as AO when location is unavailable', () => { expect(resolveAoHttpBase()).to.equal('https://agent-orchestrator-prod-va7.adobe.io'); - expect(resolveCoworkerAccessBase()).to.equal('https://cx-accesscontrol-va7.adobe.io'); }); }); @@ -65,25 +60,36 @@ describe('checkCoworkerAccess', () => { }); it('checks chat use with the selected IMS org and current user token', async () => { - setMockIms({ token: { token: 'selected-org-token' } }); + setMockIms({ token: { token: 'selected-org-token' }, imsClientId: 'darkalley' }); expect(await checkCoworkerAccess()).to.deep.equal({ allowed: true }); expect(calls).to.have.length(1); const [{ url, opts }] = calls; - expect(url).to.equal('https://cx-accesscontrol-can2.adobe.io/enforcement/cx-coworker'); - expect(opts.method).to.equal('POST'); + expect(url).to.equal('https://agent-orchestrator-prod-can2.adobe.io/api/access'); + expect(opts.method).to.equal('GET'); expect(opts.headers).to.deep.equal({ authorization: 'Bearer selected-org-token', - 'x-gw-ims-org-id': orgId, - 'content-type': 'application/json', + 'x-tenant-id': orgId, + 'x-api-key': 'darkalley', accept: 'application/json', }); - expect(JSON.parse(opts.body)).to.deep.equal({ - requests: [{ resource: { uri }, action: 'use' }], - }); + expect(opts.body).to.equal(undefined); + expect(opts.cache).to.equal('no-store'); + }); + + it('uses the AO fallback host when the selected org has no location', async () => { + setMockIms({ projectedProductContext: [{ prodCtx: { owningEntity: orgId } }] }); + expect(await checkCoworkerAccess()).to.deep.equal({ allowed: true }); + expect(calls[0].url).to.equal('https://agent-orchestrator-prod-va7.adobe.io/api/access'); + }); + + it('does not request access without a configured IMS client', async () => { + setMockIms({ imsClientId: null }); + expect(await checkCoworkerAccess()).to.deep.equal({ error: 'configuration' }); + expect(calls).to.have.length(0); }); it('reports an explicit denial separately from a failed check', async () => { - body = response('deny'); + body = response(false); expect(await checkCoworkerAccess()).to.deep.equal({ allowed: false }); }); @@ -95,14 +101,14 @@ describe('checkCoworkerAccess', () => { }); [ - { responses: [] }, - { responses: {} }, - { responses: [null] }, - { responses: [...response().responses, ...response().responses] }, - response('allow'), - response('PERMIT'), - response('permit', { action: 'manage' }), - response('permit', { resource: { uri: '/orgs/other/apps/coworker/chat/*' } }), + {}, + null, + { allowed: null }, + { allowed: 'true' }, + { allowed: 'false' }, + { allowed: 1 }, + { allowed: 'permit' }, + { responses: [{ resource: { uri }, action: 'use', effect: 'permit' }] }, ].forEach((invalidBody, index) => { it(`rejects a malformed or mismatched decision (${index + 1})`, async () => { body = invalidBody; @@ -140,10 +146,11 @@ describe('checkCoworkerAccess', () => { { environment: 'STAGE' }, { environment: 'DEV' }, ].forEach((location) => { - it(`does not invent an ACS host for ${JSON.stringify(location)}`, async () => { + it(`uses the same AO environment as chat for ${JSON.stringify(location)}`, async () => { setMockIms({ projectedProductContext: context(location) }); - expect(await checkCoworkerAccess()).to.deep.equal({ error: 'configuration' }); - expect(calls).to.have.length(0); + expect(await checkCoworkerAccess()).to.deep.equal({ allowed: true }); + expect(calls[0].url) + .to.equal(`https://agent-orchestrator-${location.environment.toLowerCase()}-can2.adobe.io/api/access`); }); }); @@ -151,7 +158,7 @@ describe('checkCoworkerAccess', () => { const results = await Promise.all([checkCoworkerAccess(), checkCoworkerAccess()]); expect(results).to.deep.equal([{ allowed: true }, { allowed: true }]); expect(calls).to.have.length(1); - body = response('deny'); + body = response(false); expect(await checkCoworkerAccess()).to.deep.equal({ allowed: false }); expect(calls).to.have.length(2); }); @@ -164,28 +171,44 @@ describe('checkCoworkerAccess', () => { expect(calls).to.have.length(2); }); - it('does not share in-flight checks across organizations or tokens', async () => { + it('separates in-flight checks by org, token, AO region, and IMS client', async () => { const pending = []; + const started = []; + const nextRequest = () => new Promise((resolve) => { started.push(resolve); }); window.fetch = (url, opts) => { calls.push({ url, opts }); + started.shift()(); return new Promise((resolve) => { pending.push(resolve); }); }; + const firstStarted = nextRequest(); const first = checkCoworkerAccess(); - await Promise.resolve(); + await firstStarted; setMockIms({ projectedProductContext: context({ org: 'other@AdobeOrg' }) }); + const secondStarted = nextRequest(); const second = checkCoworkerAccess(); - await Promise.resolve(); + await secondStarted; setMockIms({ token: { token: 'refreshed-token' } }); + const thirdStarted = nextRequest(); const third = checkCoworkerAccess(); - await Promise.resolve(); - expect(calls).to.have.length(3); - pending.forEach((resolve, index) => { - const result = response('permit', { - resource: { uri: JSON.parse(calls[index].opts.body).requests[0].resource.uri }, - }); - resolve(new Response(JSON.stringify(result))); - }); - expect(await Promise.all([first, second, third])) - .to.deep.equal([{ allowed: true }, { allowed: true }, { allowed: true }]); + await thirdStarted; + setMockIms({ projectedProductContext: context({ org: 'other@AdobeOrg', region: 'NEW1' }) }); + const fourthStarted = nextRequest(); + const fourth = checkCoworkerAccess(); + await fourthStarted; + setMockIms({ imsClientId: 'another-client' }); + const fifthStarted = nextRequest(); + const fifth = checkCoworkerAccess(); + await fifthStarted; + expect(calls).to.have.length(5); + expect(calls[4].opts.headers['x-api-key']).to.equal('another-client'); + pending.forEach((resolve) => resolve(new Response(JSON.stringify(response())))); + expect(await Promise.all([first, second, third, fourth, fifth])) + .to.deep.equal([ + { allowed: true }, + { allowed: true }, + { allowed: true }, + { allowed: true }, + { allowed: true }, + ]); }); }); diff --git a/test/nx2/blocks/chat-ao/session.test.js b/test/nx2/blocks/chat-ao/session.test.js index 9f6c180e4..a607298ad 100644 --- a/test/nx2/blocks/chat-ao/session.test.js +++ b/test/nx2/blocks/chat-ao/session.test.js @@ -14,6 +14,7 @@ describe('lazy AO session controllers', () => { const { controller } = session; if (!controller || controllers.has(controller)) return; controllers.add(controller); + if (controller.checkAccess) controller.checkAccess = async () => true; controller.loadEpisodes = async () => { episodeLoads += 1; controller._update(); @@ -58,7 +59,7 @@ describe('lazy AO session controllers', () => { expect(requests.some((href) => href.includes('/chat-ao/coworker/controller.js'))).to.equal(false); }); - it('loads Coworker by default and retains the entitlement bypass', async () => { + it('loads Coworker by default', async () => { const owner = document.createElement('nx-chat-ao'); const session = getAoSession({ context, owner }); subscribe(session, owner); diff --git a/test/nx2/blocks/chat-ao/shared-session.test.js b/test/nx2/blocks/chat-ao/shared-session.test.js index 8af974212..9376cafe7 100644 --- a/test/nx2/blocks/chat-ao/shared-session.test.js +++ b/test/nx2/blocks/chat-ao/shared-session.test.js @@ -117,9 +117,6 @@ describe('standalone input and full AO chat sharing', () => { accessEffect = 'permit'; accessStatus = 200; accessWait = undefined; - patch(CoworkerChatController.prototype, 'checkAccess', function enforceAccess() { - return checkAccess.call(this, { enforceEntitlement: true }); - }); setMockIms({ projectedProductContext: [{ prodCtx: { owningEntity: org } }], }); @@ -129,12 +126,12 @@ describe('standalone input and full AO chat sharing', () => { if (href.startsWith('/') || href.startsWith(window.location.origin)) { return originalFetch(resource, options); } - if (href.includes('/enforcement/cx-coworker')) { + if (href.endsWith('/api/access')) { accessChecks += 1; await accessWait?.promise; - const responses = JSON.parse(options.body).requests - .map((request) => ({ ...request, effect: accessEffect })); - return new Response(JSON.stringify({ responses }), { + return new Response(JSON.stringify({ + allowed: accessEffect === 'permit', reason: null, message: null, + }), { status: accessStatus, headers: { 'Content-Type': 'application/json' }, }); } @@ -218,8 +215,10 @@ describe('standalone input and full AO chat sharing', () => { resetMockIms(); }); - it('initializes both Coworker views without calling entitlement enforcement by default', async () => { - patch(CoworkerChatController.prototype, 'checkAccess', checkAccess); + it('supports explicitly bypassing the Coworker access check for both views', async () => { + patch(CoworkerChatController.prototype, 'checkAccess', function skipAccess() { + return checkAccess.call(this, { enforceEntitlement: false }); + }); accessEffect = 'deny'; accessStatus = 503; const [standalone, full] = await pair('coworker'); diff --git a/test/nx2/mocks/ims.js b/test/nx2/mocks/ims.js index 689b3c696..97cdd5ca5 100644 --- a/test/nx2/mocks/ims.js +++ b/test/nx2/mocks/ims.js @@ -1,6 +1,7 @@ let _accessToken = { token: 'test-token' }; let _anonymous = false; let _userId = 'test-user@AdobeID'; +let _imsClientId = 'test-client'; let _displayName = 'Test User'; let _email = 'test-user@adobe.com'; let _io = { user: { avatar: 'https://example.com/avatar.png' } }; @@ -13,11 +14,12 @@ export const IMS_ORIGIN = 'https://ims-na1.adobelogin.com'; export function setMockIms({ token, anonymous, userId, displayName, email, io, orgs, - ownerOrg, tenantId, projectedProductContext, + ownerOrg, tenantId, projectedProductContext, imsClientId, } = {}) { if (token !== undefined) _accessToken = token; if (anonymous !== undefined) _anonymous = anonymous; if (userId !== undefined) _userId = userId; + if (imsClientId !== undefined) _imsClientId = imsClientId; if (displayName !== undefined) _displayName = displayName; if (email !== undefined) _email = email; if (io !== undefined) _io = io; @@ -31,6 +33,7 @@ export function resetMockIms() { _accessToken = { token: 'test-token' }; _anonymous = false; _userId = 'test-user@AdobeID'; + _imsClientId = 'test-client'; _displayName = 'Test User'; _email = 'test-user@adobe.com'; _io = { user: { avatar: 'https://example.com/avatar.png' } }; @@ -46,6 +49,7 @@ export const loadIms = async () => { anonymous: false, accessToken: _accessToken, userId: _userId, + imsClientId: _imsClientId, displayName: _displayName, email: _email, ownerOrg: _ownerOrg,