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

Viewing files at commit 00864c3cb723Commit detailsView latest

tests/api.test.ts 469 lines · 15.9 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
      touchAgentPresence: async (operatorId: string, agentId: string) => {
76
        calls.push(`heartbeat:${operatorId}:${agentId}`);
77
        return {
78
          status: 'online' as const,
79
          checkedAt: '2026-01-01T00:00:00.000Z',
80
        };
81
      },
82
      disableAgentRuntime: async (operatorId: string, agentId: string) => {
83
        calls.push(`disable-runtime:${operatorId}:${agentId}`);
84
        return { agentId, status: 'disabled' as const };
85
      },
86
      deleteAgent: async (operatorId: string, agentId: string) => {
87
        calls.push(`delete-agent:${operatorId}:${agentId}`);
88
        return { agentId, deleted: true as const, historyRetained: true as const };
89
      },
90
      listAgentAccessTokens: async (operatorId: string, agentId?: string) => {
91
        calls.push(`list-tokens:${operatorId}:${agentId ?? '*'}`);
92
        return [];
93
      },
94
      issueAgentAccessToken: async (
95
        operatorId: string,
96
        agentId: string,
97
        value: { name: string; expiresInDays: number },
98
      ) => {
99
        calls.push(`issue-token:${operatorId}:${agentId}:${value.name}:${value.expiresInDays}`);
100
        return {
101
          tokenId: 'abcdefghijklmnop',
102
          token: 'oc_at_abcdefghijklmnop.abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG',
103
          agentId,
104
          name: value.name,
105
          scopes: ['mcp:access', 'runtime:connect'],
106
          createdAt: '2026-01-01T00:00:00.000Z',
107
          expiresAt: '2027-01-01T00:00:00.000Z',
108
        };
109
      },
110
      revokeAgentAccessToken: async (operatorId: string, agentId: string, tokenId: string) => {
111
        calls.push(`revoke-token:${operatorId}:${agentId}:${tokenId}`);
112
        return { tokenId, agentId, revokedAt: '2026-01-02T00:00:00.000Z' };
113
      },
114
      receiveTemporaryMessage: async (
115
        token: string,
116
        agentId: string,
117
        requestKey: string,
118
        content: string,
119
      ) => {
120
        calls.push(`temporary:${token}:${agentId}:${requestKey}:${content}`);
121
        return {
122
          message: {
123
            messageId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
124
            threadId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
125
            interactionId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
126
            senderAgentId: 'agent-peer',
127
            recipientAgentId: agentId,
128
            contentType: 'text/plain' as const,
129
            content,
130
            contentHash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
131
            delivery: 'delivered' as const,
132
            createdAt: new Date().toISOString(),
133
          },
134
          deduplicated: false,
135
        };
136
      },
137
    };
138
    const app = buildApi(undefined, undefined, repository);
139
    await app.ready();
140
    expect((await app.inject({ method: 'GET', url: '/v0.1/dashboard' })).statusCode).toBe(401);
141
    expect(
142
      (
143
        await app.inject({
144
          method: 'GET',
145
          url: '/v0.1/dashboard',
146
          headers: { 'x-openclasp-operator': 'user-a' },
147
        })
148
      ).statusCode,
149
    ).toBe(200);
150
    expect(
151
      (
152
        await app.inject({
153
          method: 'GET',
154
          url: '/v0.1/settings',
155
          headers: { 'x-openclasp-operator': 'user-b' },
156
        })
157
      ).statusCode,
158
    ).toBe(200);
159
    expect(
160
      (
161
        await app.inject({
162
          method: 'PUT',
163
          url: '/v0.1/agents/agent-a/runtime',
164
          headers: { 'x-openclasp-operator': 'user-a' },
165
          payload: { endpoint: 'https://agent.example/openclasp' },
166
        })
167
      ).statusCode,
168
    ).toBe(200);
