Skip to content

Commit 340ab97

Browse files
fix(primitives): enforce member access and assignment rules
1 parent 5c5887a commit 340ab97

49 files changed

Lines changed: 1149 additions & 235 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/server/src/MemberDirectory.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ export const make = Effect.gen(function* () {
2727
directory
2828
.getMany(companyId, ids)
2929
.pipe(Effect.mapError((cause) => new Runtime.SourceUnavailable({ cause }))),
30-
isCandidate: (companyId, id) =>
30+
candidates: (companyId, ids) =>
3131
directory
32-
.isCandidate(companyId, id)
32+
.candidates(companyId, ids)
3333
.pipe(Effect.mapError((cause) => new Runtime.SourceUnavailable({ cause }))),
3434
revision: (companyId) =>
3535
directory

‎apps/server/src/Members.test.ts‎

Lines changed: 255 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,74 @@ const layer = Layer.mergeAll(Companies.layer, Users.layer).pipe(
3838
Layer.provideMerge(server({ NODE_ENV: "test" }))
3939
);
4040

41+
const connect = Effect.fnUntraced(function* (
42+
document: { patchId: string; versionId: string; documentId: string },
43+
authenticated: Record<string, string>
44+
) {
45+
const response = yield* send(
46+
HttpClientRequest.get("/api/runtime/stream").pipe(
47+
HttpClientRequest.setUrlParams(document),
48+
HttpClientRequest.setHeaders(authenticated)
49+
)
50+
);
51+
assert.strictEqual(response.status, 200);
52+
const received = yield* Queue.unbounded<RuntimeStreamFrame>();
53+
yield* response.stream.pipe(
54+
Stream.decodeText,
55+
Stream.splitLines,
56+
Stream.filter((line) => line.startsWith("data: ")),
57+
Stream.map((line) => decodeFrame(line.slice(6))),
58+
Stream.runForEach((frame) => Queue.offer(received, frame)),
59+
Effect.forkScoped
60+
);
61+
const next = Effect.fnUntraced(function* (type: RuntimeStreamFrame["type"]) {
62+
while (true) {
63+
const frame = yield* Queue.take(received);
64+
if (frame.type === type) return frame;
65+
if (frame.type === "error") throw new Error(JSON.stringify(frame));
66+
}
67+
});
68+
const hello = yield* next("hello");
69+
if (hello.type !== "hello") throw new Error("Expected stream hello");
70+
return {
71+
next,
72+
generation: hello.generation,
73+
subscribe: (sequence: number, id: string, op: string) =>
74+
send(
75+
HttpClientRequest.post("/api/runtime/subscriptions").pipe(
76+
HttpClientRequest.setHeaders(authenticated),
77+
HttpClientRequest.bodyJsonUnsafe({
78+
...document,
79+
generation: hello.generation,
80+
sequence,
81+
type: "subscribe",
82+
subscription: { id, op, args: op === "tables.list" ? { table: "rows" } : {} }
83+
})
84+
)
85+
)
86+
};
87+
});
88+
89+
const call = (
90+
document: { patchId: string; versionId: string },
91+
authenticated: Record<string, string>,
92+
op: string,
93+
args: Record<string, unknown> = {}
94+
) =>
95+
send(
96+
HttpClientRequest.post("/api/runtime/call").pipe(
97+
HttpClientRequest.setHeaders(authenticated),
98+
HttpClientRequest.bodyJsonUnsafe({
99+
patchId: document.patchId,
100+
versionId: document.versionId,
101+
wire: WIRE_VERSION,
102+
principal: JSON.parse(authenticated["x-patchy-principal"]!),
103+
op,
104+
args
105+
})
106+
)
107+
).pipe(Effect.flatMap(answer));
108+
41109
it.layer(layer)("hosted member directory", (it) => {
42110
it.effect("delivers committed joins and deactivation to an open candidate subscription", () =>
43111
Effect.gen(function* () {
@@ -133,7 +201,7 @@ it.layer(layer)("hosted member directory", (it) => {
133201
}).pipe(Effect.scoped)
134202
);
135203

136-
it.effect("refuses directory access to a signed-out reader of a public tier 1 patch", () =>
204+
it.effect("authenticates public directory calls without exposing identity through me", () =>
137205
Effect.gen(function* () {
138206
const response = yield* publish(DEV_SEED.token, {
139207
html: "<!doctype html><html><head><title>Public members</title></head><body>Members</body></html>",
@@ -142,23 +210,196 @@ it.layer(layer)("hosted member directory", (it) => {
142210
});
143211
assert.strictEqual(response.status, 201);
144212
const published = decodePublished(yield* response.json);
145-
const result = yield* answer(
146-
yield* send(
147-
HttpClientRequest.post("/api/runtime/call").pipe(
148-
HttpClientRequest.setHeaders({ ...headers, "x-patchy-principal": "null" }),
149-
HttpClientRequest.bodyJsonUnsafe({
213+
const authenticated = {
214+
...headers,
215+
cookie: signedInCookies(signSession({ azp: headers.origin }))
216+
};
217+
const bootstrap = { ...authenticated, "x-patchy-principal": "null" };
218+
assert.deepStrictEqual(yield* call(published, bootstrap, "me"), {
219+
status: 200,
220+
body: { ok: true, value: null }
221+
});
222+
assert.deepStrictEqual(yield* call(published, bootstrap, "principal"), {
223+
status: 200,
224+
body: { ok: true, value: { userId: DEV_SEED.userId } }
225+
});
226+
const crossOrigin = yield* call(
227+
published,
228+
{ ...bootstrap, origin: "https://outside.example" },
229+
"principal"
230+
);
231+
assert.deepInclude(crossOrigin.body, { code: "access_denied" });
232+
const stale = yield* call(
233+
published,
234+
{
235+
...bootstrap,
236+
cookie: signedInCookies(signSession({ azp: headers.origin, iat: 1, nbf: 1, exp: 2 }))
237+
},
238+
"principal"
239+
);
240+
assert.deepInclude(stale.body, { code: "session_refresh_required" });
241+
for (const [op, args] of [
242+
["members.list", {}],
243+
["members.search", { text: DEV_SEED.email }],
244+
["members.get", { id: DEV_SEED.userId }],
245+
["members.getMany", { ids: [DEV_SEED.userId] }]
246+
] as const) {
247+
const result = yield* call(published, authenticated, op, args);
248+
assert.strictEqual(result.status, 200);
249+
assert.deepInclude(result.body, { ok: true });
250+
assert.include(JSON.stringify(result.body), DEV_SEED.userId);
251+
}
252+
const unbound = yield* call(published, bootstrap, "members.list");
253+
assert.deepInclude(unbound.body, { code: "principal_changed" });
254+
const switched = yield* call(
255+
published,
256+
{ ...authenticated, "x-patchy-principal": '{"userId":"another_viewer"}' },
257+
"members.list"
258+
);
259+
assert.deepInclude(switched.body, { code: "principal_changed" });
260+
for (const op of ["tables.list", "files.list", "postgres.query", "members.unknown"]) {
261+
const result = yield* call(published, authenticated, op);
262+
assert.strictEqual(result.status, 403);
263+
assert.deepInclude(result.body, { code: "not_available_on_public" });
264+
}
265+
})
266+
);
267+
268+
it.effect("refuses anonymous, foreign and deactivated public directory readers and streams", () =>
269+
Effect.gen(function* () {
270+
const companies = yield* Companies.Companies;
271+
const users = yield* Users.Users;
272+
const outsider = yield* companies.create({
273+
handle: "members-outsider",
274+
name: "Outsider",
275+
clerkUserId: "user_member_outsider",
276+
277+
userName: "Outsider"
278+
});
279+
const invite = yield* companies.createInvite({
280+
companyId: DEV_SEED.companyId,
281+
282+
invitedBy: DEV_SEED.userId
283+
});
284+
const inactive = yield* companies.consumeInvite({
285+
inviteId: invite.id,
286+
clerkUserId: "user_member_inactive",
287+
288+
name: "Inactive"
289+
});
290+
yield* users.deactivate({ companyId: DEV_SEED.companyId, userId: inactive.id });
291+
const response = yield* publish(DEV_SEED.token, {
292+
html: "<!doctype html><html><head><title>Public members</title></head><body>Members</body></html>",
293+
manifest,
294+
scope: "public"
295+
});
296+
const published = decodePublished(yield* response.json);
297+
for (const [userId, sub, email, code] of [
298+
[null, null, null, "session_expired"],
299+
[outsider.user.id, "user_member_outsider", "[email protected]", "access_denied"],
300+
[inactive.id, "user_member_inactive", "[email protected]", "access_denied"]
301+
] as const) {
302+
const authenticated = {
303+
...headers,
304+
"x-patchy-principal": JSON.stringify(userId === null ? null : { userId }),
305+
...(sub === null
306+
? {}
307+
: { cookie: signedInCookies(signSession({ azp: headers.origin, sub, email })) })
308+
};
309+
for (const op of ["principal", "members.list"]) {
310+
const result = yield* call(published, authenticated, op);
311+
assert.deepInclude(result.body, { ok: false, code });
312+
}
313+
const stream = yield* send(
314+
HttpClientRequest.get("/api/runtime/stream").pipe(
315+
HttpClientRequest.setUrlParams({
150316
patchId: published.patchId,
151317
versionId: published.versionId,
152-
wire: WIRE_VERSION,
153-
principal: null,
154-
op: "members.list",
155-
args: {}
156-
})
318+
documentId: "refused_member_document"
319+
}),
320+
HttpClientRequest.setHeaders(authenticated)
157321
)
322+
);
323+
assert.deepInclude(yield* stream.json, { ok: false, code });
324+
}
325+
})
326+
);
327+
328+
it.effect("reauthorizes public member subscriptions on reconnect and live deactivation", () =>
329+
Effect.gen(function* () {
330+
const companies = yield* Companies.Companies;
331+
const users = yield* Users.Users;
332+
const invite = yield* companies.createInvite({
333+
companyId: DEV_SEED.companyId,
334+
335+
invitedBy: DEV_SEED.userId
336+
});
337+
const viewer = yield* companies.consumeInvite({
338+
inviteId: invite.id,
339+
clerkUserId: "user_member_subscriber",
340+
341+
name: "Subscriber"
342+
});
343+
const authenticated = {
344+
...headers,
345+
"x-patchy-principal": JSON.stringify({ userId: viewer.id }),
346+
cookie: signedInCookies(
347+
signSession({
348+
azp: headers.origin,
349+
sub: "user_member_subscriber",
350+
351+
})
352+
)
353+
};
354+
const response = yield* publish(DEV_SEED.token, {
355+
html: "<!doctype html><html><head><title>Public members</title></head><body>Members</body></html>",
356+
manifest,
357+
scope: "public"
358+
});
359+
const published = decodePublished(yield* response.json);
360+
const document = {
361+
patchId: published.patchId,
362+
versionId: published.versionId,
363+
documentId: "public_member_document"
364+
};
365+
const initial = yield* connect(document, authenticated);
366+
assert.strictEqual((yield* initial.subscribe(1, "members", "members.list")).status, 200);
367+
const snapshot = yield* initial.next("snapshot");
368+
if (snapshot.type !== "snapshot") throw new Error("Expected members snapshot");
369+
assert.include(
370+
decodePage(snapshot.result).rows.map((member) => member.id),
371+
viewer.id
372+
);
373+
assert.strictEqual((yield* initial.subscribe(2, "table", "tables.list")).status, 200);
374+
const refused = yield* initial.next("error");
375+
if (refused.type !== "error") throw new Error("Expected public table refusal");
376+
assert.strictEqual(refused.id, "table");
377+
assert.deepInclude(refused.error, { ok: false, code: "not_available_on_public" });
378+
const reconnected = yield* connect(document, {
379+
...authenticated,
380+
"x-patchy-generation": initial.generation
381+
});
382+
assert.notStrictEqual(reconnected.generation, initial.generation);
383+
assert.strictEqual((yield* reconnected.subscribe(1, "members", "members.list")).status, 200);
384+
const resumed = yield* reconnected.next("snapshot");
385+
if (resumed.type !== "snapshot") throw new Error("Expected resumed snapshot");
386+
assert.include(
387+
decodePage(resumed.result).rows.map((member) => member.id),
388+
viewer.id
389+
);
390+
yield* users.deactivate({ companyId: DEV_SEED.companyId, userId: viewer.id });
391+
assert.deepStrictEqual(yield* reconnected.next("access_denied"), { type: "access_denied" });
392+
const denied = yield* send(
393+
HttpClientRequest.get("/api/runtime/stream").pipe(
394+
HttpClientRequest.setUrlParams(document),
395+
HttpClientRequest.setHeaders({
396+
...authenticated,
397+
"x-patchy-generation": reconnected.generation
398+
})
158399
)
159400
);
160-
assert.strictEqual(result.status, 403);
161-
assert.deepInclude(result.body, { ok: false, code: "not_available_on_public" });
162-
})
401+
assert.strictEqual(denied.status, 403);
402+
assert.deepInclude(yield* denied.json, { code: "access_denied" });
403+
}).pipe(Effect.scoped)
163404
);
164405
});

‎apps/server/src/Server.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,9 +136,9 @@ const services = Layer.mergeAll(
136136
RuntimeProduction.layer(handlers),
137137
RuntimeStream.layer.pipe(
138138
Layer.provide(Subscriptions.layer),
139-
Layer.provide([SubscriptionReads.layer, StreamAdmission.layer, StreamLimits.layer])
139+
Layer.provide([SubscriptionReads.layer, StreamLimits.layer])
140140
)
141-
);
141+
).pipe(Layer.provide(StreamAdmission.layer));
142142
if (yield* FleetInvocation.enabled)
143143
return runtime.pipe(
144144
Layer.provide(

0 commit comments

Comments
 (0)