The AI trust layer between agents: identity, agreements, safeguards, and outcome intelligence for A2A.

Viewing files at commit 39e235ac59f4Commit detailsView latest

tests/api.test.ts 394 lines · 13.6 KB · typescript
1
import { describe, expect, it } from 'vitest';
2
import { buildApi } from '../apps/api/src/app.js';
3
4
describe('HTTP API', () => {
5
  it('serves health, readiness, and OpenAPI', async () => {
6
    const app = buildApi();
7
    await app.ready();
8
    expect((await app.inject({ method: 'GET', url: '/health' })).statusCode).toBe(200);
9
    expect((await app.inject({ method: 'GET', url: '/ready' })).json()).toEqual({
10
      status: 'ready',
11
    });
12
    expect(
13
      (await app.inject({ method: 'GET', url: '/extensions/trust/v0.1' })).json(),
14
    ).toMatchObject({ version: '0.1', transportsMessages: false });
15
    const specification = (await app.inject({ method: 'GET', url: '/openapi.json' })).json();
16
    expect(specification.info.title).toBe('OpenClasp API');
17
    expect(specification.paths).toHaveProperty('/v0.1/risk/assess');
18
    await app.close();
19
  });
20
21
  it('isolates hosted dashboard and settings by authenticated operator', async () => {
22
    const calls: string[] = [];
23
    const repository = {
24
      dashboard: async (operatorId: string) => {
25
        calls.push(`dashboard:${operatorId}`);
26
        return {
27
          agents: [],
28
          projects: [],
29
          installations: [],
30
          setupRequests: [],
31
          publications: [],
32
          interactions: [],
33
          federatedInteractions: [],
34
          liveSessions: [],
35
          hostedThreads: [],
36
          events: [],
37
          conflicts: [],
38
          receipts: [],
39
          profiles: [],
40
          runtimes: [],
41
          accessTokens: [],
42
        };
43
      },
44
      getSettings: async (operatorId: string) => {
45
        calls.push(`settings:${operatorId}`);
46
        return {
47
          displayName: '',
48
          contributionEnabled: false,
49
          retentionDays: 30,
50
          evidenceSharing: 'ask' as const,
51
          rawConversationsStored: false as const,
52
        };
53
      },
54
      saveSettings: async (operatorId: string, value: any) => {
55
        calls.push(`save:${operatorId}`);
56
        return { ...value, rawConversationsStored: false as const };
57
      },
58
      upsert: async () => undefined,
59
      list: async () => [],
60
      publishAgent: async (_operatorId: string, card: any) => card,
61
      unpublishAgent: async () => true,
62
      getPublishedAgent: async () => undefined,
63
      searchPublishedAgents: async () => [],
64
      registerAgentRuntime: async (operatorId: string, agentId: string, endpoint: string) => {
65
        calls.push(`runtime:${operatorId}:${agentId}:${endpoint}`);
66
        return {
67
          agentId,
68
          endpoint,
69
          a2aEndpoint: endpoint,
70
          status: 'verified' as const,
71
          verifiedAt: new Date().toISOString(),
72
          verificationKey: 'public-key',
73
        };
74
      },
75
      disableAgentRuntime: async (operatorId: string, agentId: string) => {
76
        calls.push(`disable-runtime:${operatorId}:${agentId}`);
77
        return { agentId, status: 'disabled' as const };
78
      },
79
      deleteAgent: async (operatorId: string, agentId: string) => {
80
        calls.push(`delete-agent:${operatorId}:${agentId}`);
81
        return { agentId, deleted: true as const, historyRetained: true as const };
82
      },
83
      listAgentAccessTokens: async (operatorId: string, agentId?: string) => {
84
        calls.push(`list-tokens:${operatorId}:${agentId ?? '*'}`);
85
        return [];
86
      },
87
      issueAgentAccessToken: async (
88
        operatorId: string,
89
        agentId: string,
90
        value: { name: string; expiresInDays: number },
91
      ) => {
92
        calls.push(`issue-token:${operatorId}:${agentId}:${value.name}:${value.expiresInDays}`);
93
        return {
94
          tokenId: 'abcdefghijklmnop',
95
          token: 'oc_at_abcdefghijklmnop.abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
96
          agentId,
97
          name: value.name,
98
          scopes: ['mcp:access'],
99
          createdAt: '2026-01-01T00:00:00.000Z',
100
          expiresAt: '2027-01-01T00:00:00.000Z',
101
        };
102
      },
103
      revokeAgentAccessToken: async (operatorId: string, agentId: string, tokenId: string) => {
104
        calls.push(`revoke-token:${operatorId}:${agentId}:${tokenId}`);
105
        return { tokenId, agentId, revokedAt: '2026-01-02T00:00:00.000Z' };
106
      },
107
      receiveTemporaryMessage: async (
108
        token: string,
109
        agentId: string,
110
        requestKey: string,
111
        content: string,
112
      ) => {
113
        calls.push(`temporary:${token}:${agentId}:${requestKey}:${content}`);
114
        return {
115
          message: {
116
            messageId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
117
            threadId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
118
            interactionId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
119
            senderAgentId: 'agent-peer',
120
            recipientAgentId: agentId,
121
            contentType: 'text/plain' as const,
122
            content,
123
            contentHash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
124
            delivery: 'delivered' as const,
125
            createdAt: new Date().toISOString(),
126
          },
127
          deduplicated: false,
128
        };
129
      },
130
    };
131
    const app = buildApi(undefined, undefined, repository);
132
    await app.ready();
133
    expect((await app.inject({ method: 'GET', url: '/v0.1/dashboard' })).statusCode).toBe(401);
134
    expect(
135
      (
136
        await app.inject({
137
          method: 'GET',
138
          url: '/v0.1/dashboard',
139
          headers: { 'x-openclasp-operator': 'user-a' },
140
        })
141
      ).statusCode,
142
    ).toBe(200);
143
    expect(
144
      (
145
        await app.inject({
146
          method: 'GET',
147
          url: '/v0.1/settings',
148
          headers: { 'x-openclasp-operator': 'user-b' },
149
        })
150
      ).statusCode,
151
    ).toBe(200);
152
    expect(
153
      (
154
        await app.inject({
155
          method: 'PUT',
156
          url: '/v0.1/agents/agent-a/runtime',
157
          headers: { 'x-openclasp-operator': 'user-a' },
158
          payload: { endpoint: 'https://agent.example/openclasp' },
159
        })
160
      ).statusCode,
161
    ).toBe(200);
162
    expect(calls).toEqual([
163
      'dashboard:user-a',
164
      'settings:user-b',
165
      'runtime:user-a:agent-a:https://agent.example/openclasp',
166
    ]);
167
    expect(
168
      (
169
        await app.inject({
170
          method: 'DELETE',
171
          url: '/v0.1/agents/agent-a',
172
          headers: { 'x-openclasp-operator': 'user-a' },
173
        })
174
      ).json(),
175
    ).toMatchObject({ agentId: 'agent-a', deleted: true, historyRetained: true });
176
    expect(calls.at(-1)).toBe('delete-agent:user-a:agent-a');
177
    const issuedToken = await app.inject({
178
      method: 'POST',
179
      url: '/v0.1/agents/agent-a/access-tokens',
180
      headers: { 'x-openclasp-operator': 'user-a' },
181
      payload: { name: 'Botpress', expiresInDays: 365 },
182
    });
183
    expect(issuedToken.statusCode).toBe(200);
184
    expect(issuedToken.json()).toMatchObject({
185
      agentId: 'agent-a',
186
      name: 'Botpress',
187
      scopes: ['mcp:access'],
188
    });
189
    expect(calls.at(-1)).toBe('issue-token:user-a:agent-a:Botpress:365');
190
    expect(
191
      (
192
        await app.inject({
193
          method: 'DELETE',
194
          url: '/v0.1/agents/agent-a/access-tokens/abcdefghijklmnop',
195
          headers: { 'x-openclasp-operator': 'user-a' },
196
        })
197
      ).statusCode,
198
    ).toBe(200);
199
    expect(calls.at(-1)).toBe('revoke-token:user-a:agent-a:abcdefghijklmnop');
200
    expect(
201
      (
202
        await app.inject({
203
          method: 'POST',
204
          url: '/a2a/temporary/agent-a',
205
          payload: {
206
            jsonrpc: '2.0',
207
            id: 'request-1',
208
            method: 'message/send',
209
            params: { message: { parts: [{ kind: 'text', text: 'Hello engineer' }] } },
210
          },
211
        })
212
      ).statusCode,
213
    ).toBe(401);
214
    const temporaryDelivery = await app.inject({
215
      method: 'POST',
216
      url: '/a2a/temporary/agent-a',
217
      headers: { authorization: 'Bearer scoped-token' },
218
      payload: {
219
        jsonrpc: '2.0',
220
        id: 'request-1',
221
        method: 'message/send',
222
        params: { message: { parts: [{ kind: 'text', text: 'Hello engineer' }] } },
223
      },
224
    });
225
    expect(temporaryDelivery.statusCode).toBe(200);
226
    expect(temporaryDelivery.json()).toMatchObject({
227
      result: {
228
        task: { id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', state: 'submitted' },
229
        privacyMode: 'openclasp_hosted_temporary',
230
      },
231
    });
232
    expect(calls.at(-1)).toBe('temporary:scoped-token:agent-a:request-1:Hello engineer');
233
    await app.close();
234
  });
235
236
  it('publishes only an owned agent public card', async () => {
237
    const published: any[] = [];
238
    const repository = {
239
      dashboard: async () => ({}) as any,
240
      getSettings: async () => ({}) as any,
241
      saveSettings: async () => ({}) as any,
242
      upsert: async () => undefined,
243
      list: async () => [
244
        {
245
          kind: 'agent_profile' as const,
246
          recordId: 'agent-one',
247
          payload: {
248
            agentId: 'agent-one',
249
            projectId: 'secret-project',
250
            name: 'Research agent',
251
            description: 'Finds primary sources',
252
            framework: 'Codex',
253
            agentVersion: '1.0.0',
254
            a2aEndpoint: 'https://agent.example/a2a',
255
            capabilities: ['research'],
256
            limitations: ['no purchases'],
257
            identityMode: 'oauth_installation' as const,
258
            status: 'active' as const,
259
            createdAt: '2026-01-01T00:00:00.000Z',
260
            updatedAt: '2026-01-01T00:00:00.000Z',
261
          },
262
        },
263
      ],
264
      publishAgent: async (_operatorId: string, card: any) => {
265
        published.push(card);
266
        return card;
267
      },
268
      unpublishAgent: async () => true,
269
      getPublishedAgent: async () => published[0],
270
      searchPublishedAgents: async () => published,
271
    };
272
    const app = buildApi(undefined, undefined, repository);
273
    await app.ready();
274
    const response = await app.inject({
275
      method: 'POST',
276
      url: '/v0.1/agents/agent-one/publication',
277
      headers: { 'x-openclasp-operator': 'owner-one' },
278
      payload: { published: true },
279
    });
280
    expect(response.statusCode).toBe(200);
281
    expect(published[0]).toMatchObject({
282
      agentId: 'agent-one',
283
      capabilities: ['research'],
284
      assurance: 'oauth_authenticated',
285
    });
286
    expect(published[0]).not.toHaveProperty('projectId');
287
    expect(published[0]).not.toHaveProperty('operatorId');
288
    const publicCard = await app.inject({
289
      method: 'GET',
290
      url: '/agents/agent-one/card.json',
291
    });
292
    expect(publicCard.statusCode).toBe(200);
293
    expect(publicCard.json()).not.toHaveProperty('projectId');
294
    const a2aCard = await app.inject({
295
      method: 'GET',
296
      url: '/agents/agent-one/a2a-agent-card.json',
297
    });
298
    expect(a2aCard.statusCode).toBe(200);
299
    expect(a2aCard.json().supportedInterfaces[0]).toMatchObject({
300
      url: 'https://agent.example/a2a',
301
      protocolVersion: '1.0',
302
    });
303
    const automation = await app.inject({
304
      method: 'PUT',
305
      url: '/v0.1/agents/agent-one/automation',
306
      headers: { 'x-openclasp-operator': 'owner-one' },
307
      payload: {
308
        a2aEndpoint: 'https://agent.example/a2a',
309
        autoPublish: true,
310
        autoAcceptPolicy: 'safe_matching',
311
        autoAcceptTaskCategories: ['research'],
312
      },
313
    });
314
    expect(automation.statusCode).toBe(200);
315
    expect(automation.json()).toMatchObject({
316
      autoPublish: true,
317
      autoAcceptPolicy: 'safe_matching',
318
    });
319
    await app.close();
320
  });
321
322
  it('accepts only structured live-session events at the reporting endpoint', async () => {
323
    const events: any[] = [];
324
    const repository = {
325
      dashboard: async () => ({}) as any,
326
      getSettings: async () => ({}) as any,
327
      saveSettings: async () => ({}) as any,
328
      upsert: async () => undefined,
329
      list: async () => [],
330
      publishAgent: async (_operatorId: string, card: any) => card,
331
      unpublishAgent: async () => true,
332
      getPublishedAgent: async () => undefined,
333
      searchPublishedAgents: async () => [],
334
      recordLiveSessionEvent: async (token: string, value: any) => {
335
        events.push({ token, value });
336
        return {
337
          recorded: true,
338
          deduplicated: false,
339
          eventId: value.eventId,
340
          attestation: {
341
            algorithm: 'Ed25519' as const,
342
            keyId: 'openclasp:test',
343
            value: 'signature',
344
            digest: 'digest',
345
          },
346
        };
347
      },
348
    };
349
    const app = buildApi(undefined, undefined, repository);
350
    await app.ready();
351
    const interactionId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
352
    expect(
353
      (await app.inject({ method: 'POST', url: `/sessions/${interactionId}/events` })).statusCode,
354
    ).toBe(401);
355
    const response = await app.inject({
356
      method: 'POST',
357
      url: `/sessions/${interactionId}/events`,
358
      headers: { authorization: 'Bearer live-session-token' },
359
      payload: {
360
        eventId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
361
        interactionId,
362
        agentId: 'agent-a',
363
        sequence: 1,
364
        type: 'message_sent',
365
        occurredAt: new Date().toISOString(),
366
        messageHash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
367
        evidenceReferences: [],
368
        details: {},
369
      },
370
    });
371
    expect(response.statusCode).toBe(200);
372
    expect(events[0]).toMatchObject({
373
      token: 'live-session-token',
374
      value: { interactionId, agentId: 'agent-a', type: 'message_sent' },
375
    });
376
    const rawMessageAttempt = await app.inject({
377
      method: 'POST',
378
      url: `/sessions/${interactionId}/events`,
379
      headers: { authorization: 'Bearer live-session-token' },
380
      payload: {
381
        eventId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc',
382
        interactionId,
383
        agentId: 'agent-a',
384
        sequence: 2,
385
        type: 'message_sent',
386
        occurredAt: new Date().toISOString(),
387
        details: { message: 'raw conversation text' },
388
      },
389
    });
390
    expect(rawMessageAttempt.statusCode).toBe(400);
391
    expect(events).toHaveLength(1);
392
    await app.close();
393
  });
394
});