169
    expect(calls).toEqual([
170
      'dashboard:user-a',
171
      'settings:user-b',
172
      'runtime:user-a:agent-a:https://agent.example/openclasp',
173
    ]);
174
    expect(
175
      (
176
        await app.inject({
177
          method: 'GET',
178
          url: '/v0.1/runtime/bootstrap',
179
          headers: {
180
            'x-openclasp-operator': 'user-a',
181
            'x-openclasp-bound-agent': 'agent-a',
182
            host: 'openclasp.example',
183
            'x-forwarded-proto': 'https',
184
          },
185
        })
186
      ).json(),
187
    ).toMatchObject({
188
      agentId: 'agent-a',
189
      openClaspUrl: 'https://openclasp.example',
190
      protocol: 'A2A/1.0',
191
    });
192
    expect(
193
      (
194
        await app.inject({
195
          method: 'PUT',
196
          url: '/v0.1/runtime',
197
          headers: {
198
            'x-openclasp-operator': 'user-a',
199
            'x-openclasp-bound-agent': 'agent-a',
200
          },
201
          payload: { endpoint: 'https://runtime.example/a2a' },
202
        })
203
      ).statusCode,
204
    ).toBe(200);
205
    expect(calls.at(-1)).toBe('runtime:user-a:agent-a:https://runtime.example/a2a');
206
    expect(
207
      (
208
        await app.inject({
209
          method: 'POST',
210
          url: '/v0.1/runtime/heartbeat',
211
          headers: {
212
            'x-openclasp-operator': 'user-a',
213
            'x-openclasp-bound-agent': 'agent-a',
214
          },
215
        })
216
      ).statusCode,
217
    ).toBe(200);
218
    expect(calls.at(-1)).toBe('heartbeat:user-a:agent-a');
219
    expect(
220
      (
221
        await app.inject({
222
          method: 'DELETE',
223
          url: '/v0.1/agents/agent-a',
224
          headers: { 'x-openclasp-operator': 'user-a' },
225
        })
226
      ).json(),
227
    ).toMatchObject({ agentId: 'agent-a', deleted: true, historyRetained: true });
228
    expect(calls.at(-1)).toBe('delete-agent:user-a:agent-a');
229
    const issuedToken = await app.inject({
230
      method: 'POST',
231
      url: '/v0.1/agents/agent-a/access-tokens',
232
      headers: { 'x-openclasp-operator': 'user-a' },
233
      payload: { name: 'Botpress', expiresInDays: 365 },
234
    });
235
    expect(issuedToken.statusCode).toBe(200);
236
    expect(issuedToken.json()).toMatchObject({
237
      agentId: 'agent-a',
238
      name: 'Botpress',
239
      scopes: ['mcp:access', 'runtime:connect'],
240
    });
241
    expect(calls.at(-1)).toBe('issue-token:user-a:agent-a:Botpress:365');
242
    expect(
243
      (
244
        await app.inject({
245
          method: 'DELETE',
246
          url: '/v0.1/agents/agent-a/access-tokens/abcdefghijklmnop',
247
          headers: { 'x-openclasp-operator': 'user-a' },
248
        })
249
      ).statusCode,
250
    ).toBe(200);
251
    expect(calls.at(-1)).toBe('revoke-token:user-a:agent-a:abcdefghijklmnop');
252
    const providerConnection = await app.inject({
253
      method: 'POST',
254
      url: '/v0.1/provider-connections',
255
      headers: { 'x-openclasp-operator': 'user-a' },
256
      payload: {
257
        provider: 'botpress',
258
        agentName: 'Recruiting agent',
259
        projectName: 'Recruiting',
260
        capabilities: ['candidate matching'],
261
        limitations: ['no final hiring decisions'],
262
        expiresInDays: 365,
263
      },
264
    });
265
    expect(providerConnection.statusCode).toBe(200);
