Open History to see the last commit
1import { test, expect } from './fixtures'
2import type { APIRequestContext, APIResponse } from '@playwright/test'
3
4/**
5 * Access on a `membersOnly()` host: the owner shares a thread with one
6 * member. A user of the same tenant who is not a member is refused (403),
7 * and a user of another tenant does not find the thread (404). The
8 * `x-harness-access: members` header picks that host in the route.
9 */
10
11const BASE = '/api/harness-protocol'
12const ANSWER = 'Hello over the harness protocol.'
13const FORBIDDEN = { status: 403, body: { error: 'forbidden' } }
14const NOT_FOUND = { status: 404, body: { error: 'not found' } }
15
16/** The text of the answer in a POST run stream. */
17const answerOf = async (response: APIResponse) =>
18 (await response.text())
19 .split('\n')
20 .filter((line) => line.startsWith('data: '))
21 .map((line) => JSON.parse(line.slice('data: '.length)))
22 .filter((event) => event.type === 'TEXT_MESSAGE_CONTENT')
23 .map((event) => event.delta)
24 .join('')
25
26/** The status and the JSON body of a refused request. */
27const refusalOf = async (response: APIResponse) => ({
28 status: response.status(),
29 body: await response.json(),
30})
31
32/**
33 * Open the session stream of a thread, read its first frame after the
34 * `harness.hello`, and close the stream. `: ping` comments have no `data:`
35 * line, so they are skipped. A refused request answers with JSON, not with
36 * a stream.
37 */
38async function firstEvent(url: string, headers: Record<string, string>) {
39 const response = await fetch(url, { headers })
40 if (!response.ok || !response.body) {
41 return { status: response.status, body: await response.json() }
42 }
43 const reader = response.body.pipeThrough(new TextDecoderStream()).getReader()
44 let buffer = ''
45 let body: { type?: string } | null = null
46 while (body === null) {
47 const read = await reader.read()
48 if (read.done) break
49 buffer += read.value
50 const blocks = buffer.split('\n\n')
51 buffer = blocks.pop() ?? ''
52 for (const block of blocks) {
53 const data = block.split('\n').find((line) => line.startsWith('data: '))
54 if (!data) continue
55 const frame: { type?: string } = JSON.parse(data.slice('data: '.length))
56 if (frame.type === 'harness.hello') continue
57 body = frame
58 break
59 }
60 }
61 await reader.cancel()
62 return { status: response.status, body }
63}
64
65/** One user of the `membersOnly()` host, by the token of the route. */
66function asUser(
67 request: APIRequestContext,
68 {
69 testId,
70 aimockPort,
71 baseURL,
72 }: { testId: string; aimockPort: number; baseURL: string | undefined },
73 token: string,
74) {
75 const headers = {
76 authorization: `Bearer ${token}`,
77 'x-test-id': testId,
78 'x-aimock-port': String(aimockPort),
79 'x-harness-access': 'members',
80 }
81 const json = { ...headers, 'content-type': 'application/json' }
82 return {
83 /** Send the hello prompt of the protocol fixture as the run `runId`. */
84 send: (threadId: string, runId: string) =>
85 request.post(`${BASE}/run`, {
86 headers: json,
87 data: {
88 threadId,
89 runId,
90 messages: [
91 { id: 'u1', role: 'user', content: '[harness-protocol] hello' },
92 ],
93 tools: [],
94 context: [],
95 state: {},
96 forwardedProps: {},
97 },
98 }),
99 sessions: (body: object) =>
100 request.post(`${BASE}/sessions`, { headers: json, data: body }),
101 events: (threadId: string) =>
102 firstEvent(
103 `${baseURL}${BASE}/events?threadId=${threadId}&from=0`,
104 headers,
105 ),
106 /** What a `ChatClient` with `persistence` loads for the thread. */
107 hydrate: (threadId: string) =>
108 request.get(`${BASE}/run?threadId=${threadId}`, { headers }),
109 }
110}
111
112test.describe('harness access', () => {
113 test('a shared thread serves its two members, refuses a third user, and stays hidden from another tenant', async ({
114 request,
115 baseURL,
116 testId,
117 aimockPort,
118 }) => {
119 const user = (token: string) =>
120 asUser(request, { testId, aimockPort, baseURL }, token)
121 const owner = user('e2e-token')
122 const bob = user('e2e-token-bob')
123 const carol = user('e2e-token-carol')
124 const mallory = user('e2e-token-mallory')
125 const threadId = `access-${testId}`
126
127 // 1. The owner starts the thread.
128 expect(
129 await answerOf(await owner.send(threadId, `access-owner-${testId}`)),
130 ).toBe(ANSWER)
131
132 // 2. The owner shares the thread with bob.
133 const shared = await owner.sessions({
134 op: 'share',
135 threadId,
136 userId: 'bob',
137 role: 'member',
138 })
139 expect((await shared.json()).members).toEqual([
140 { userId: 'e2e', role: 'owner' },
141 { userId: 'bob', role: 'member' },
142 ])
143
144 // 3. Bob reads the session stream and sends a prompt.
145 expect(await bob.events(threadId)).toMatchObject({
146 status: 200,
147 body: { type: 'harness.event' },
148 })
149 expect(
150 await answerOf(await bob.send(threadId, `access-bob-${testId}`)),
151 ).toBe(ANSWER)
152
153 // 4. Carol is in the same tenant, but she is not a member.
154 expect(await carol.events(threadId)).toEqual(FORBIDDEN)
155 expect(
156 await refusalOf(await carol.send(threadId, `access-carol-${testId}`)),
157 ).toEqual(FORBIDDEN)
158
159 // 5. Mallory is in another tenant, where this thread does not exist.
160 expect(await mallory.events(threadId)).toEqual(NOT_FOUND)
161 expect(await (await mallory.hydrate(threadId)).json()).toEqual({
162 messages: [],
163 activeRun: null,
164 interrupts: null,
165 })
166
167 // 6. The owner removes bob, so the next requests of bob are refused.
168 const unshared = await owner.sessions({
169 op: 'unshare',
170 threadId,
171 userId: 'bob',
172 })
173 expect((await unshared.json()).members).toEqual([
174 { userId: 'e2e', role: 'owner' },
175 ])
176 expect(await bob.events(threadId)).toEqual(FORBIDDEN)
177 expect(
178 await refusalOf(await bob.send(threadId, `access-bob-again-${testId}`)),
179 ).toEqual(FORBIDDEN)
180 })
181})