/** * Harness + authorization matrix suite. * * Covers catalogue §1.2 HARNESS-05..20 and §3.2 AUTH-01..14. * * Everything is a live HTTP/tRPC call. Where the current implementation * diverges from the catalogue's intent the case is prefixed `(current)` and the * comment states the observed contract (do not "fix" it here). */ import fs from 'node:fs' import path from 'node:path' import crypto from 'node:crypto' import { rawMutation, rawQuery, rest, uniqueSuffix } from '../helpers/api' import { resetSessions, staffSession, superadminSession, userSession } from '../helpers/sessions' import { COORDS, PASSWORD, registerThrowawayUser } from '../helpers/fixtures' import { superadminCredentials, staffCredentials, TEST_BOUND_ID, TEST_REGION_ID, userCredentials, } from '../helpers/env' jest.setTimeout(180_000) /* -------------------------------------------------------------------------- */ /* Local response helpers */ /* -------------------------------------------------------------------------- */ function batch0(body: unknown): any { return Array.isArray(body) ? (body as any[])[0] : (body as any) } function codeOf(body: unknown): string | undefined { return batch0(body)?.error?.data?.code } function httpStatusOf(body: unknown): number | undefined { return batch0(body)?.error?.data?.httpStatus } function dataOf(body: unknown): any { return batch0(body)?.result?.data } function isOk(body: unknown): boolean { return batch0(body)?.result !== undefined } function call(proc: string, method: 'GET' | 'POST', input: unknown = {}, token?: string) { return method === 'GET' ? rawQuery(proc, input, { token }) : rawMutation(proc, input, { token }) } async function json(res: Response): Promise { return (await res.json()) as any } /** Login with `Caller-Interface: web` and capture the Set-Cookie value. */ async function webCookieLogin() { const { identifier, password } = userCredentials() const res = await rest('/api/trpc/user.auth.login?batch=1', { method: 'POST', headers: { 'content-type': 'application/json', 'Caller-Interface': 'web' }, body: JSON.stringify({ 0: { identifier, password } }), }) const cookie = res.headers.get('set-cookie') ?? '' return { res, cookie, token: cookie.match(/auth_token=([^;]+)/)?.[1] ?? '' } } /* -------------------------------------------------------------------------- */ /* JWT helpers — the dev secret lives in wrangler.dev.toml */ /* -------------------------------------------------------------------------- */ function jwtSecret(): string { const toml = fs.readFileSync(path.resolve(__dirname, '../../wrangler.dev.toml'), 'utf8') const match = toml.match(/JWT_SECRET\s*=\s*"([^"]+)"/) if (!match) throw new Error('[api-tests] JWT_SECRET not found in wrangler.dev.toml') return match[1] } /** * Sign an HS256 JWT with the given secret and `exp` epoch. Implemented with * node:crypto so the suite never has to load jose's ESM build under ts-jest. */ function signToken(payload: Record, secret: string, expiresAtEpoch: number): string { const b64url = (value: Buffer | string) => Buffer.from(value).toString('base64url') const header = b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' })) const body = b64url(JSON.stringify({ ...payload, exp: expiresAtEpoch })) const data = `${header}.${body}` const signature = crypto.createHmac('sha256', secret).update(data).digest('base64url') return `${data}.${signature}` } /* -------------------------------------------------------------------------- */ /* Procedure tables */ /* -------------------------------------------------------------------------- */ interface Proc { proc: string method: 'GET' | 'POST' } /** §3.2 AUTH-01 — reachable without any token. */ const PUBLIC_PROCEDURES: Array = [ { proc: 'common.healthCheck', method: 'GET', input: {} }, { proc: 'common.listRegions', method: 'GET', input: {} }, { proc: 'common.checkLocationInPolygon', method: 'GET', input: { lat: COORDS.region1Bound1.lat, lng: COORDS.region1Bound1.lng }, }, { proc: 'common.resolveRegionByLocation', method: 'GET', input: { lat: COORDS.region1Bound1.lat, lng: COORDS.region1Bound1.lng }, }, { proc: 'common.resolveBound', method: 'GET', input: { regionId: TEST_REGION_ID, lat: COORDS.region1Bound1.lat, lng: COORDS.region1Bound1.lng }, }, { proc: 'common.regionSettings', method: 'GET', input: { regionId: TEST_REGION_ID } }, { proc: 'common.activeBound', method: 'GET', input: { regionId: TEST_REGION_ID } }, { proc: 'common.essentialConsts', method: 'GET', input: { boundId: TEST_BOUND_ID } }, { proc: 'user.slots.getSlots', method: 'GET', input: { regionId: TEST_REGION_ID } }, { proc: 'admin.vendorSnippets.getUpcomingSlots', method: 'GET', input: {} }, ] /** §3.2 AUTH-02 — user.* procedures that require a user token. */ const USER_PROTECTED: Proc[] = [ { proc: 'user.order.getOrders', method: 'GET' }, { proc: 'user.order.getOrderById', method: 'GET' }, { proc: 'user.address.getDefaultAddress', method: 'GET' }, { proc: 'user.address.getUserAddresses', method: 'GET' }, { proc: 'user.coupon.getEligible', method: 'GET' }, { proc: 'user.coupon.getMyCoupons', method: 'GET' }, { proc: 'user.complaint.getAll', method: 'GET' }, { proc: 'user.user.getSelfData', method: 'GET' }, { proc: 'user.order.placeOrder', method: 'POST' }, { proc: 'user.order.cancelOrder', method: 'POST' }, { proc: 'user.order.updateUserNotes', method: 'POST' }, { proc: 'user.address.createAddress', method: 'POST' }, { proc: 'user.address.updateAddress', method: 'POST' }, { proc: 'user.address.deleteAddress', method: 'POST' }, { proc: 'user.auth.updatePassword', method: 'POST' }, { proc: 'user.auth.updateProfile', method: 'POST' }, { proc: 'user.auth.deleteAccount', method: 'POST' }, { proc: 'user.product.createReview', method: 'POST' }, { proc: 'user.coupon.redeemReservedCoupon', method: 'POST' }, { proc: 'user.complaint.raise', method: 'POST' }, { proc: 'user.fileUpload.generateUploadUrls', method: 'POST' }, { proc: 'user.user.recordTrackedRegion', method: 'POST' }, ] /** §3.2 AUTH-03 — representative admin reads (protectedProcedure). */ const ADMIN_READS: Proc[] = [ { proc: 'admin.vendorSnippets.getAll', method: 'GET' }, { proc: 'admin.staffUser.getStaff', method: 'GET' }, { proc: 'admin.product.getProducts', method: 'GET' }, { proc: 'admin.store.getStores', method: 'GET' }, { proc: 'admin.user.getAllUsers', method: 'GET' }, { proc: 'admin.banner.getBanners', method: 'GET' }, { proc: 'admin.coupon.getAll', method: 'GET' }, { proc: 'admin.complaint.getAll', method: 'GET' }, { proc: 'admin.slots.getAll', method: 'GET' }, { proc: 'admin.order.getAll', method: 'GET' }, ] /** §3.2 AUTH-04 — representative admin writes (protectedProcedure). */ const ADMIN_WRITES: Proc[] = [ { proc: 'admin.coupon.create', method: 'POST' }, { proc: 'admin.order.updateNotes', method: 'POST' }, { proc: 'admin.banner.updateBanner', method: 'POST' }, { proc: 'admin.product.updateProduct', method: 'POST' }, { proc: 'admin.store.updateStore', method: 'POST' }, { proc: 'admin.slots.updateSlotCapacity', method: 'POST' }, { proc: 'admin.vendorSnippets.update', method: 'POST' }, { proc: 'admin.complaint.resolve', method: 'POST' }, ] /** §3.2 AUTH-05 — staffProcedure (staff-only) reads. */ const STAFF_ONLY_QUERIES: Proc[] = [ { proc: 'admin.staffUser.me', method: 'GET' }, { proc: 'admin.region.current', method: 'GET' }, { proc: 'admin.region.bounds', method: 'GET' }, { proc: 'admin.region.effective', method: 'GET' }, { proc: 'admin.region.getRegionConstants', method: 'GET' }, { proc: 'admin.region.getBoundSettings', method: 'GET' }, ] /** §3.2 AUTH-05 — staffProcedure (staff-only) writes from the catalogue. */ const STAFF_ONLY_WRITES: Proc[] = [ { proc: 'admin.banner.createBanner', method: 'POST' }, { proc: 'admin.product.createProduct', method: 'POST' }, { proc: 'admin.product.createGroup', method: 'POST' }, { proc: 'admin.product.createProductTag', method: 'POST' }, { proc: 'admin.store.createStore', method: 'POST' }, { proc: 'admin.staffUser.sendAdminNotification', method: 'POST' }, { proc: 'admin.vendorSnippets.create', method: 'POST' }, { proc: 'admin.region.updateRegionConstants', method: 'POST' }, { proc: 'admin.region.updateBoundSettings', method: 'POST' }, ] /** §3.2 AUTH-07 — every superadmin.* procedure except the public login. */ const SUPERADMIN_PROCEDURES: Proc[] = [ { proc: 'superadmin.auth.me', method: 'GET' }, { proc: 'superadmin.regions.list', method: 'GET' }, { proc: 'superadmin.regions.get', method: 'GET' }, { proc: 'superadmin.regions.bounds', method: 'GET' }, { proc: 'superadmin.regions.boundSettings', method: 'GET' }, { proc: 'superadmin.regions.getRegionConstants', method: 'GET' }, { proc: 'superadmin.regions.effectiveSettings', method: 'GET' }, { proc: 'superadmin.regions.create', method: 'POST' }, { proc: 'superadmin.regions.update', method: 'POST' }, { proc: 'superadmin.regions.createBound', method: 'POST' }, { proc: 'superadmin.regions.updateBound', method: 'POST' }, { proc: 'superadmin.regions.deleteBound', method: 'POST' }, { proc: 'superadmin.regions.updateBoundSettings', method: 'POST' }, { proc: 'superadmin.regions.updateRegionConstants', method: 'POST' }, { proc: 'superadmin.staff.list', method: 'GET' }, { proc: 'superadmin.staff.roles', method: 'GET' }, { proc: 'superadmin.staff.sendAdminNotification', method: 'POST' }, { proc: 'superadmin.staff.create', method: 'POST' }, { proc: 'superadmin.staff.update', method: 'POST' }, { proc: 'superadmin.staff.remove', method: 'POST' }, { proc: 'superadmin.const.getGlobalConstants', method: 'GET' }, { proc: 'superadmin.const.getLegacyConstants', method: 'GET' }, { proc: 'superadmin.const.updateGlobalConstants', method: 'POST' }, { proc: 'superadmin.const.updateLegacyConstants', method: 'POST' }, { proc: 'superadmin.globalStores.list', method: 'GET' }, { proc: 'superadmin.globalStores.get', method: 'GET' }, { proc: 'superadmin.globalStores.create', method: 'POST' }, { proc: 'superadmin.globalStores.update', method: 'POST' }, { proc: 'superadmin.globalStores.delete', method: 'POST' }, { proc: 'superadmin.stores.list', method: 'GET' }, { proc: 'superadmin.stores.elevate', method: 'POST' }, { proc: 'superadmin.globalProducts.list', method: 'GET' }, { proc: 'superadmin.globalProducts.get', method: 'GET' }, { proc: 'superadmin.globalProducts.create', method: 'POST' }, { proc: 'superadmin.globalProducts.update', method: 'POST' }, { proc: 'superadmin.globalProducts.delete', method: 'POST' }, { proc: 'superadmin.globalCoupons.list', method: 'GET' }, { proc: 'superadmin.globalCoupons.get', method: 'GET' }, { proc: 'superadmin.globalCoupons.create', method: 'POST' }, { proc: 'superadmin.globalCoupons.update', method: 'POST' }, { proc: 'superadmin.globalCoupons.delete', method: 'POST' }, { proc: 'superadmin.products.list', method: 'GET' }, { proc: 'superadmin.products.elevate', method: 'POST' }, { proc: 'superadmin.complaint.getAll', method: 'GET' }, ] /* -------------------------------------------------------------------------- */ /* HARNESS-05..20 */ /* -------------------------------------------------------------------------- */ describe('harness edges (HARNESS-05..20)', () => { beforeAll(() => { // Fresh logins for this process (the file owns its own session cache). resetSessions() }) it('HARNESS-05: the auth_token cookie authenticates when no bearer is sent', async () => { const { token } = await webCookieLogin() expect(token.length).toBeGreaterThan(20) const res = await rawQuery( 'user.order.getOrders', { page: 1, pageSize: 1 }, { headers: { cookie: `auth_token=${token}` } } ) expect(isOk(res.body)).toBe(true) expect(dataOf(res.body)).toBeTruthy() }) it('HARNESS-06: `Caller-Interface: web` sets a HttpOnly/Secure/SameSite=Lax cookie', async () => { const { cookie } = await webCookieLogin() expect(cookie).toMatch(/auth_token=/) expect(cookie).toMatch(/HttpOnly/i) expect(cookie).toMatch(/Secure/i) expect(cookie).toMatch(/SameSite=Lax/i) expect(cookie).toMatch(/Path=\//i) }) it('HARNESS-07: a plain (mobile) login sets no cookie', async () => { const { identifier, password } = userCredentials() const userLogin = await rest('/api/trpc/user.auth.login?batch=1', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ 0: { identifier, password } }), }) expect(userLogin.status).toBe(200) expect(userLogin.headers.get('set-cookie')).toBeNull() const staffCreds = staffCredentials() const staffLogin = await rest('/api/trpc/admin.staffUser.login?batch=1', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ 0: { name: staffCreds.name, password: staffCreds.password } }), }) expect(staffLogin.status).toBe(200) expect(staffLogin.headers.get('set-cookie')).toBeNull() }) it('(current) HARNESS-09: staff token on a user-only endpoint fails in the resolver, not the guard', async () => { const staff = await staffSession() const res = await rawQuery('user.order.getOrders', { page: 1, pageSize: 1 }, { token: staff.token }) // (current) protectedProcedure only checks `ctx.user || ctx.staffUser`, so a // staff token passes the guard and the resolver then throws a TypeError on // `ctx.user.userId` -> INTERNAL_SERVER_ERROR (never UNAUTHORIZED). expect(codeOf(res.body)).toBe('INTERNAL_SERVER_ERROR') expect(httpStatusOf(res.body)).toBe(500) expect(dataOf(res.body)).toBeUndefined() }) it('HARNESS-10: a user token on a staff-only write is rejected', async () => { const user = await userSession() const res = await rawMutation('admin.product.createProduct', {}, { token: user.token }) expect(codeOf(res.body)).toBe('UNAUTHORIZED') expect(httpStatusOf(res.body)).toBe(401) const anon = await rawMutation('admin.product.createProduct', {}) expect(codeOf(anon.body)).toBe('UNAUTHORIZED') }) it('HARNESS-11: a superadmin token on a staff-only endpoint is rejected', async () => { const superadmin = await superadminSession() const query = await rawQuery('admin.staffUser.me', {}, { token: superadmin.token }) expect(codeOf(query.body)).toBe('UNAUTHORIZED') const write = await rawMutation('admin.product.createProduct', {}, { token: superadmin.token }) expect(codeOf(write.body)).toBe('UNAUTHORIZED') }) it('HARNESS-12: a staff token on a superadmin endpoint is rejected', async () => { const staff = await staffSession() const res = await rawQuery('superadmin.auth.me', {}, { token: staff.token }) expect(codeOf(res.body)).toBe('UNAUTHORIZED') }) it('(current) HARNESS-13: a suspended user token is still accepted by tRPC (but rejected by REST)', async () => { const staff = await staffSession() const throwaway = await registerThrowawayUser() let suspended = false try { const suspend = await rawMutation( 'admin.user.updateUserSuspension', { userId: throwaway.userId, isSuspended: true }, { token: staff.token } ) expect(isOk(suspend.body)).toBe(true) suspended = true // (current) createContext assigns `user = decoded` *before* the suspension // check, and the surrounding catch swallows the FORBIDDEN, so the token // keeps working on every tRPC route instead of being rejected. const tRPC = await rawQuery('user.user.getSelfData', {}, { token: throwaway.token }) expect(isOk(tRPC.body)).toBe(true) expect(dataOf(tRPC.body)?.data?.user?.id).toBe(throwaway.userId) // The REST auth middleware *does* honour suspension -> 403. const restRes = await rest('/api/test', { headers: { Authorization: `Bearer ${throwaway.token}` } }) expect(restRes.status).toBe(403) expect((await json(restRes)).message).toMatch(/suspended/i) // Public endpoints stay reachable either way. const publicRes = await rawQuery('common.healthCheck', {}, { token: throwaway.token }) expect(isOk(publicRes.body)).toBe(true) } finally { if (suspended) { const unsuspend = await rawMutation( 'admin.user.updateUserSuspension', { userId: throwaway.userId, isSuspended: false }, { token: staff.token } ) expect(isOk(unsuspend.body)).toBe(true) } } }) it('HARNESS-14: an unknown boundId is a 404 from common.essentialConsts', async () => { const res = await rawQuery('common.essentialConsts', { boundId: 987_654_321 }) expect(codeOf(res.body)).toBe('NOT_FOUND') expect(httpStatusOf(res.body)).toBe(404) }) it('HARNESS-15: an invalid JSON batch body is a tRPC error and never crashes the worker', async () => { const res = await rawMutation('user.auth.login', null, { headers: { 'content-type': 'application/json' }, body: '{not valid json', }) expect(res.status).toBe(400) expect(codeOf(res.body)).toBe('BAD_REQUEST') const health = await rest('/api/health') expect(health.status).toBe(200) }) it('HARNESS-16: OPTIONS CORS preflight advertises the allowed origin/headers/methods', async () => { const res = await rest('/api/trpc/user.auth.login?batch=1', { method: 'OPTIONS', headers: { Origin: 'http://localhost:5174', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'content-type,authorization,caller-interface', }, }) expect(res.status).toBeLessThan(300) expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5174') expect((res.headers.get('access-control-allow-methods') ?? '')).toMatch(/GET/) expect((res.headers.get('access-control-allow-methods') ?? '')).toMatch(/POST/) expect((res.headers.get('access-control-allow-headers') ?? '').toLowerCase()).toContain('authorization') expect((res.headers.get('access-control-allow-headers') ?? '').toLowerCase()).toContain('caller-interface') }) it('(current) HARNESS-17: an unknown route is a bare 404 (text, not JSON) with no stack', async () => { const user = await userSession() const res = await rest('/api/definitely-not-a-route', { headers: { Authorization: `Bearer ${user.token}` }, }) expect(res.status).toBe(404) const text = await res.text() // (current) Hono's default 404 is `404 Not Found` as text/plain, not a JSON // envelope; the upside is that it leaks no stack trace. expect(text).toMatch(/404 Not Found/i) expect(text).not.toMatch(/stack|at file:|node_modules/i) }) it('HARNESS-18: ApiError statuses map to the matching tRPC/HTTP codes', async () => { // 400 — invalid email format (zod). const bad400 = await rawMutation('user.auth.register', { name: 'Mapping', email: 'not-an-email', mobile: '9000000000', password: PASSWORD, }) expect(codeOf(bad400.body)).toBe('BAD_REQUEST') expect(httpStatusOf(bad400.body)).toBe(400) // 401 — wrong password. const { identifier } = userCredentials() const bad401 = await rawMutation('user.auth.login', { identifier, password: 'wrong-password' }) expect(codeOf(bad401.body)).toBe('UNAUTHORIZED') expect(httpStatusOf(bad401.body)).toBe(401) // 404 — unknown bound. const bad404 = await rawQuery('common.essentialConsts', { boundId: 987_654_322 }) expect(codeOf(bad404.body)).toBe('NOT_FOUND') expect(httpStatusOf(bad404.body)).toBe(404) // 422 — region with no configured bound. const bad422 = await rawQuery('common.regionSettings', { regionId: 987_654_322 }) expect(codeOf(bad422.body)).toBe('UNPROCESSABLE_CONTENT') expect(httpStatusOf(bad422.body)).toBe(422) // 409 — duplicate email (unique identity). const throwaway = await registerThrowawayUser() const dup = await rawMutation('user.auth.register', { name: 'Dup Mapping', email: throwaway.email, mobile: `8${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`, password: PASSWORD, }) expect(codeOf(dup.body)).toBe('CONFLICT') expect(httpStatusOf(dup.body)).toBe(409) // 403 — suspended user on the REST middleware (the only place that maps 403 // today; tRPC sees suspended tokens as anonymous — see HARNESS-13). const staff = await staffSession() const suspendedUser = await registerThrowawayUser() await rawMutation( 'admin.user.updateUserSuspension', { userId: suspendedUser.userId, isSuspended: true }, { token: staff.token } ) try { const forbidden = await rest('/api/test', { headers: { Authorization: `Bearer ${suspendedUser.token}` }, }) expect(forbidden.status).toBe(403) } finally { await rawMutation( 'admin.user.updateUserSuspension', { userId: suspendedUser.userId, isSuspended: false }, { token: staff.token } ) } }) it('(current) HARNESS-19: an unhandled resolver error is a 500 with no SQL leakage', async () => { const user = await userSession() const res = await rawQuery('common.getStoresSummary', {}, { token: user.token }) expect(codeOf(res.body)).toBe('INTERNAL_SERVER_ERROR') expect(httpStatusOf(res.body)).toBe(500) const message = String(batch0(res.body)?.error?.message ?? '') // (current) the message is the raw TypeError (and dev builds add a stack // field) rather than a generic string — but no SQL statement is exposed. expect(message).not.toMatch(/select |insert |update |delete from|sqlite|d1_error/i) }) it('HARNESS-20: the jest project enforces serial execution (maxWorkers 1)', async () => { const configText = fs.readFileSync(path.resolve(__dirname, '../jest.config.js'), 'utf8') expect(configText).toMatch(/maxWorkers\s*:\s*1/) expect(configText).toMatch(/testTimeout/) }) }) /* -------------------------------------------------------------------------- */ /* AUTH-01..14 */ /* -------------------------------------------------------------------------- */ describe('authorization matrix (AUTH-01..14)', () => { beforeAll(() => resetSessions()) it('AUTH-01: public procedures (incl. logins and public vendor reads) work without a token', async () => { const suffix = uniqueSuffix() const { name: staffName, password: staffPassword } = staffCredentials() const { username, password: superPassword } = superadminCredentials() const { identifier, password } = userCredentials() const logins: Array = [ { proc: 'user.auth.login', method: 'POST', input: { identifier, password } }, { proc: 'user.auth.register', method: 'POST', input: { name: `Public Register ${suffix}`, email: `public-${suffix}@example.com`, mobile: `7${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`, password: PASSWORD, }, }, { proc: 'admin.staffUser.login', method: 'POST', input: { name: staffName, password: staffPassword } }, { proc: 'superadmin.auth.login', method: 'POST', input: { username, password: superPassword } }, ] for (const entry of [...PUBLIC_PROCEDURES, ...logins]) { const res = await call(entry.proc, entry.method, entry.input) expect({ proc: entry.proc, ok: isOk(res.body), code: codeOf(res.body) }).toEqual({ proc: entry.proc, ok: true, code: undefined, }) } }) it('AUTH-02: every user.* protected procedure is 401 without a token', async () => { for (const entry of USER_PROTECTED) { const res = await call(entry.proc, entry.method, {}) expect({ proc: entry.proc, code: codeOf(res.body) }).toEqual({ proc: entry.proc, code: 'UNAUTHORIZED', }) } }) it('(current) AUTH-03: a user token passes the admin read guard (some resolve, some 500)', async () => { const user = await userSession() const staff = await staffSession() for (const entry of ADMIN_READS) { const anon = await call(entry.proc, entry.method, {}) expect({ proc: entry.proc, anon: codeOf(anon.body) }).toEqual({ proc: entry.proc, anon: 'UNAUTHORIZED', }) const staffRes = await call(entry.proc, entry.method, {}, staff.token) expect({ proc: entry.proc, staff: codeOf(staffRes.body) }).toEqual({ proc: entry.proc, staff: undefined, }) } // (current) protectedProcedure accepts a user token, so admin reads are not // staff-only. The observed outcomes vary by resolver: // - vendorSnippets.getAll / staffUser.getStaff don't touch ctx.staffUser -> succeed // - product/store/user/banner/coupon/complaint dereference ctx.staffUser -> 500 // - slots.getAll has an explicit staff check -> 401 // - order.getAll returns a result with `data: undefined` on failure const userOutcomes: Record = {} for (const entry of ADMIN_READS) { const res = await call(entry.proc, entry.method, {}, user.token) userOutcomes[entry.proc] = codeOf(res.body) } expect(userOutcomes['admin.vendorSnippets.getAll']).toBeUndefined() expect(userOutcomes['admin.staffUser.getStaff']).toBeUndefined() expect(userOutcomes['admin.product.getProducts']).toBe('INTERNAL_SERVER_ERROR') expect(userOutcomes['admin.store.getStores']).toBe('INTERNAL_SERVER_ERROR') expect(userOutcomes['admin.user.getAllUsers']).toBe('INTERNAL_SERVER_ERROR') expect(userOutcomes['admin.slots.getAll']).toBe('UNAUTHORIZED') const orderRead = await rawQuery('admin.order.getAll', {}, { token: user.token }) expect(batch0(orderRead.body)?.result).toBeDefined() expect(dataOf(orderRead.body)).toBeUndefined() }) it('(current) AUTH-04: a user token passes the admin write guard', async () => { const user = await userSession() const staff = await staffSession() for (const entry of ADMIN_WRITES) { const anon = await call(entry.proc, entry.method, {}) expect({ proc: entry.proc, anon: codeOf(anon.body) }).toEqual({ proc: entry.proc, anon: 'UNAUTHORIZED', }) const userRes = await call(entry.proc, entry.method, {}, user.token) const userCode = codeOf(userRes.body) expect({ proc: entry.proc, userPassesGuard: userCode !== 'UNAUTHORIZED' }).toEqual({ proc: entry.proc, userPassesGuard: true, }) const staffRes = await call(entry.proc, entry.method, {}, staff.token) const staffCode = codeOf(staffRes.body) expect({ proc: entry.proc, staffPassesGuard: staffCode !== 'UNAUTHORIZED' }).toEqual({ proc: entry.proc, staffPassesGuard: true, }) } // (current) admin.user.updateUserSuspension never touches ctx.staffUser, so a // user token performs a real suspension. Demonstrated on a throwaway user and // reverted immediately. const throwaway = await registerThrowawayUser() const asUser = await rawMutation( 'admin.user.updateUserSuspension', { userId: throwaway.userId, isSuspended: true }, { token: user.token } ) expect(isOk(asUser.body)).toBe(true) try { const r = await rest('/api/test', { headers: { Authorization: `Bearer ${throwaway.token}` } }) expect(r.status).toBe(403) } finally { const revert = await rawMutation( 'admin.user.updateUserSuspension', { userId: throwaway.userId, isSuspended: false }, { token: staff.token } ) expect(isOk(revert.body)).toBe(true) } }) it('AUTH-05: staff-only procedures reject no-token/user/superadmin and accept staff', async () => { const user = await userSession() const staff = await staffSession() const superadmin = await superadminSession() for (const entry of [...STAFF_ONLY_QUERIES, ...STAFF_ONLY_WRITES]) { for (const [label, token] of [ ['anon', undefined], ['user', user.token], ['superadmin', superadmin.token], ] as const) { const res = await call(entry.proc, entry.method, {}, token) expect({ proc: entry.proc, who: label, code: codeOf(res.body) }).toEqual({ proc: entry.proc, who: label, code: 'UNAUTHORIZED', }) } } for (const entry of STAFF_ONLY_QUERIES) { const res = await call(entry.proc, entry.method, {}, staff.token) const code = codeOf(res.body) // `getBoundSettings` requires an input, so an empty input is a // BAD_REQUEST; `undefined` means the query answered. Either way the guard // opened for staff. expect({ proc: entry.proc, staffPassesGuard: code === undefined || code === 'BAD_REQUEST' }).toEqual({ proc: entry.proc, staffPassesGuard: true, }) } // Writes reach the resolver with a staff token (the guard passed); an empty // input then fails schema validation, which is what proves the guard opened. for (const entry of STAFF_ONLY_WRITES) { const res = await call(entry.proc, entry.method, {}, staff.token) const code = codeOf(res.body) expect({ proc: entry.proc, staffPassesGuard: code === undefined || code === 'BAD_REQUEST' }).toEqual({ proc: entry.proc, staffPassesGuard: true, }) } // End-to-end: a real staff write succeeds. const created = await rawMutation( 'admin.store.createStore', { name: `AUTH-05 Store ${uniqueSuffix()}`, description: 'auth matrix' }, { token: staff.token } ) expect(isOk(created.body)).toBe(true) expect(dataOf(created.body)?.store?.id).toBeGreaterThan(0) }) it('AUTH-06: common.generateUploadUrls accepts any authenticated principal, rejects anonymous', async () => { const user = await userSession() const staff = await staffSession() const superadmin = await superadminSession() const anon = await rawMutation('common.generateUploadUrls', { contextString: 'review', mimeTypes: ['image/png'], }) expect(codeOf(anon.body)).toBe('UNAUTHORIZED') for (const [label, token] of [ ['user', user.token], ['staff', staff.token], ['superadmin', superadmin.token], ] as const) { const res = await rawMutation( 'common.generateUploadUrls', { contextString: 'review', mimeTypes: ['image/png'] }, { token } ) const urls = dataOf(res.body)?.uploadUrls expect({ who: label, ok: isOk(res.body), urls: Array.isArray(urls) && urls.length === 1 }).toEqual({ who: label, ok: true, urls: true, }) } }) it('AUTH-07: every superadmin.* procedure rejects user/staff and accepts superadmin', async () => { const user = await userSession() const staff = await staffSession() const superadmin = await superadminSession() for (const entry of SUPERADMIN_PROCEDURES) { for (const [label, token] of [ ['anon', undefined], ['user', user.token], ['staff', staff.token], ] as const) { const res = await call(entry.proc, entry.method, {}, token) expect({ proc: entry.proc, who: label, code: codeOf(res.body) }).toEqual({ proc: entry.proc, who: label, code: 'UNAUTHORIZED', }) } // Superadmin reaches the resolver; missing input is fine (proves the guard // opened) as long as the guard did not reject. const superRes = await call(entry.proc, entry.method, {}, superadmin.token) expect({ proc: entry.proc, code: codeOf(superRes.body) }).not.toEqual({ proc: entry.proc, code: 'UNAUTHORIZED', }) } }) it('(current) AUTH-08: a staff token on user.order.getOrders 500s instead of being rejected', async () => { const staff = await staffSession() const res = await rawQuery('user.order.getOrders', { page: 1, pageSize: 1 }, { token: staff.token }) expect(codeOf(res.body)).toBe('INTERNAL_SERVER_ERROR') expect(dataOf(res.body)).toBeUndefined() }) it('AUTH-09: a user token on admin.slots.createSlot is rejected', async () => { const user = await userSession() const superadmin = await superadminSession() const input = { deliveryTime: new Date(Date.now() + 5 * 3_600_000).toISOString(), freezeTime: new Date(Date.now() + 4 * 3_600_000).toISOString(), isActive: true, skuIds: [], } const asUser = await rawMutation('admin.slots.createSlot', input, { token: user.token }) expect(codeOf(asUser.body)).toBe('UNAUTHORIZED') const asSuper = await rawMutation('admin.slots.createSlot', input, { token: superadmin.token }) expect(codeOf(asSuper.body)).toBe('UNAUTHORIZED') const asAnon = await rawMutation('admin.slots.createSlot', input) expect(codeOf(asAnon.body)).toBe('UNAUTHORIZED') }) it('AUTH-10: a superadmin token on admin.product.getProducts is rejected (no data leak)', async () => { const superadmin = await superadminSession() const res = await rawQuery('admin.product.getProducts', {}, { token: superadmin.token }) expect(codeOf(res.body)).toBe('UNAUTHORIZED') expect(dataOf(res.body)).toBeUndefined() }) it('(current) AUTH-11: a suspended user is not rejected by tRPC (REST does reject)', async () => { const staff = await staffSession() const throwaway = await registerThrowawayUser() await rawMutation( 'admin.user.updateUserSuspension', { userId: throwaway.userId, isSuspended: true }, { token: staff.token } ) try { const adminRead = await rawQuery('user.address.getUserAddresses', {}, { token: throwaway.token }) // (current) see HARNESS-13: suspension is swallowed by createContext, so the // user endpoints keep responding. expect(isOk(adminRead.body)).toBe(true) const restRes = await rest('/api/test', { headers: { Authorization: `Bearer ${throwaway.token}` } }) expect(restRes.status).toBe(403) } finally { await rawMutation( 'admin.user.updateUserSuspension', { userId: throwaway.userId, isSuspended: false }, { token: staff.token } ) } }) it('AUTH-12: expired user/staff/superadmin tokens are 401 on protected tRPC', async () => { const user = await userSession() const staff = await staffSession() const superadmin = await superadminSession() const secret = jwtSecret() const past = Math.floor(Date.now() / 1000) - 3_600 const expiredUser = await signToken({ userId: user.userId }, secret, past) const expiredStaff = await signToken({ staffId: staff.staffId }, secret, past) const expiredSuper = await signToken( { superadminId: superadmin.superadminId, identityType: 'superadmin' }, secret, past ) // Positive control: the same signing routine with a future `exp` produces a // token the backend accepts, so the 401s below are about expiry. const liveUser = await signToken({ userId: user.userId }, secret, Math.floor(Date.now() / 1000) + 3_600) expect(isOk((await rawQuery('user.user.getSelfData', {}, { token: liveUser })).body)).toBe(true) expect(codeOf((await rawQuery('user.user.getSelfData', {}, { token: expiredUser })).body)).toBe( 'UNAUTHORIZED' ) expect(codeOf((await rawQuery('admin.staffUser.me', {}, { token: expiredStaff })).body)).toBe( 'UNAUTHORIZED' ) expect(codeOf((await rawQuery('superadmin.auth.me', {}, { token: expiredSuper })).body)).toBe( 'UNAUTHORIZED' ) // Public procedures ignore the (invalid) token. expect(isOk((await rawQuery('common.healthCheck', {}, { token: expiredUser })).body)).toBe(true) // (current) the REST middleware lets the jose error escape as a 500 instead // of mapping an expired token to 401. const restRes = await rest('/api/test', { headers: { Authorization: `Bearer ${expiredUser}` } }) expect(restRes.status).toBe(500) }) it('AUTH-13: a token forged with the wrong secret is 401 on protected tRPC', async () => { const user = await userSession() const future = Math.floor(Date.now() / 1000) + 3_600 const forged = await signToken({ userId: user.userId }, 'definitely-not-the-secret', future) expect(codeOf((await rawQuery('user.user.getSelfData', {}, { token: forged })).body)).toBe( 'UNAUTHORIZED' ) expect(codeOf((await rawQuery('user.order.getOrders', { page: 1, pageSize: 1 }, { token: forged })).body)).toBe( 'UNAUTHORIZED' ) expect(isOk((await rawQuery('common.healthCheck', {}, { token: forged })).body)).toBe(true) // (current) same REST mismatch as AUTH-12. const restRes = await rest('/api/test', { headers: { Authorization: `Bearer ${forged}` } }) expect(restRes.status).toBe(500) }) it('(current) AUTH-14: a user token on common.getStoresSummary 500s and leaks no stores', async () => { const user = await userSession() const staff = await staffSession() const anon = await rawQuery('common.getStoresSummary', {}) expect(codeOf(anon.body)).toBe('UNAUTHORIZED') const staffRes = await rawQuery('common.getStoresSummary', {}, { token: staff.token }) expect(isOk(staffRes.body)).toBe(true) expect(Array.isArray(dataOf(staffRes.body)?.stores)).toBe(true) const userRes = await rawQuery('common.getStoresSummary', {}, { token: user.token }) // (current) protectedProcedure lets the user token through; the resolver then // dereferences ctx.staffUser.regionId -> 500, and no stores are returned. expect(codeOf(userRes.body)).toBe('INTERNAL_SERVER_ERROR') expect(dataOf(userRes.body)).toBeUndefined() }) })