266
    expect(providerConnection.json()).toMatchObject({
267
      agent: {
268
        name: 'Recruiting agent',
269
        framework: 'Botpress',
270
        identityMode: 'owner_managed',
271
      },
272
      accessToken: { name: 'Botpress', scopes: ['mcp:access', 'runtime:connect'] },
273
    });
274
    expect(calls.at(-1)).toMatch(/^issue-token:user-a:agent_.*:Botpress:365$/);
275
    expect(
276
      (
277
        await app.inject({
278
          method: 'POST',
279
          url: '/a2a/temporary/agent-a',
280
          payload: {
281
            jsonrpc: '2.0',
282
            id: 'request-1',
283
            method: 'message/send',
284
            params: { message: { parts: [{ kind: 'text', text: 'Hello engineer' }] } },
285
          },
286
        })
287
      ).statusCode,
288
    ).toBe(401);
289
    const temporaryDelivery = await app.inject({
290
      method: 'POST',
291
      url: '/a2a/temporary/agent-a',
292
      headers: { authorization: 'Bearer scoped-token' },
293
      payload: {
294
        jsonrpc: '2.0',
295
        id: 'request-1',
296
        method: 'message/send',
297
        params: { message: { parts: [{ kind: 'text', text: 'Hello engineer' }] } },
298
      },
299
    });
300
    expect(temporaryDelivery.statusCode).toBe(200);
301
    expect(temporaryDelivery.json()).toMatchObject({
302
      result: {
303
        task: { id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', state: 'submitted' },
304
        privacyMode: 'openclasp_hosted_temporary',
305
      },
306
    });
307
    expect(calls.at(-1)).toBe('temporary:scoped-token:agent-a:request-1:Hello engineer');
308
    await app.close();
309
  });
310
311
  it('publishes only an owned agent public card', async () => {
312
    const published: any[] = [];
313
    const repository = {
314
      dashboard: async () => ({}) as any,
315
      getSettings: async () => ({}) as any,
316
      saveSettings: async () => ({}) as any,
317
      upsert: async () => undefined,
318
      list: async () => [
319
        {
320
          kind: 'agent_profile' as const,
321
          recordId: 'agent-one',
322
          payload: {
323
            agentId: 'agent-one',
324
            projectId: 'secret-project',
325
            name: 'Research agent',
326
            description: 'Finds primary sources',
327
            framework: 'Codex',
328
            agentVersion: '1.0.0',
329
            a2aEndpoint: 'https://agent.example/a2a',
330
            capabilities: ['research'],
331
            limitations: ['no purchases'],
332
            identityMode: 'oauth_installation' as const,
333
            status: 'active' as const,
334
            createdAt: '2026-01-01T00:00:00.000Z',
335
            updatedAt: '2026-01-01T00:00:00.000Z',
336
          },
337
        },
338
      ],
339
      publishAgent: async (_operatorId: string, card: any) => {
340
        published.push(card);
341
        return card;
342
      },
343
      unpublishAgent: async () => true,
344
      getPublishedAgent: async () => published[0],
345
      searchPublishedAgents: async () => published,
346
    };
347
    const app = buildApi(undefined, undefined, repository);
348
    await app.ready();
349
    const response = await app.inject({
350
      method: 'POST',
351
      url: '/v0.1/agents/agent-one/publication',
352
      headers: { 'x-openclasp-operator': 'owner-one' },
353
      payload: { published: true },
354
    });
355
    expect(response.statusCode).toBe(200);
356
    expect(published[0]).toMatchObject({
357
      agentId: 'agent-one',
358
      capabilities: ['research'],
359
      assurance: 'oauth_authenticated',
360
    });
361
    expect(published[0]).not.toHaveProperty('projectId');
362
    expect(published[0]).not.toHaveProperty('operatorId');
363
    const publicCard = await app.inject({
364
      method: 'GET',
365
      url: '/agents/agent-one/card.json',
366
    });
367
    expect(publicCard.statusCode).toBe(200);
368
    expect(publicCard.json()).not.toHaveProperty('projectId');
369
    const a2aCard = await app.inject({
370
      method: 'GET',
371
      url: '/agents/agent-one/a2a-agent-card.json',
372
    });
373
    expect(a2aCard.statusCode).toBe(200);
374
    expect(a2aCard.json().supportedInterfaces[0]).toMatchObject({
375
      url: 'https://agent.example/a2a',
376
      protocolVersion: '1.0',
377
    });
378
    const automation = await app.inject({
379
      method: 'PUT',
380
      url: '/v0.1/agents/agent-one/automation',
381
      headers: { 'x-openclasp-operator': 'owner-one' },
382
      payload: {
383
        a2aEndpoint: 'https://agent.example/a2a',
384
        autoPublish: true,
385
        autoAcceptPolicy: 'safe_matching',
386
        autoAcceptTaskCategories: ['research'],
387
      },
388
    });
389
    expect(automation.statusCode).toBe(200);
390
    expect(automation.json()).toMatchObject({
391
      autoPublish: true,
392
      autoAcceptPolicy: 'safe_matching',
393
    });
394
    await app.close();
395
  });
