Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions docs/chat-ao-component.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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

Expand Down
39 changes: 15 additions & 24 deletions nx2/blocks/chat-ao/coworker/access.js
Original file line number Diff line number Diff line change
@@ -1,50 +1,41 @@
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' };
}
}

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);
Expand Down
2 changes: 1 addition & 1 deletion nx2/blocks/chat-ao/coworker/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
8 changes: 1 addition & 7 deletions nx2/blocks/chat-ao/coworker/endpoints.js
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -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`;
}
6 changes: 5 additions & 1 deletion nx2/blocks/chat-ao/utils/uploads.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion nx2/utils/ims.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
109 changes: 66 additions & 43 deletions test/nx2/blocks/chat-ao/coworker/access.test.js
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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');
});
});

Expand Down Expand Up @@ -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 });
});

Expand All @@ -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;
Expand Down Expand Up @@ -140,18 +146,19 @@ 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`);
});
});

it('shares concurrent checks but does not cache completed decisions', async () => {
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);
});
Expand All @@ -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 },
]);
});
});
3 changes: 2 additions & 1 deletion test/nx2/blocks/chat-ao/session.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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);
Expand Down
17 changes: 8 additions & 9 deletions test/nx2/blocks/chat-ao/shared-session.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }],
});
Expand All @@ -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' },
});
}
Expand Down Expand Up @@ -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');
Expand Down
Loading
Loading