From 5d27c2aa0e815595ca03b149698cc69c087c5c5c Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Tue, 3 Nov 2026 15:11:11 -0700 Subject: [PATCH] test(events): cover user-scope publish, inline create and listing --- .../events/userHandlers.integration.test.ts | 1133 +++++++++++++++++ .../events/workers.integration.test.ts | 234 +++- 2 files changed, 1366 insertions(+), 1 deletion(-) create mode 100644 src/backend/services/events/userHandlers.integration.test.ts diff --git a/src/backend/services/events/userHandlers.integration.test.ts b/src/backend/services/events/userHandlers.integration.test.ts new file mode 100644 index 000000000..f84e2355d --- /dev/null +++ b/src/backend/services/events/userHandlers.integration.test.ts @@ -0,0 +1,1133 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +/** + * User-scope handlers on the publish side: who may publish into a user's own + * scope, the inline create that names a handler by its source, what stays off + * the primary and the broadcast bus, isolation from app scope and from other + * users, and the caps and rent unit a scope counts as. + */ + +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + it, + onTestFinished, + vi, +} from 'vitest'; +import { v4 as uuidv4 } from 'uuid'; +import * as rateLimit from '../../core/http/middleware/rateLimit.js'; +import { HttpError } from '../../core/http/HttpError.js'; +import { + EVENTS_HANDLER_PUBLISH_LIMIT, + EVENTS_HANDLER_SOURCE_MAX_BYTES, + EVENTS_USER_HANDLERS_PER_SCOPE, + EVENTS_USER_SCOPE_SOURCE_MAX_BYTES, +} from '../../controllers/events/limits.js'; +import { + appHandlerScope, + hashContent, + type HandlerScope, +} from '../../stores/events/EventHandlerStore.js'; +import { setupPuterTestEnv, type PuterTestEnv } from '../../testUtil.js'; +import type { IConfig } from '../../types.js'; +import { + DEFAULT_FREE_SUBSCRIPTION, + DEFAULT_TEMP_SUBSCRIPTION, +} from '../metering/consts.js'; +import { EVENTS_BACKGROUND_PERMISSION } from './authorization.js'; +import type { DurableSubscriptionView } from './EventsService.js'; + +const BOOT_TIMEOUT_MS = 120_000; + +const SOURCE = + 'async ({ event, ctx }) => { await fetch(ctx.url, { method: "POST" }); }'; +const OTHER_SOURCE = + 'async ({ event, ctx }) => { console.log(event.path, ctx.url); }'; + +let env: PuterTestEnv; +let userId: number; +let otherUserId: number; +let anchor: string; +let otherAnchor: string; +let appUid: string; +/** App sessions of the two users in the app `user` owns. */ +let userToken: string; +let otherToken: string; +let foreignAppUid: string; +let foreignAppToken: string; + +const events = () => env.server.services.events; +const store = () => env.server.stores.eventHandler; +const userScope = (holder: number, uid = appUid): HandlerScope => ({ + appUid: uid, + holder, +}); + +interface ApiResponse { + status: number; + body: Record; +} + +const call = async ( + method: 'GET' | 'POST', + path: string, + token: string, + body?: object, +): Promise => { + const response = await fetch(new URL(path, env.apiOrigin), { + method, + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${token}`, + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + return { + status: response.status, + body: (await response.json()) as Record, + }; +}; + +const publishUser = (token: string, name: string, source: string, extra = {}) => + call('POST', '/events/handlers/publish', token, { + scope: 'user', + name, + source, + ...extra, + }); +const publishApp = (token: string, name: string, source: string, extra = {}) => + call('POST', '/events/handlers/publish', token, { name, source, ...extra }); +const removeUser = (token: string, name: string) => + call('POST', '/events/handlers/remove', token, { scope: 'user', name }); +const listUser = (token: string) => + call('GET', '/events/handlers/list?scope=user', token); +const subscribe = (token: string, body: object) => + call('POST', '/events/subscribe', token, body); + +const makeApp = async ( + ownerUserId: number, + grants: Array<{ token: string; path: string }>, +): Promise<{ uid: string; tokens: string[] }> => { + const uid = `app-${uuidv4()}`; + await env.server.clients.db.write( + 'INSERT INTO `apps` (`uid`, `name`, `title`, `index_url`, `owner_user_id`) VALUES (?, ?, ?, ?, ?)', + [uid, uid, uid, `https://${uid}.example/`, ownerUserId], + ); + const tokens: string[] = []; + for (const grant of grants) { + const entry = await env.server.stores.fsEntry.getEntryByPath( + grant.path, + ); + const { actor } = await env.server.services.auth.authenticate( + grant.token, + ); + await env.server.services.permission.grantUserAppPermission( + actor!, + uid, + `fs:${entry!.uid}:list`, + ); + await env.server.services.permission.grantUserAppPermission( + actor!, + uid, + EVENTS_BACKGROUND_PERMISSION, + ); + tokens.push( + await env.server.services.auth.getUserAppToken(actor!, uid), + ); + } + return { uid, tokens }; +}; + +const actorOf = async (token: string) => + (await env.server.services.auth.authenticate(token)).actor!; + +const scopedTokenFrom = async (token: string): Promise => { + const actor = await actorOf(token); + const entry = await env.server.stores.fsEntry.getEntryByPath(anchor); + return env.server.services.auth.createAccessToken( + actor, + [[`fs:${entry!.uid}:list`]], + { label: 'user-handlers-scope' }, + ); +}; + +/** The plan and rented-unit counts a cap test runs against. */ +const holding = ( + plan: string, + held: { workers?: number; scopes?: number; owned?: number }, +) => { + vi.spyOn( + env.server.services.metering, + 'getActorSubscription', + ).mockResolvedValue({ id: plan } as never); + vi.spyOn( + env.server.stores.subdomain, + 'countByUserIdAndPrefix', + ).mockResolvedValue(held.workers ?? 0); + vi.spyOn(store(), 'countUserScopesWithHandlersForUser').mockResolvedValue( + held.scopes ?? 0, + ); + vi.spyOn(store(), 'countAppsWithHandlersForOwner').mockResolvedValue( + held.owned ?? 0, + ); +}; + +let publishSpends: number; +let creates: Array<{ + appUid: string; + scope: string; + userId: number | undefined; +}>; +let destroys: Array<{ + appUid: string; + scope: string; + userId: number | undefined; +}>; + +beforeAll(async () => { + env = await setupPuterTestEnv({ + events: { enabled: true, userHandlers: true }, + unlimitedMetering: true, + } as IConfig); + + userId = (await env.server.stores.user.getByUsername( + env.users.user.username, + ))!.id; + otherUserId = (await env.server.stores.user.getByUsername( + env.users.other.username, + ))!.id; + + anchor = `/${env.users.user.username}/userhandlers`; + otherAnchor = `/${env.users.other.username}/userhandlers`; + await env.server.services.fs.mkdir(userId, { + path: anchor, + createMissingParents: true, + }); + await env.server.services.fs.mkdir(otherUserId, { + path: otherAnchor, + createMissingParents: true, + }); + + const owned = await makeApp(userId, [ + { token: env.users.user.token, path: anchor }, + { token: env.users.other.token, path: otherAnchor }, + ]); + appUid = owned.uid; + [userToken, otherToken] = owned.tokens; + + const foreign = await makeApp(otherUserId, [ + { token: env.users.user.token, path: anchor }, + ]); + foreignAppUid = foreign.uid; + [foreignAppToken] = foreign.tokens; + + env.server.clients.event.on('events.worker.create', (_key, event) => { + creates.push({ + appUid: event.appUid, + scope: event.scope, + userId: event.actor.user.id, + }); + }); + env.server.clients.event.on('events.worker.destroy', (_key, event) => { + destroys.push({ + appUid: event.appUid, + scope: event.scope, + userId: event.actor.user.id, + }); + }); +}, BOOT_TIMEOUT_MS); + +afterAll(async () => { + await env?.shutdown(); +}); + +beforeEach(async () => { + // Through the store, which also drops the cached sets a raw delete leaves. + for (const uid of [appUid, foreignAppUid]) await store().deleteForApp(uid); + await env.server.clients.db.write('DELETE FROM `event_subscriptions`', []); + await env.server.stores.eventSubscription.rebuildDurable(userId, []); + await env.server.stores.eventSubscription.rebuildDurable(otherUserId, []); + creates = []; + destroys = []; + publishSpends = 0; + // The publish window is 60 a minute per user and this file publishes far + // more; what it counts is how often a call spent from it. + vi.spyOn(rateLimit, 'checkRateLimit').mockImplementation(async (key) => { + if (String(key).startsWith(EVENTS_HANDLER_PUBLISH_LIMIT.scope)) + publishSpends += 1; + return true; + }); + (events() as unknown as { config: IConfig }).config.events!.userHandlers = + true; +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('who may publish into a user scope', () => { + it('lets an app session publish into its own user scope', async () => { + const published = await publishUser(userToken, 'daily', SOURCE); + + expect(published.status).toBe(200); + expect(published.body).toMatchObject({ + name: 'daily', + hash: hashContent(SOURCE), + outcome: 'created', + }); + expect( + await store().getByName(userScope(userId), 'daily'), + ).toMatchObject({ sourceHash: hashContent(SOURCE) }); + // Nothing reaches the app's own set. + expect(await store().listForApp(appHandlerScope(appUid))).toEqual([]); + }); + + it('lets a user who does not own the app publish into their scope', async () => { + const published = await publishUser(otherToken, 'daily', SOURCE); + expect(published.status).toBe(200); + expect( + await store().getByName(userScope(otherUserId), 'daily'), + ).not.toBe(null); + }); + + it('refuses a scoped access token, including one the app issued', async () => { + for (const token of [ + await scopedTokenFrom(env.users.user.token), + await scopedTokenFrom(userToken), + ]) { + const refused = await publishUser(token, 'daily', SOURCE, { + appUid, + }); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe('events_handler_forbidden'); + } + }); + + it('refuses a session with no app and a request naming no app of its own', async () => { + const refused = await publishUser( + env.users.user.token, + 'daily', + SOURCE, + { + appUid, + }, + ); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe('events_handler_forbidden'); + }); + + it('refuses a request naming another app than the caller`s', async () => { + const refused = await publishUser(userToken, 'daily', SOURCE, { + appUid: foreignAppUid, + }); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe('events_handler_forbidden'); + }); + + it('refuses a guest', async () => { + vi.spyOn( + env.server.services.metering, + 'getActorSubscription', + ).mockResolvedValue({ id: DEFAULT_TEMP_SUBSCRIPTION } as never); + const refused = await publishUser(userToken, 'daily', SOURCE); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe('events_handler_forbidden'); + }); + + it('refuses a session with an unresolved app', async () => { + const actor = { ...(await actorOf(userToken)) }; + delete (actor as { effectiveApp?: unknown }).effectiveApp; + await expect( + events().publishHandler(actor, { + scope: 'user', + name: 'daily', + source: SOURCE, + }), + ).rejects.toMatchObject({ legacyCode: 'events_handler_forbidden' }); + }); + + it('still requires owner equality for app scope', async () => { + const refused = await publishApp(otherToken, 'daily', SOURCE); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe('events_handler_forbidden'); + expect((await publishApp(userToken, 'daily', SOURCE)).status).toBe(200); + }); + + it('rejects a scope that is neither app nor user', async () => { + const refused = await call( + 'POST', + '/events/handlers/publish', + userToken, + { + scope: 'team', + name: 'daily', + source: SOURCE, + }, + ); + expect(refused.status).toBe(400); + }); + + it('reserves `@` names for what the server mints from a source', async () => { + const refused = await publishUser( + userToken, + `@${'a'.repeat(64)}`, + SOURCE, + ); + expect(refused.status).toBe(400); + expect(refused.body.code).toBe('events_handler_name_invalid'); + + const matching = await publishUser( + userToken, + `@${hashContent(SOURCE)}`, + SOURCE, + ); + expect(matching.status).toBe(200); + }); +}); + +describe('credit and the worker lifecycle', () => { + it('answers 402 with no balance, and still lets the user list and remove', async () => { + expect((await publishUser(userToken, 'daily', SOURCE)).status).toBe( + 200, + ); + + vi.spyOn( + env.server.services.metering, + 'hasAnyUsageCached', + ).mockResolvedValue(false); + + const refused = await publishUser(userToken, 'other', OTHER_SOURCE); + expect(refused.status).toBe(402); + expect(refused.body.code).toBe('insufficient_funds'); + expect((await listUser(userToken)).status).toBe(200); + expect((await removeUser(userToken, 'daily')).status).toBe(200); + }); + + it('fires events.worker.create once for the 0 to 1, as the holder', async () => { + await publishUser(otherToken, 'daily', SOURCE); + await publishUser(otherToken, 'again', OTHER_SOURCE); + + expect(creates).toEqual([ + { appUid, scope: 'user', userId: otherUserId }, + ]); + }); + + it('fires events.worker.destroy on the last removal, as the holder', async () => { + await publishUser(otherToken, 'daily', SOURCE); + await publishUser(otherToken, 'again', OTHER_SOURCE); + + await removeUser(otherToken, 'daily'); + expect(destroys).toEqual([]); + await removeUser(otherToken, 'again'); + expect(destroys).toEqual([ + { appUid, scope: 'user', userId: otherUserId }, + ]); + }); + + it('tags an app-scope lifecycle event with the app scope and its owner', async () => { + await publishApp(userToken, 'daily', SOURCE); + expect(creates).toEqual([{ appUid, scope: 'app', userId }]); + }); +}); + +describe('inline create', () => { + const inline = (token: string, source: string) => + subscribe(token, { + subject: `fs:${anchor}`, + queue: true, + handlerSource: source, + context: { url: 'https://hooks.example/abc' }, + }); + + const dbCalls = () => { + const db = env.server.clients.db; + const spies = [ + vi.spyOn(db, 'pread'), + vi.spyOn(db, 'read'), + vi.spyOn(db, 'write'), + vi.spyOn(db, 'insert'), + ]; + return () => spies.reduce((sum, spy) => sum + spy.mock.calls.length, 0); + }; + + it('publishes `@` into the caller`s scope and binds the row to it', async () => { + const created = await inline(userToken, SOURCE); + + expect(created.status).toBe(200); + const name = `@${hashContent(SOURCE)}`; + expect(created.body).toMatchObject({ + handlerName: name, + handlerScope: 'user', + }); + expect(await store().getByName(userScope(userId), name)).toMatchObject({ + source: SOURCE, + }); + const row = await env.server.stores.durableSubscription.getBySubId( + String(created.body.subId), + ); + expect(row).toMatchObject({ handlerName: name, handlerScope: 'user' }); + expect(await store().listForApp(appHandlerScope(appUid))).toEqual([]); + }); + + it('binds a broadcast row too, and refuses neither handler nor source for a queue', async () => { + const created = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerSource: SOURCE, + }); + expect(created.status).toBe(200); + + const refused = await subscribe(userToken, { + subject: `fs:${anchor}`, + queue: true, + }); + expect(refused.status).toBe(400); + expect(refused.body.code).toBe('events_handler_required'); + }); + + it('refuses a body that sends both a handlerName and a handlerSource', async () => { + const refused = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'daily', + handlerSource: SOURCE, + }); + expect(refused.status).toBe(400); + }); + + it('answers a repeat of the same code from the cached set with no database work and no budget', async () => { + const actor = await actorOf(userToken); + + // The first create writes; the next one warms the cache. + await events().ensureInlineHandler(actor, appUid, SOURCE); + await events().ensureInlineHandler(actor, appUid, SOURCE); + + const primaryBefore = publishSpends; + const calls = dbCalls(); + const again = await events().ensureInlineHandler(actor, appUid, SOURCE); + + expect(again).toEqual({ + name: `@${hashContent(SOURCE)}`, + hash: hashContent(SOURCE), + scope: 'user', + }); + expect(calls()).toBe(0); + expect(publishSpends).toBe(primaryBefore); + }); + + it('reads the primary and spends the budget once for the first create in an empty scope', async () => { + const actor = await actorOf(userToken); + const calls = dbCalls(); + + await events().ensureInlineHandler(actor, appUid, SOURCE); + + expect(calls()).toBeGreaterThan(0); + expect(publishSpends).toBe(1); + }); + + it('treats a create that lost the unique-index race as unchanged', async () => { + const actor = await actorOf(userToken); + const real = store().publish.bind(store()); + vi.spyOn(store(), 'publish').mockImplementationOnce(async (input) => { + await real(input); + throw new HttpError(409, 'different source published', { + legacyCode: 'events_handler_conflict', + }); + }); + + await expect( + events().ensureInlineHandler(actor, appUid, SOURCE), + ).resolves.toMatchObject({ name: `@${hashContent(SOURCE)}` }); + }); + + it('does not hide a conflict whose published source differs', async () => { + const actor = await actorOf(userToken); + vi.spyOn(store(), 'publish').mockRejectedValueOnce( + new HttpError(409, 'different source published', { + legacyCode: 'events_handler_conflict', + }), + ); + await expect( + events().ensureInlineHandler(actor, appUid, SOURCE), + ).rejects.toMatchObject({ legacyCode: 'events_handler_conflict' }); + }); + + it('lets concurrent identical creates both succeed, leaving one handler', async () => { + const [a, b, c] = await Promise.all([ + inline(userToken, SOURCE), + inline(userToken, SOURCE), + inline(userToken, SOURCE), + ]); + + expect([a.status, b.status, c.status]).toEqual([200, 200, 200]); + expect(await store().countForApp(userScope(userId))).toBe(1); + }); + + it('leaves the handler behind when the row create fails past it', async () => { + const refused = await subscribe(userToken, { + subject: 'fs:/nowhere/at/all', + queue: true, + handlerSource: SOURCE, + }); + expect(refused.status).not.toBe(200); + // The subject failed to resolve first, so nothing was published. + expect(await store().countForApp(userScope(userId))).toBe(0); + + vi.spyOn( + env.server.stores.durableSubscription, + 'create', + ).mockRejectedValueOnce( + new HttpError(429, 'quota', { legacyCode: 'too_many_requests' }), + ); + const quota = await inline(userToken, SOURCE); + expect(quota.status).toBe(429); + expect(await store().countForApp(userScope(userId))).toBe(1); + }); + + it('resumes rows suspended for a missing handler when it is created again', async () => { + const created = await inline(userToken, SOURCE); + const subId = String(created.body.subId); + const name = `@${hashContent(SOURCE)}`; + + await removeUser(userToken, name); + const suspended = + await env.server.stores.durableSubscription.getBySubId(subId); + expect(suspended?.suspendedReason).toBe('handler_not_found'); + + await inline(userToken, SOURCE); + const resumed = + await env.server.stores.durableSubscription.getBySubId(subId); + expect(resumed?.suspendedAt).toBeNull(); + }); + + it('suspends the rows bound to a scope that is destroyed', async () => { + const created = await inline(userToken, SOURCE); + const destroyed = await call( + 'POST', + '/events/workers/destroy', + userToken, + { scope: 'user' }, + ); + + expect(destroyed.body).toMatchObject({ removed: 1, suspended: 1 }); + const row = await env.server.stores.durableSubscription.getBySubId( + String(created.body.subId), + ); + expect(row?.suspendedReason).toBe('handler_not_found'); + }); + + it('refuses an inline create from an account session, a scoped token and a guest', async () => { + for (const token of [ + env.users.user.token, + await scopedTokenFrom(userToken), + ]) { + const refused = await inline(token, SOURCE); + expect(refused.status).toBeGreaterThanOrEqual(400); + expect(refused.status).toBeLessThan(500); + } + vi.spyOn( + env.server.services.metering, + 'getActorSubscription', + ).mockResolvedValue({ id: DEFAULT_TEMP_SUBSCRIPTION } as never); + expect((await inline(userToken, SOURCE)).status).toBeGreaterThanOrEqual( + 400, + ); + expect(await store().countForApp(userScope(userId))).toBe(0); + }); + + it('answers 402 with no balance only when it has to publish', async () => { + const actor = await actorOf(userToken); + await events().ensureInlineHandler(actor, appUid, SOURCE); + await events().ensureInlineHandler(actor, appUid, SOURCE); + vi.spyOn( + env.server.services.metering, + 'hasAnyUsageCached', + ).mockResolvedValue(false); + + await expect( + events().ensureInlineHandler(actor, appUid, SOURCE), + ).resolves.toBeDefined(); + await expect( + events().ensureInlineHandler(actor, appUid, OTHER_SOURCE), + ).rejects.toMatchObject({ statusCode: 402 }); + }); +}); + +describe('peer broadcast', () => { + const cacheUpdates = (emit: ReturnType) => + emit.mock.calls.filter( + (args) => + args[0] === 'outer.cacheUpdate' && + (args[1] as { cacheKey: string[] }).cacheKey.some((key) => + key.startsWith(`eventHandlers:uset:${appUid}:${userId}`), + ), + ); + + it('sends nothing for an inline insert, and one event each for a remove and a named publish', async () => { + const emit = vi.spyOn(env.server.clients.event, 'emit'); + const actor = await actorOf(userToken); + + await events().ensureInlineHandler(actor, appUid, SOURCE); + expect(cacheUpdates(emit)).toHaveLength(0); + + await removeUser(userToken, `@${hashContent(SOURCE)}`); + expect(cacheUpdates(emit)).toHaveLength(1); + + await publishUser(userToken, 'named', OTHER_SOURCE); + expect(cacheUpdates(emit)).toHaveLength(2); + }); + + it('still clears this region`s cache on an inline insert', async () => { + const actor = await actorOf(userToken); + await events().ensureInlineHandler(actor, appUid, SOURCE); + await events().ensureInlineHandler(actor, appUid, SOURCE); + // Warm: the set is cached for the one handler. + const second = await events().ensureInlineHandler( + actor, + appUid, + OTHER_SOURCE, + ); + expect( + ( + await store().cachedSetForApp(userScope(userId), { + handlerName: second.name, + }) + ).map((handler) => handler.name), + ).toContain(second.name); + }); +}); + +describe('scope isolation', () => { + it('keeps one user from listing, binding to or removing another`s handler', async () => { + await publishUser(userToken, 'mine', SOURCE); + + expect((await listUser(otherToken)).body.handlers).toEqual([]); + expect((await listUser(userToken)).body.handlers).toEqual([ + expect.objectContaining({ name: 'mine' }), + ]); + + await expect( + events().assertHandlerBinding(appUid, 'mine', null, { + holder: otherUserId, + }), + ).rejects.toMatchObject({ legacyCode: 'events_handler_not_found' }); + await expect( + events().assertHandlerBinding(appUid, 'mine', null, { + holder: userId, + }), + ).resolves.toBeUndefined(); + + const removed = await removeUser(otherToken, 'mine'); + expect(removed.body).toMatchObject({ removed: false }); + expect(await store().getByName(userScope(userId), 'mine')).not.toBe( + null, + ); + + const bound = await subscribe(otherToken, { + subject: `fs:${otherAnchor}`, + handlerName: 'mine', + handlerScope: 'user', + }); + expect(bound.status).toBe(404); + expect(bound.body.code).toBe('events_handler_not_found'); + }); + + it('never resolves an app-scope handler for a user binding, or the reverse', async () => { + await publishApp(userToken, 'shared-name', SOURCE); + await publishUser(userToken, 'user-only', OTHER_SOURCE); + + const userBindingOfAppName = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'shared-name', + handlerScope: 'user', + }); + expect(userBindingOfAppName.status).toBe(404); + + const appBindingOfUserName = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'user-only', + }); + expect(appBindingOfUserName.status).toBe(404); + + await expect( + events().assertHandlerBinding(appUid, 'user-only', null), + ).rejects.toMatchObject({ legacyCode: 'events_handler_not_found' }); + await expect( + events().assertHandlerBinding(appUid, 'shared-name', null, { + holder: userId, + }), + ).rejects.toMatchObject({ legacyCode: 'events_handler_not_found' }); + }); + + it('binds a named user handler to the caller`s scope, hash checked', async () => { + await publishUser(userToken, 'daily', SOURCE); + + const bound = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'daily', + handlerScope: 'user', + queue: true, + }); + expect(bound.status).toBe(200); + expect(bound.body).toMatchObject({ + handlerName: 'daily', + handlerScope: 'user', + }); + + const wrongHash = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'daily', + handlerScope: 'user', + handlerHash: 'a'.repeat(64), + }); + expect(wrongHash.status).toBe(409); + expect(wrongHash.body.code).toBe('events_handler_hash_mismatch'); + }); + + it('keeps app-scope and user-scope dependents apart on removal', async () => { + await publishApp(userToken, 'same', SOURCE); + await publishUser(userToken, 'same', OTHER_SOURCE); + const appRow = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'same', + }); + const userRow = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'same', + handlerScope: 'user', + }); + expect(appRow.status).toBe(200); + expect(userRow.status).toBe(200); + const rows = env.server.stores.durableSubscription; + + // Removing the app's name leaves the user's binding in service. + const appRemoval = await call( + 'POST', + '/events/handlers/remove', + userToken, + { + name: 'same', + }, + ); + expect(appRemoval.body).toMatchObject({ removed: true, suspended: 1 }); + expect( + (await rows.getBySubId(String(appRow.body.subId)))?.suspendedReason, + ).toBe('handler_not_found'); + expect( + (await rows.getBySubId(String(userRow.body.subId)))?.suspendedAt, + ).toBeNull(); + + // And the reverse: removing the user's leaves a republished app row. + await publishApp(userToken, 'same', SOURCE); + expect( + (await rows.getBySubId(String(appRow.body.subId)))?.suspendedAt, + ).toBeNull(); + const userRemoval = await removeUser(userToken, 'same'); + expect(userRemoval.body).toMatchObject({ removed: true, suspended: 1 }); + expect( + (await rows.getBySubId(String(appRow.body.subId)))?.suspendedAt, + ).toBeNull(); + expect( + (await rows.getBySubId(String(userRow.body.subId))) + ?.suspendedReason, + ).toBe('handler_not_found'); + }); + + it('resumes only the user scope`s rows when a user republishes the name', async () => { + await publishUser(userToken, 'same', SOURCE); + const userRow = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'same', + handlerScope: 'user', + }); + await removeUser(userToken, 'same'); + const rows = env.server.stores.durableSubscription; + expect( + (await rows.getBySubId(String(userRow.body.subId))) + ?.suspendedReason, + ).toBe('handler_not_found'); + + // An app-scope publish of the same name does not bring it back. + await publishApp(userToken, 'same', SOURCE); + expect( + (await rows.getBySubId(String(userRow.body.subId))) + ?.suspendedReason, + ).toBe('handler_not_found'); + + const republished = await publishUser(userToken, 'same', SOURCE); + expect(republished.body.resumed).toBe(1); + }); +}); + +describe('with the flag off', () => { + beforeEach(() => { + ( + events() as unknown as { config: IConfig } + ).config.events!.userHandlers = false; + }); + + it('refuses a user-scope publish and an inline create', async () => { + const publishRefused = await publishUser(userToken, 'daily', SOURCE); + expect(publishRefused.status).toBe(503); + expect(publishRefused.body.code).toBe('events_user_handlers_disabled'); + + const inlineRefused = await subscribe(userToken, { + subject: `fs:${anchor}`, + queue: true, + handlerSource: SOURCE, + }); + expect(inlineRefused.status).toBe(503); + expect(inlineRefused.body.code).toBe('events_user_handlers_disabled'); + + const namedRefused = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'daily', + handlerScope: 'user', + }); + expect(namedRefused.status).toBe(503); + expect(await store().countForApp(userScope(userId))).toBe(0); + }); + + it('leaves app scope alone, and lets a user remove what they hold', async () => { + expect((await publishApp(userToken, 'daily', SOURCE)).status).toBe(200); + + await store().publish({ + scope: userScope(userId), + name: 'held', + source: SOURCE, + }); + expect((await removeUser(userToken, 'held')).body).toMatchObject({ + removed: true, + }); + }); +}); + +describe('caps', () => { + it('refuses the handler past the per-scope count', async () => { + for (let i = 0; i < EVENTS_USER_HANDLERS_PER_SCOPE; i++) + expect( + (await publishUser(userToken, `h${i}`, `${SOURCE} // ${i}`)) + .status, + ).toBe(200); + + const refused = await publishUser(userToken, 'one-more', OTHER_SOURCE); + expect(refused.status).toBe(429); + expect(refused.body.code).toBe('events_handler_limit'); + + // Another user's scope in the same app is a scope of its own. + expect((await publishUser(otherToken, 'h0', SOURCE)).status).toBe(200); + }); + + it('refuses a scope whose handlers together exceed the combined size', async () => { + const padded = (i: number) => + `async () => { /* ${i} ${'x'.repeat(EVENTS_HANDLER_SOURCE_MAX_BYTES - 1024)} */ }`; + const fits = Math.floor( + EVENTS_USER_SCOPE_SOURCE_MAX_BYTES / + (EVENTS_HANDLER_SOURCE_MAX_BYTES - 1000), + ); + for (let i = 0; i < fits; i++) + expect( + (await publishUser(userToken, `big${i}`, padded(i))).status, + ).toBe(200); + + const refused = await publishUser(userToken, 'bigger', padded(99)); + expect(refused.status).toBe(413); + expect(refused.body.code).toBe('events_worker_too_large'); + + // The cap is per scope. + expect((await publishUser(otherToken, 'big0', padded(0))).status).toBe( + 200, + ); + }); + + it('holds one handler to the shared per-handler size', async () => { + const refused = await publishUser( + userToken, + 'huge', + `async () => { /* ${'x'.repeat(EVENTS_HANDLER_SOURCE_MAX_BYTES)} */ }`, + ); + expect(refused.status).toBe(413); + expect(refused.body.code).toBe('events_handler_too_large'); + }); + + it('spends the shared publish budget on a user-scope publish', async () => { + await publishUser(userToken, 'daily', SOURCE); + expect(publishSpends).toBe(1); + }); +}); + +describe('rented-unit cap', () => { + const refusedAsLimit = (response: ApiResponse) => { + expect(response.status).toBe(403); + expect(response.body.code).toBe('forbidden'); + }; + + it('refuses a free user the 17th unit, whichever source filled the 16', async () => { + for (const held of [ + { workers: 16 }, + { scopes: 16 }, + { owned: 16 }, + { workers: 6, scopes: 5, owned: 5 }, + ]) { + holding(DEFAULT_FREE_SUBSCRIPTION, held); + refusedAsLimit(await publishUser(userToken, 'daily', SOURCE)); + const inline = await subscribe(userToken, { + subject: `fs:${anchor}`, + queue: true, + handlerSource: SOURCE, + }); + refusedAsLimit(inline); + // The app's first handler is a unit as well. + refusedAsLimit(await publishApp(userToken, 'daily', SOURCE)); + vi.restoreAllMocks(); + // restoreAllMocks drops the publish spy too. + vi.spyOn(rateLimit, 'checkRateLimit').mockResolvedValue(true); + } + expect(await store().countForApp(userScope(userId))).toBe(0); + expect(await store().countForApp(appHandlerScope(appUid))).toBe(0); + }); + + it('admits the 16th unit for a free user', async () => { + holding(DEFAULT_FREE_SUBSCRIPTION, { + workers: 10, + scopes: 3, + owned: 2, + }); + expect((await publishUser(userToken, 'daily', SOURCE)).status).toBe( + 200, + ); + }); + + it('refuses a paid user the 101st unit and admits the 100th', async () => { + holding('paid-plan', { workers: 90, scopes: 5, owned: 5 }); + refusedAsLimit(await publishUser(userToken, 'daily', SOURCE)); + + vi.restoreAllMocks(); + vi.spyOn(rateLimit, 'checkRateLimit').mockResolvedValue(true); + holding('paid-plan', { workers: 90, scopes: 5, owned: 4 }); + expect((await publishUser(userToken, 'daily', SOURCE)).status).toBe( + 200, + ); + }); + + it('never counts a publish into an existing scope as a new unit', async () => { + await publishUser(userToken, 'first', SOURCE); + await publishApp(userToken, 'first', SOURCE); + + holding(DEFAULT_FREE_SUBSCRIPTION, { + workers: 16, + scopes: 16, + owned: 16, + }); + expect( + (await publishUser(userToken, 'second', OTHER_SOURCE)).status, + ).toBe(200); + expect((await publishUser(userToken, 'first', SOURCE)).status).toBe( + 200, + ); + expect( + (await publishApp(userToken, 'second', OTHER_SOURCE)).status, + ).toBe(200); + const inline = await subscribe(userToken, { + subject: `fs:${anchor}`, + queue: true, + handlerSource: 'async () => { /* inline */ }', + }); + expect(inline.status).toBe(200); + }); + + it('counts a batch`s first handler once, not once per item', async () => { + holding(DEFAULT_FREE_SUBSCRIPTION, { workers: 15 }); + vi.mocked( + store().countUserScopesWithHandlersForUser, + ).mockImplementation(async () => + store().countForApp(userScope(userId)), + ); + const batch = await call( + 'POST', + '/events/handlers/publishAll', + userToken, + { + scope: 'user', + handlers: [ + { name: 'a', source: SOURCE }, + { name: 'b', source: OTHER_SOURCE }, + ], + }, + ); + expect(batch.status).toBe(200); + }); +}); + +describe('subscription views', () => { + it('reports `handlerScope` only on a user-scope row', async () => { + await publishApp(userToken, 'app-handler', SOURCE); + const appRow = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerName: 'app-handler', + }); + const inline = await subscribe(userToken, { + subject: `fs:${anchor}`, + handlerSource: SOURCE, + }); + + const listed = (await call('GET', '/events/subscriptions', userToken)) + .body.items as DurableSubscriptionView[]; + const byId = new Map(listed.map((item) => [item.subId, item])); + expect( + byId.get(String(appRow.body.subId))?.handlerScope, + ).toBeUndefined(); + expect(byId.get(String(inline.body.subId))?.handlerScope).toBe('user'); + }); +}); + +// Firing resolves app-scope sets only, so a row bound to a user-scope handler +// has to wait rather than run against the wrong set or be failed. +describe('firing a user-scope row', () => { + it('leaves a delivery owed instead of running or failing it', async () => { + const created = await subscribe(userToken, { + subject: `fs:${anchor}`, + queue: true, + handlerSource: SOURCE, + }); + expect(created.status).toBe(200); + const invoke = vi.fn(); + const previous = events().worker; + events().worker = { invoke } as never; + onTestFinished(() => { + events().worker = previous; + }); + + await env.server.services.fs.touch(userId, { + path: `${anchor}/${uuidv4()}.txt`, + }); + await new Promise((resolve) => setTimeout(resolve, 300)); + + expect(invoke).not.toHaveBeenCalled(); + const row = await env.server.stores.durableSubscription.getBySubId( + String(created.body.subId), + ); + expect(row?.suspendedAt).toBeNull(); + }); +}); + +void foreignAppToken; diff --git a/src/backend/services/events/workers.integration.test.ts b/src/backend/services/events/workers.integration.test.ts index 775ba2af8..99562557a 100644 --- a/src/backend/services/events/workers.integration.test.ts +++ b/src/backend/services/events/workers.integration.test.ts @@ -175,7 +175,7 @@ let destroys: Array<{ appUid: string; ownerId: number | undefined }>; beforeAll(async () => { env = await setupPuterTestEnv({ - events: { enabled: true }, + events: { enabled: true, userHandlers: true }, unlimitedMetering: true, } as IConfig); @@ -204,6 +204,7 @@ afterAll(async () => { beforeEach(async () => { await env.server.clients.db.write('DELETE FROM `event_handlers`', []); + await env.server.clients.db.write('DELETE FROM `event_user_handlers`', []); await env.server.clients.db.write('DELETE FROM `event_subscriptions`', []); await env.server.clients.db.write('DELETE FROM `apps`', []); creates.length = 0; @@ -625,3 +626,234 @@ describe('POST /events/workers/destroy', () => { expect(destroys).toEqual([]); }); }); + +// -- User scopes ----------------------------------------------------- + +/** `userId`'s own session of `app`, wherever the app's owner is. */ +const sessionIn = async (app: { uid: string }, asUser: 'user' | 'other') => { + const { actor } = await env.server.services.auth.authenticate( + asUser === 'user' ? env.users.user.token : env.users.other.token, + ); + return env.server.services.auth.getUserAppToken(actor!, app.uid); +}; + +const publishUserScope = (token: string, name: string, source: string) => + call('POST', '/events/handlers/publish', token, { + scope: 'user', + name, + source, + }); + +describe('GET /events/workers with user scopes', () => { + it('adds the caller`s user scopes to their app workers outside an app', async () => { + const mine = await makeApp(userId); + await publish(mine.token, { + appUid: mine.uid, + name: 'a', + source: SOURCE, + }); + const theirs = await makeApp(otherUserId); + const inTheirs = await sessionIn(theirs, 'user'); + await publishUserScope(inTheirs, 'x', SOURCE); + await publishUserScope(inTheirs, 'y', OTHER_SOURCE); + // Another holder's scope in the same app is not the caller's. + await publishUserScope(await sessionIn(theirs, 'other'), 'z', SOURCE); + + const listed = await call( + 'GET', + '/events/workers', + env.users.user.token, + ); + + expect(listed.status).toBe(200); + expect(listed.body.items).toEqual([ + expect.objectContaining({ + scope: 'app', + appUid: mine.uid, + handlerCount: 1, + }), + expect.objectContaining({ + scope: 'user', + appUid: theirs.uid, + appName: theirs.uid, + handlerCount: 2, + }), + ]); + expect(listed.body.cursor).toBeUndefined(); + }); + + it('pages through the app workers and then the user scopes', async () => { + const mine = await makeApp(userId); + await publish(mine.token, { + appUid: mine.uid, + name: 'a', + source: SOURCE, + }); + const first = await makeApp(otherUserId); + const second = await makeApp(otherUserId); + await publishUserScope(await sessionIn(first, 'user'), 'x', SOURCE); + await publishUserScope(await sessionIn(second, 'user'), 'x', SOURCE); + + const seen: Array> = []; + let cursor: string | undefined; + let pages = 0; + do { + const page = await call( + 'GET', + `/events/workers?limit=1${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`, + env.users.user.token, + ); + expect(page.status).toBe(200); + seen.push(...(page.body.items as Array>)); + cursor = page.body.cursor as string | undefined; + pages += 1; + } while (cursor && pages < 10); + + expect(seen.map((item) => [item.scope, item.appUid])).toEqual([ + ['app', mine.uid], + ...[first.uid, second.uid].sort().map((uid) => ['user', uid]), + ]); + }); + + it('lists only that app`s scope for the caller inside an app', async () => { + const theirs = await makeApp(otherUserId); + const otherApp = await makeApp(otherUserId); + const inTheirs = await sessionIn(theirs, 'user'); + await publishUserScope(inTheirs, 'x', SOURCE); + await publishUserScope(await sessionIn(otherApp, 'user'), 'x', SOURCE); + await publishUserScope(await sessionIn(theirs, 'other'), 'x', SOURCE); + // The owner's own worker in that app is not the caller's to see. + await publish(theirs.token, { + appUid: theirs.uid, + name: 'owner', + source: SOURCE, + }); + + const listed = await call('GET', '/events/workers', inTheirs); + + expect(listed.status).toBe(200); + expect(listed.body.items).toEqual([ + expect.objectContaining({ + scope: 'user', + appUid: theirs.uid, + handlerCount: 1, + }), + ]); + }); + + it('still lists the owner`s worker beside their own user scope inside the app', async () => { + const mine = await makeApp(userId); + await publish(mine.token, { + appUid: mine.uid, + name: 'a', + source: SOURCE, + }); + await publishUserScope(mine.token, 'x', SOURCE); + + const listed = await call('GET', '/events/workers', mine.token); + + expect( + (listed.body.items as Array>).map( + (item) => item.scope, + ), + ).toEqual(['app', 'user']); + }); + + it('refuses a scoped token, which has no scope of its own', async () => { + const theirs = await makeApp(otherUserId); + await publishUserScope(await sessionIn(theirs, 'user'), 'x', SOURCE); + const scoped = await appIssuedScopedToken({ + uid: theirs.uid, + token: await sessionIn(theirs, 'user'), + }); + + const listed = await call('GET', '/events/workers', scoped); + expect(listed.status).toBe(403); + expect(listed.body.code).toBe('events_worker_owner_only'); + }); +}); + +describe('POST /events/workers/destroy with a user scope', () => { + it('removes the caller`s scope only, suspends what was bound, and announces it', async () => { + const theirs = await makeApp(otherUserId); + const mineIn = await sessionIn(theirs, 'user'); + const otherIn = await sessionIn(theirs, 'other'); + await publish(theirs.token, { + appUid: theirs.uid, + name: 'owner', + source: SOURCE, + }); + await publishUserScope(mineIn, 'x', SOURCE); + await publishUserScope(mineIn, 'y', OTHER_SOURCE); + await publishUserScope(otherIn, 'x', SOURCE); + destroys.length = 0; + + const destroyed = await call( + 'POST', + '/events/workers/destroy', + mineIn, + { + scope: 'user', + }, + ); + + expect(destroyed.status).toBe(200); + expect(destroyed.body).toMatchObject({ + appUid: theirs.uid, + removed: 2, + suspended: 0, + scope: 'user', + }); + const store = env.server.stores.eventHandler; + expect( + await store.countForApp({ appUid: theirs.uid, holder: userId }), + ).toBe(0); + expect( + await store.countForApp({ + appUid: theirs.uid, + holder: otherUserId, + }), + ).toBe(1); + expect(await store.countForApp({ appUid: theirs.uid, holder: 0 })).toBe( + 1, + ); + expect(destroys).toEqual([{ appUid: theirs.uid, ownerId: userId }]); + + const again = await call('POST', '/events/workers/destroy', mineIn, { + scope: 'user', + }); + expect(again.status).toBe(404); + }); + + it('refuses a scoped token, a session with no app, and another app', async () => { + const theirs = await makeApp(otherUserId); + const mineIn = await sessionIn(theirs, 'user'); + await publishUserScope(mineIn, 'x', SOURCE); + const scoped = await appIssuedScopedToken({ + uid: theirs.uid, + token: mineIn, + }); + const elsewhere = await makeApp(otherUserId); + + for (const [token, body] of [ + [scoped, { scope: 'user' }], + [env.users.user.token, { scope: 'user', appUid: theirs.uid }], + [mineIn, { scope: 'user', appUid: elsewhere.uid }], + ] as const) { + const refused = await call( + 'POST', + '/events/workers/destroy', + token, + body, + ); + expect(refused.status).toBe(403); + expect(refused.body.code).toBe('events_handler_forbidden'); + } + expect( + await env.server.stores.eventHandler.countForApp({ + appUid: theirs.uid, + holder: userId, + }), + ).toBe(1); + }); +});