396
397
  it('accepts only structured live-session events at the reporting endpoint', async () => {
398
    const events: any[] = [];
399
    const repository = {
400
      dashboard: async () => ({}) as any,
401
      getSettings: async () => ({}) as any,
402
      saveSettings: async () => ({}) as any,
403
      upsert: async () => undefined,
404
      list: async () => [],
405
      publishAgent: async (_operatorId: string, card: any) => card,
406
      unpublishAgent: async () => true,
407
      getPublishedAgent: async () => undefined,
408
      searchPublishedAgents: async () => [],
409
      recordLiveSessionEvent: async (token: string, value: any) => {
410
        events.push({ token, value });
411
        return {
412
          recorded: true,
413
          deduplicated: false,
414
          eventId: value.eventId,
415
          attestation: {
416
            algorithm: 'Ed25519' as const,
417
            keyId: 'openclasp:test',
418
            value: 'signature',
419
            digest: 'digest',
420
          },
421
        };
422
      },
423
    };
424
    const app = buildApi(undefined, undefined, repository);
425
    await app.ready();
426
    const interactionId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
427
    expect(
428
      (await app.inject({ method: 'POST', url: `/sessions/${interactionId}/events` })).statusCode,
429
    ).toBe(401);
430
    const response = await app.inject({
431
      method: 'POST',
432
      url: `/sessions/${interactionId}/events`,
433
      headers: { authorization: 'Bearer live-session-token' },
434
      payload: {
435
        eventId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
436
        interactionId,
437
        agentId: 'agent-a',
438
        sequence: 1,
439
        type: 'message_sent',
440
        occurredAt: new Date().toISOString(),
441
        messageHash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
442
        evidenceReferences: [],
443
        details: {},
444
      },
445
    });
446
    expect(response.statusCode).toBe(200);
447
    expect(events[0]).toMatchObject({
448
      token: 'live-session-token',
449
      value: { interactionId, agentId: 'agent-a', type: 'message_sent' },
450
    });
451
    const rawMessageAttempt = await app.inject({
452
      method: 'POST',
453
      url: `/sessions/${interactionId}/events`,
454
      headers: { authorization: 'Bearer live-session-token' },
455
      payload: {
456
        eventId: 'cccccccc-cccc-4ccc-8ccc-cccccccccccc',
457
        interactionId,
458
        agentId: 'agent-a',
459
        sequence: 2,
460
        type: 'message_sent',
461
        occurredAt: new Date().toISOString(),
462
        details: { message: 'raw conversation text' },
463
      },
464
    });
465
    expect(rawMessageAttempt.statusCode).toBe(400);
466
    expect(events).toHaveLength(1);
467
    await app.close();
468
  });
469
});