Skip to content

Commit aca5601

Browse files
fix: use access check for coworker (#1064)
1 parent 5dc52b6 commit aca5601

10 files changed

Lines changed: 112 additions & 95 deletions

File tree

‎docs/chat-ao-component.md‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,11 @@ send is scheduled, and a warning toast asks the user to wait for the response.
4141

4242
`coworker/` owns AO endpoint resolution and the on-demand
4343
`checkCoworkerAccess()` helper. It checks chat access for the current IMS user
44-
and organization, returning `{ allowed }` or `{ error, status? }`. ACS uses
45-
the AO region with a VA7 fallback; only production is supported.
46-
47-
Entitlement enforcement is temporarily bypassed during Coworker startup; no ACS
48-
request is made. The helper and access handling remain intact. The flow below
49-
applies when `checkAccess({ enforceEntitlement: true })` is used.
44+
and organization, returning `{ allowed }` or `{ error, status? }`. It calls
45+
`GET /api/access` on the same regional/environment AO host as chat, using
46+
the shared bearer-token and tenant headers plus the active IMS client ID as `x-api-key`.
47+
AO's boolean `allowed` field determines permission; malformed responses are
48+
verification errors.
5049

5150
Coworker session startup checks access before loading history or skills and
5251
opening connections. The standalone input stays hidden until access is permitted,
@@ -62,7 +61,7 @@ Switching org reloads the page and checks access again.
6261
CMA startup is unchanged. The full panel uses the presentation-only
6362
`renderChatStatus()` renderer in `shared/chat/status/status.js`. Default status
6463
mapping and wording live in `shared/chat/access.js` for either harness to reuse;
65-
the ACS request remains Coworker-specific.
64+
the access request remains Coworker-specific.
6665

6766
## Input ownership
6867

‎nx2/blocks/chat-ao/coworker/access.js‎

Lines changed: 15 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,41 @@
1-
import { loadIms } from '../../../utils/ims.js';
2-
import { getOrgId } from '../utils/uploads.js';
3-
import { resolveCoworkerAccessBase } from './endpoints.js';
1+
import { aoContext } from '../utils/uploads.js';
42

53
const pendingChecks = new Map();
64

7-
async function requestAccess({ base, orgId, token }) {
8-
const uri = `/orgs/${orgId}/apps/coworker/chat/*`;
5+
async function requestAccess({ base, headers, imsClientId }) {
96
try {
10-
const resp = await fetch(`${base}/enforcement/cx-coworker`, {
11-
method: 'POST',
7+
const resp = await fetch(`${base}/api/access`, {
8+
method: 'GET',
129
headers: {
13-
authorization: `Bearer ${token}`,
14-
'x-gw-ims-org-id': orgId,
15-
'content-type': 'application/json',
10+
...headers,
11+
'x-api-key': imsClientId,
1612
accept: 'application/json',
1713
},
18-
body: JSON.stringify({ requests: [{ resource: { uri }, action: 'use' }] }),
1914
cache: 'no-store',
2015
});
2116
if (resp.status !== 200) return { error: 'http', status: resp.status };
2217

2318
const json = await resp.json().catch(() => null);
24-
const decision = json?.responses?.[0];
25-
if (!Array.isArray(json?.responses) || json.responses.length !== 1
26-
|| decision?.resource?.uri !== uri || decision?.action !== 'use'
27-
|| !['permit', 'deny'].includes(decision?.effect)) {
19+
if (typeof json?.allowed !== 'boolean') {
2820
return { error: 'invalid-response', status: resp.status };
2921
}
30-
return { allowed: decision.effect === 'permit' };
22+
return { allowed: json.allowed };
3123
} catch {
3224
return { error: 'network' };
3325
}
3426
}
3527

3628
export async function checkCoworkerAccess() {
3729
try {
38-
const { accessToken, userId, projectedProductContext } = await loadIms();
39-
const orgId = getOrgId(projectedProductContext);
40-
if (!accessToken?.token || !orgId) return { error: 'identity' };
30+
const {
31+
base, tenantId: orgId, userId, token, headers, imsClientId,
32+
} = await aoContext();
33+
if (!token || !orgId) return { error: 'identity' };
34+
if (!imsClientId) return { error: 'configuration' };
4135

42-
const base = resolveCoworkerAccessBase(projectedProductContext);
43-
if (!base) return { error: 'configuration' };
44-
45-
const key = JSON.stringify([userId, orgId, base, accessToken.token]);
36+
const key = JSON.stringify([userId, orgId, base, token, imsClientId]);
4637
if (!pendingChecks.has(key)) {
47-
pendingChecks.set(key, requestAccess({ base, orgId, token: accessToken.token })
38+
pendingChecks.set(key, requestAccess({ base, headers, imsClientId })
4839
.finally(() => pendingChecks.delete(key)));
4940
}
5041
return await pendingChecks.get(key);

‎nx2/blocks/chat-ao/coworker/controller.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ const STALE_EPISODE_MS = 24 * 60 * 60 * 1000;
2727
// AO-direct / CX Coworker harness: episode history comes from the orchestrator
2828
// REST API (list + messages + warm session). See docs/chat-ao-controller-decoupling.md.
2929
export default class CoworkerChatController extends BaseChatController {
30-
async checkAccess({ enforceEntitlement = false } = {}) {
30+
async checkAccess({ enforceEntitlement = true } = {}) {
3131
this._access = CHECKING_CHAT_ACCESS;
3232
this._update();
3333
const result = enforceEntitlement ? await checkCoworkerAccess() : { allowed: true };

‎nx2/blocks/chat-ao/coworker/endpoints.js‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { DEFAULT_AO_LOCATION, AO_HTTP_BASE, AO_WS_BASE } from './constants.js';
1+
import { AO_HTTP_BASE, AO_WS_BASE } from './constants.js';
22

33
export function resolveAoLocation(projectedProductContext) {
44
const found = projectedProductContext?.find(({ prodCtx } = {}) => prodCtx?.statusCode === 'ACTIVE'
@@ -21,9 +21,3 @@ export function resolveAoWsBase(projectedProductContext) {
2121
const loc = resolveAoLocation(projectedProductContext);
2222
return loc ? `wss://agent-orchestrator-${loc.environment}-${loc.region}.adobe.io` : AO_WS_BASE;
2323
}
24-
25-
export function resolveCoworkerAccessBase(projectedProductContext) {
26-
const loc = resolveAoLocation(projectedProductContext) ?? DEFAULT_AO_LOCATION;
27-
if (loc.environment !== 'prod') return undefined;
28-
return `https://cx-accesscontrol-${loc.region}.adobe.io`;
29-
}

‎nx2/blocks/chat-ao/utils/uploads.js‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,17 @@ export function getOrgId(projectedProductContext) {
99

1010
// Shared IMS -> {base, headers} composition every AO REST call needs.
1111
export async function aoContext() {
12-
const { accessToken, userId, projectedProductContext } = await loadIms();
12+
const {
13+
accessToken, userId, projectedProductContext, imsClientId,
14+
} = await loadIms();
1315
const tenantId = getOrgId(projectedProductContext);
1416
return {
1517
base: resolveAoHttpBase(projectedProductContext),
1618
projectedProductContext,
1719
tenantId,
1820
userId,
21+
token: accessToken?.token,
22+
imsClientId,
1923
headers: {
2024
authorization: `Bearer ${accessToken?.token}`,
2125
'x-tenant-id': tenantId,

‎nx2/utils/ims.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,9 @@ async function loadDetails(accessToken) {
104104
const tenantId = getTenantId(profile);
105105
const getIo = getIoFactory(accessToken);
106106
const getOrgs = getOrgsFactory(accessToken);
107-
return { ...profile, tenantId, accessToken, getIo, getOrgs };
107+
return {
108+
...profile, tenantId, accessToken, imsClientId, getIo, getOrgs,
109+
};
108110
}
109111

110112
function settleWithTimeout(resolve, reject) {

‎test/nx2/blocks/chat-ao/coworker/access.test.js‎

Lines changed: 66 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
import { expect } from '@esm-bundle/chai';
22
import { checkCoworkerAccess } from '../../../../../nx2/blocks/chat-ao/coworker/access.js';
3-
import {
4-
resolveCoworkerAccessBase, resolveAoHttpBase,
5-
} from '../../../../../nx2/blocks/chat-ao/coworker/endpoints.js';
3+
import { resolveAoHttpBase } from '../../../../../nx2/blocks/chat-ao/coworker/endpoints.js';
64
import { resetMockIms, setMockIms } from '../../../mocks/ims.js';
75

86
const orgId = 'selected@AdobeOrg';
@@ -19,24 +17,21 @@ function context({ org = orgId, region = 'CAN2', environment = 'PROD' } = {}) {
1917
}];
2018
}
2119

22-
function response(effect = 'permit', overrides = {}) {
23-
return { responses: [{ resource: { uri }, action: 'use', effect, ...overrides }] };
20+
function response(allowed = true) {
21+
return { allowed, reason: null, message: null };
2422
}
2523

2624
describe('Coworker access endpoints', () => {
2725
['can2', 'new1'].forEach((region) => {
28-
it(`derives the ACS host from the AO region (${region}) without an allowlist`, () => {
26+
it(`resolves the AO region (${region}) without an allowlist`, () => {
2927
const profile = context({ region: region.toUpperCase() });
3028
expect(resolveAoHttpBase(profile))
3129
.to.equal(`https://agent-orchestrator-prod-${region}.adobe.io`);
32-
expect(resolveCoworkerAccessBase(profile))
33-
.to.equal(`https://cx-accesscontrol-${region}.adobe.io`);
3430
});
3531
});
3632

3733
it('uses the same production VA7 fallback as AO when location is unavailable', () => {
3834
expect(resolveAoHttpBase()).to.equal('https://agent-orchestrator-prod-va7.adobe.io');
39-
expect(resolveCoworkerAccessBase()).to.equal('https://cx-accesscontrol-va7.adobe.io');
4035
});
4136
});
4237

@@ -65,25 +60,36 @@ describe('checkCoworkerAccess', () => {
6560
});
6661

6762
it('checks chat use with the selected IMS org and current user token', async () => {
68-
setMockIms({ token: { token: 'selected-org-token' } });
63+
setMockIms({ token: { token: 'selected-org-token' }, imsClientId: 'darkalley' });
6964
expect(await checkCoworkerAccess()).to.deep.equal({ allowed: true });
7065
expect(calls).to.have.length(1);
7166
const [{ url, opts }] = calls;
72-
expect(url).to.equal('https://cx-accesscontrol-can2.adobe.io/enforcement/cx-coworker');
73-
expect(opts.method).to.equal('POST');
67+
expect(url).to.equal('https://agent-orchestrator-prod-can2.adobe.io/api/access');
68+
expect(opts.method).to.equal('GET');
7469
expect(opts.headers).to.deep.equal({
7570
authorization: 'Bearer selected-org-token',
76-
'x-gw-ims-org-id': orgId,
77-
'content-type': 'application/json',
71+
'x-tenant-id': orgId,
72+
'x-api-key': 'darkalley',
7873
accept: 'application/json',
7974
});
80-
expect(JSON.parse(opts.body)).to.deep.equal({
81-
requests: [{ resource: { uri }, action: 'use' }],
82-
});
75+
expect(opts.body).to.equal(undefined);
76+
expect(opts.cache).to.equal('no-store');
77+
});
78+
79+
it('uses the AO fallback host when the selected org has no location', async () => {
80+
setMockIms({ projectedProductContext: [{ prodCtx: { owningEntity: orgId } }] });
81+
expect(await checkCoworkerAccess()).to.deep.equal({ allowed: true });
82+
expect(calls[0].url).to.equal('https://agent-orchestrator-prod-va7.adobe.io/api/access');
83+
});
84+
85+
it('does not request access without a configured IMS client', async () => {
86+
setMockIms({ imsClientId: null });
87+
expect(await checkCoworkerAccess()).to.deep.equal({ error: 'configuration' });
88+
expect(calls).to.have.length(0);
8389
});
8490

8591
it('reports an explicit denial separately from a failed check', async () => {
86-
body = response('deny');
92+
body = response(false);
8793
expect(await checkCoworkerAccess()).to.deep.equal({ allowed: false });
8894
});
8995

@@ -95,14 +101,14 @@ describe('checkCoworkerAccess', () => {
95101
});
96102

97103
[
98-
{ responses: [] },
99-
{ responses: {} },
100-
{ responses: [null] },
101-
{ responses: [...response().responses, ...response().responses] },
102-
response('allow'),
103-
response('PERMIT'),
104-
response('permit', { action: 'manage' }),
105-
response('permit', { resource: { uri: '/orgs/other/apps/coworker/chat/*' } }),
104+
{},
105+
null,
106+
{ allowed: null },
107+
{ allowed: 'true' },
108+
{ allowed: 'false' },
109+
{ allowed: 1 },
110+
{ allowed: 'permit' },
111+
{ responses: [{ resource: { uri }, action: 'use', effect: 'permit' }] },
106112
].forEach((invalidBody, index) => {
107113
it(`rejects a malformed or mismatched decision (${index + 1})`, async () => {
108114
body = invalidBody;
@@ -140,18 +146,19 @@ describe('checkCoworkerAccess', () => {
140146
{ environment: 'STAGE' },
141147
{ environment: 'DEV' },
142148
].forEach((location) => {
143-
it(`does not invent an ACS host for ${JSON.stringify(location)}`, async () => {
149+
it(`uses the same AO environment as chat for ${JSON.stringify(location)}`, async () => {
144150
setMockIms({ projectedProductContext: context(location) });
145-
expect(await checkCoworkerAccess()).to.deep.equal({ error: 'configuration' });
146-
expect(calls).to.have.length(0);
151+
expect(await checkCoworkerAccess()).to.deep.equal({ allowed: true });
152+
expect(calls[0].url)
153+
.to.equal(`https://agent-orchestrator-${location.environment.toLowerCase()}-can2.adobe.io/api/access`);
147154
});
148155
});
149156

150157
it('shares concurrent checks but does not cache completed decisions', async () => {
151158
const results = await Promise.all([checkCoworkerAccess(), checkCoworkerAccess()]);
152159
expect(results).to.deep.equal([{ allowed: true }, { allowed: true }]);
153160
expect(calls).to.have.length(1);
154-
body = response('deny');
161+
body = response(false);
155162
expect(await checkCoworkerAccess()).to.deep.equal({ allowed: false });
156163
expect(calls).to.have.length(2);
157164
});
@@ -164,28 +171,44 @@ describe('checkCoworkerAccess', () => {
164171
expect(calls).to.have.length(2);
165172
});
166173

167-
it('does not share in-flight checks across organizations or tokens', async () => {
174+
it('separates in-flight checks by org, token, AO region, and IMS client', async () => {
168175
const pending = [];
176+
const started = [];
177+
const nextRequest = () => new Promise((resolve) => { started.push(resolve); });
169178
window.fetch = (url, opts) => {
170179
calls.push({ url, opts });
180+
started.shift()();
171181
return new Promise((resolve) => { pending.push(resolve); });
172182
};
183+
const firstStarted = nextRequest();
173184
const first = checkCoworkerAccess();
174-
await Promise.resolve();
185+
await firstStarted;
175186
setMockIms({ projectedProductContext: context({ org: 'other@AdobeOrg' }) });
187+
const secondStarted = nextRequest();
176188
const second = checkCoworkerAccess();
177-
await Promise.resolve();
189+
await secondStarted;
178190
setMockIms({ token: { token: 'refreshed-token' } });
191+
const thirdStarted = nextRequest();
179192
const third = checkCoworkerAccess();
180-
await Promise.resolve();
181-
expect(calls).to.have.length(3);
182-
pending.forEach((resolve, index) => {
183-
const result = response('permit', {
184-
resource: { uri: JSON.parse(calls[index].opts.body).requests[0].resource.uri },
185-
});
186-
resolve(new Response(JSON.stringify(result)));
187-
});
188-
expect(await Promise.all([first, second, third]))
189-
.to.deep.equal([{ allowed: true }, { allowed: true }, { allowed: true }]);
193+
await thirdStarted;
194+
setMockIms({ projectedProductContext: context({ org: 'other@AdobeOrg', region: 'NEW1' }) });
195+
const fourthStarted = nextRequest();
196+
const fourth = checkCoworkerAccess();
197+
await fourthStarted;
198+
setMockIms({ imsClientId: 'another-client' });
199+
const fifthStarted = nextRequest();
200+
const fifth = checkCoworkerAccess();
201+
await fifthStarted;
202+
expect(calls).to.have.length(5);
203+
expect(calls[4].opts.headers['x-api-key']).to.equal('another-client');
204+
pending.forEach((resolve) => resolve(new Response(JSON.stringify(response()))));
205+
expect(await Promise.all([first, second, third, fourth, fifth]))
206+
.to.deep.equal([
207+
{ allowed: true },
208+
{ allowed: true },
209+
{ allowed: true },
210+
{ allowed: true },
211+
{ allowed: true },
212+
]);
190213
});
191214
});

‎test/nx2/blocks/chat-ao/session.test.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ describe('lazy AO session controllers', () => {
1414
const { controller } = session;
1515
if (!controller || controllers.has(controller)) return;
1616
controllers.add(controller);
17+
if (controller.checkAccess) controller.checkAccess = async () => true;
1718
controller.loadEpisodes = async () => {
1819
episodeLoads += 1;
1920
controller._update();
@@ -58,7 +59,7 @@ describe('lazy AO session controllers', () => {
5859
expect(requests.some((href) => href.includes('/chat-ao/coworker/controller.js'))).to.equal(false);
5960
});
6061

61-
it('loads Coworker by default and retains the entitlement bypass', async () => {
62+
it('loads Coworker by default', async () => {
6263
const owner = document.createElement('nx-chat-ao');
6364
const session = getAoSession({ context, owner });
6465
subscribe(session, owner);

‎test/nx2/blocks/chat-ao/shared-session.test.js‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -117,9 +117,6 @@ describe('standalone input and full AO chat sharing', () => {
117117
accessEffect = 'permit';
118118
accessStatus = 200;
119119
accessWait = undefined;
120-
patch(CoworkerChatController.prototype, 'checkAccess', function enforceAccess() {
121-
return checkAccess.call(this, { enforceEntitlement: true });
122-
});
123120
setMockIms({
124121
projectedProductContext: [{ prodCtx: { owningEntity: org } }],
125122
});
@@ -129,12 +126,12 @@ describe('standalone input and full AO chat sharing', () => {
129126
if (href.startsWith('/') || href.startsWith(window.location.origin)) {
130127
return originalFetch(resource, options);
131128
}
132-
if (href.includes('/enforcement/cx-coworker')) {
129+
if (href.endsWith('/api/access')) {
133130
accessChecks += 1;
134131
await accessWait?.promise;
135-
const responses = JSON.parse(options.body).requests
136-
.map((request) => ({ ...request, effect: accessEffect }));
137-
return new Response(JSON.stringify({ responses }), {
132+
return new Response(JSON.stringify({
133+
allowed: accessEffect === 'permit', reason: null, message: null,
134+
}), {
138135
status: accessStatus, headers: { 'Content-Type': 'application/json' },
139136
});
140137
}
@@ -218,8 +215,10 @@ describe('standalone input and full AO chat sharing', () => {
218215
resetMockIms();
219216
});
220217

221-
it('initializes both Coworker views without calling entitlement enforcement by default', async () => {
222-
patch(CoworkerChatController.prototype, 'checkAccess', checkAccess);
218+
it('supports explicitly bypassing the Coworker access check for both views', async () => {
219+
patch(CoworkerChatController.prototype, 'checkAccess', function skipAccess() {
220+
return checkAccess.call(this, { enforceEntitlement: false });
221+
});
223222
accessEffect = 'deny';
224223
accessStatus = 503;
225224
const [standalone, full] = await pair('coworker');

0 commit comments

Comments
 (0)