diff --git a/.github/workflows/pull-web.yml b/.github/workflows/pull-web.yml index 5d3b81103..f8807384e 100644 --- a/.github/workflows/pull-web.yml +++ b/.github/workflows/pull-web.yml @@ -18,6 +18,8 @@ jobs: node-version: 26 - name: Install modules run: npm install + - name: Run M1 account authorization regression tests + run: node --test tests/m1-*.test.cjs - name: Run svelte checks run: npm run check - name: Check linting diff --git a/materialious/src/lib/server/user.ts b/materialious/src/lib/server/user.ts index 13fc23807..b684e0583 100644 --- a/materialious/src/lib/server/user.ts +++ b/materialious/src/lib/server/user.ts @@ -63,7 +63,8 @@ export class User { async removeSubscription(id: string) { await getSequelize().ChannelSubscriptionTable.destroy({ where: { - id + id, + UserId: this.id } }); } @@ -72,7 +73,8 @@ export class User { return ( (await getSequelize().ChannelSubscriptionTable.count({ where: { - id + id, + UserId: this.id } })) > 0 ); @@ -81,7 +83,7 @@ export class User { async subscriptions(): Promise { const subscriptions = await getSequelize().ChannelSubscriptionTable.findAll({ where: { - userId: this.data.id + UserId: this.id } }); diff --git a/materialious/src/routes/api/user/history/+server.ts b/materialious/src/routes/api/user/history/+server.ts index 4b4c1fbf3..5cd2e0638 100644 --- a/materialious/src/routes/api/user/history/+server.ts +++ b/materialious/src/routes/api/user/history/+server.ts @@ -125,6 +125,8 @@ export async function GET({ locals, url }) { } export async function DELETE({ locals }) { + if (!locals.userId) throw error(401, 'Unauthorized'); + await getSequelize().UserHistoryTable.destroy({ where: { UserId: locals.userId diff --git a/materialious/src/routes/api/user/logout/+server.ts b/materialious/src/routes/api/user/logout/+server.ts index 84a04ffb9..68ae59158 100644 --- a/materialious/src/routes/api/user/logout/+server.ts +++ b/materialious/src/routes/api/user/logout/+server.ts @@ -1,5 +1,5 @@ export function DELETE({ cookies }) { - cookies.delete('userid', { path: '/' }); + cookies.delete('userid', { path: '/api' }); return new Response(); } diff --git a/materialious/src/routes/api/user/subscriptions/+server.ts b/materialious/src/routes/api/user/subscriptions/+server.ts index 13e2682d8..1c755f72c 100644 --- a/materialious/src/routes/api/user/subscriptions/+server.ts +++ b/materialious/src/routes/api/user/subscriptions/+server.ts @@ -1,6 +1,8 @@ import { getUser } from '#lib/server/user'; +import { error } from '@sveltejs/kit'; export async function GET({ locals }) { + if (!locals.userId) error(401, 'Unauthorized'); const user = await getUser(locals.userId); return Response.json({ diff --git a/materialious/src/routes/api/user/subscriptions/[id]/+server.ts b/materialious/src/routes/api/user/subscriptions/[id]/+server.ts index 6c458a33c..421a74a68 100644 --- a/materialious/src/routes/api/user/subscriptions/[id]/+server.ts +++ b/materialious/src/routes/api/user/subscriptions/[id]/+server.ts @@ -10,6 +10,7 @@ const zSubscriptionCreate = z.object({ }); export async function POST({ locals, request, params }) { + if (!locals.userId) error(401, 'Unauthorized'); const subscription = zSubscriptionCreate.safeParse(await request.json()); if (!subscription.success) error(400); @@ -25,6 +26,7 @@ export async function POST({ locals, request, params }) { } export async function PATCH({ locals, params }) { + if (!locals.userId) error(401, 'Unauthorized'); const user = await getUser(locals.userId); await user.subscriptionRssUpdated(params.id); @@ -32,6 +34,7 @@ export async function PATCH({ locals, params }) { } export async function DELETE({ locals, params }) { + if (!locals.userId) error(401, 'Unauthorized'); const user = await getUser(locals.userId); await user.removeSubscription(params.id); @@ -39,6 +42,7 @@ export async function DELETE({ locals, params }) { } export async function GET({ locals, params }) { + if (!locals.userId) error(401, 'Unauthorized'); const user = await getUser(locals.userId); return Response.json({ diff --git a/materialious/tests/m1-account-boundaries.test.cjs b/materialious/tests/m1-account-boundaries.test.cjs new file mode 100644 index 000000000..f43c2fb49 --- /dev/null +++ b/materialious/tests/m1-account-boundaries.test.cjs @@ -0,0 +1,277 @@ +/* eslint-disable @typescript-eslint/no-require-imports -- Node CommonJS test harness loads transpiled modules with require stubs. */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const crypto = require('node:crypto'); +const ts = require('typescript'); + +// Run the actual unmodified TypeScript module bodies with only their external +// dependencies replaced by local stubs. No network, user accounts or live DB. +function loadTypeScript(relativePath, dependencies) { + const file = path.join(__dirname, '../src', relativePath); + const source = fs.readFileSync(file, 'utf8'); + const transpiled = ts.transpileModule(source, { + compilerOptions: { + module: ts.ModuleKind.CommonJS, + target: ts.ScriptTarget.ES2022, + esModuleInterop: true + }, + fileName: file, + reportDiagnostics: true + }); + const errors = (transpiled.diagnostics || []).filter( + (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error + ); + assert.equal(errors.length, 0, 'TypeScript transpilation failed'); + + const module = { exports: {} }; + vm.runInNewContext( + transpiled.outputText, + { + module, + exports: module.exports, + require(name) { + if (!Object.hasOwn(dependencies, name)) { + throw new Error('Unexpected import in regression test: ' + name); + } + return dependencies[name]; + }, + Response, + TextEncoder, + Buffer + }, + { filename: file, timeout: 5000 } + ); + return module.exports; +} + +function fakeSubscriptionDatabase(initialRecords) { + const records = initialRecords.map((record) => ({ ...record })); + const matches = (record, where) => + Object.entries(where).every(([field, value]) => record[field] === value); + + return { + records, + sequelize: { + ChannelSubscriptionTable: { + async count({ where }) { + return records.filter((record) => matches(record, where)).length; + }, + async destroy({ where }) { + let deleted = 0; + for (let index = records.length - 1; index >= 0; index -= 1) { + if (matches(records[index], where)) { + records.splice(index, 1); + deleted += 1; + } + } + return deleted; + }, + async findAll({ where }) { + return records.filter((record) => matches(record, where)); + } + } + } + }; +} + +function userWithFakeDatabase(initialRecords) { + const database = fakeSubscriptionDatabase(initialRecords); + const { User } = loadTypeScript('lib/server/user.ts', { + './database': { getSequelize: () => database.sequelize }, + sequelize: { Op: { or: Symbol.for('m1-test-or') } }, + crypto, + '@sveltejs/kit': { + error(code) { + const exception = new Error('SvelteKit HTTP ' + code); + exception.status = code; + throw exception; + } + }, + '#lib/auth/userCreateError': { USERNAME_TAKEN: 'Username taken' } + }); + return { database, User }; +} + +test('subscription checks cannot reveal a record owned by another user', async () => { + const { database, User } = userWithFakeDatabase([ + { id: 'subscription-owned-by-b', UserId: 'user-b' }, + { id: 'subscription-owned-by-a', UserId: 'user-a' } + ]); + const actorA = new User({ id: 'user-a', username: 'user-a' }); + const actorB = new User({ id: 'user-b', username: 'user-b' }); + + assert.equal(await actorA.amSubscribed('subscription-owned-by-b'), false); + assert.equal(await actorA.amSubscribed('subscription-owned-by-a'), true); + assert.equal(await actorB.amSubscribed('subscription-owned-by-b'), true); + assert.equal(database.records.length, 2); +}); + +test('subscription deletion cannot change records owned by another user', async () => { + const { database, User } = userWithFakeDatabase([ + { id: 'subscription-owned-by-b', UserId: 'user-b' } + ]); + const actorA = new User({ id: 'user-a', username: 'user-a' }); + const actorB = new User({ id: 'user-b', username: 'user-b' }); + + await actorA.removeSubscription('subscription-owned-by-b'); + assert.equal(database.records.length, 1); + assert.equal(database.records[0].UserId, 'user-b'); + + await actorB.removeSubscription('subscription-owned-by-b'); + assert.equal(database.records.length, 0); +}); + +test('subscription listing consistently uses the database UserId foreign key', async () => { + const { User } = userWithFakeDatabase([ + { id: 'a-only', UserId: 'user-a' }, + { id: 'b-only', UserId: 'user-b' } + ]); + const actorA = new User({ id: 'user-a', username: 'user-a' }); + const results = await actorA.subscriptions(); + assert.equal(results.length, 1); + assert.equal(results[0].id, 'a-only'); +}); + +function unauthorizedDependencies() { + const unauthorized = () => { + const exception = new Error('Unauthorized'); + exception.status = 401; + throw exception; + }; + return { + '#lib/server/user': { + getUser: async () => { + throw new Error('getUser must not be called without authentication'); + } + }, + '@sveltejs/kit': { error: unauthorized }, + zod: { + string: () => ({ max: () => ({}) }), + object: () => ({ + safeParse: () => { + throw new Error('Request body must not be read without authentication'); + } + }) + } + }; +} + +test('anonymous subscription collection requests return HTTP 401', async () => { + const routes = loadTypeScript('routes/api/user/subscriptions/+server.ts', unauthorizedDependencies()); + await assert.rejects(routes.GET({ locals: {} }), (error) => error.status === 401); +}); + +test('anonymous subscription item methods reject before any request parsing', async () => { + const routes = loadTypeScript('routes/api/user/subscriptions/[id]/+server.ts', unauthorizedDependencies()); + for (const method of ['GET', 'POST', 'PATCH', 'DELETE']) { + await assert.rejects( + routes[method]({ locals: {}, params: { id: 'any' } }), + (error) => error.status === 401, + method + ' must return 401 before querying user content' + ); + } +}); + +test('logout deletes the same path used for the authentication cookie', () => { + const cookieSet = []; + const cookieDeleted = []; + + const misc = loadTypeScript('lib/server/misc.ts', { + 'cookie-signature': { sign: (id) => 'signed_' + id }, + '$app/env/private': { COOKIE_SECRET: 'test-only-cookie-secret' } + }); + const logout = loadTypeScript('routes/api/user/logout/+server.ts', {}); + + misc.setAuthCookie('disposable-user', { + set: (name, value, options) => cookieSet.push({ name, path: options.path }) + }); + logout.DELETE({ + cookies: { + delete: (name, options) => cookieDeleted.push({ name, path: options.path }) + } + }); + assert.equal(cookieSet.length, 1); + assert.equal(cookieDeleted.length, 1); + assert.equal(cookieDeleted[0].name, cookieSet[0].name); + assert.equal(cookieDeleted[0].path, cookieSet[0].path); +}); + +function historyRouteWithRows(initialRows) { + const records = initialRows.map((row) => ({ ...row })); + const calls = []; + const database = { + UserHistoryTable: { + async findAll(options) { + calls.push({ method: 'findAll', where: options.where }); + return records.filter((row) => row.UserId === options.where.UserId); + }, + async destroy(options) { + calls.push({ method: 'destroy', where: options.where }); + for (let i = records.length - 1; i >= 0; i -= 1) { + if (records[i].UserId === options.where.UserId) records.splice(i, 1); + } + } + } + }; + // Build only the schema declarations needed to load the real route. + // Unauthorized requests must be rejected before payload parsing or DB access. + const schema = { max() { return this; }, optional() { return this; } }; + const zod = { + object: () => schema, + string: () => schema, + number: () => schema, + coerce: { date: () => schema } + }; + const routes = loadTypeScript('routes/api/user/history/+server.ts', { + '#lib/server/database': { getSequelize: () => database }, + '@sveltejs/kit': { + error(status) { throw Object.assign(new Error('HTTP error'), { status }); } + }, + zod, + sequelize: { Op: { in: Symbol.for('m1-history-in'), lt: Symbol.for('m1-history-lt') } }, + '$app/env/private': { HISTORY_CULLING: '-1' } + }); + return { routes, records, calls }; +} + +test('anonymous history methods return 401 without database access', async () => { + const { routes, records, calls } = historyRouteWithRows([ + { id: 'a-video', UserId: 'user-a' } + ]); + const isUnauthorized = (exception) => exception.status === 401; + + await assert.rejects( + routes.GET({ locals: {}, url: new URL('http://localhost/api/user/history') }), + isUnauthorized + ); + await assert.rejects( + routes.POST({ + locals: {}, + request: { async json() { throw new Error('Anonymous body must not be parsed'); } } + }), + isUnauthorized + ); + await assert.rejects(routes.DELETE({ locals: {} }), isUnauthorized); + assert.equal(calls.length, 0); + assert.equal(records.length, 1); +}); + +test('history route reads and deletes only the authenticated owner records', async () => { + const { routes, records, calls } = historyRouteWithRows([ + { id: 'a-video', UserId: 'user-a' }, + { id: 'b-video', UserId: 'user-b' } + ]); + const url = new URL('http://localhost/api/user/history'); + const accountA = await routes.GET({ locals: { userId: 'user-a' }, url }); + const accountB = await routes.GET({ locals: { userId: 'user-b' }, url }); + assert.deepEqual((await accountA.json()).map((row) => row.id), ['a-video']); + assert.deepEqual((await accountB.json()).map((row) => row.id), ['b-video']); + + await routes.DELETE({ locals: { userId: 'user-a' } }); + assert.deepEqual(records.map((row) => row.id), ['b-video']); + assert.deepEqual(calls.map((call) => call.where.UserId), + ['user-a', 'user-b', 'user-a']); +}); diff --git a/materialious/tests/m1-database-ownership.test.cjs b/materialious/tests/m1-database-ownership.test.cjs new file mode 100644 index 000000000..854bb25ec --- /dev/null +++ b/materialious/tests/m1-database-ownership.test.cjs @@ -0,0 +1,104 @@ +/* eslint-disable @typescript-eslint/no-require-imports -- Node CommonJS test harness loads transpiled modules with require stubs. */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const crypto = require('node:crypto'); +const ts = require('typescript'); +const { Sequelize, DataTypes, Op } = require('sequelize'); +const sqlite3 = require('sqlite3'); + +function loadActualUserModule(getSequelize) { + const file = path.resolve(__dirname, '../src/lib/server/user.ts'); + const compiled = ts.transpileModule(fs.readFileSync(file, 'utf8'), { + fileName: file, + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true } + }).outputText; + const module = { exports: {} }; + vm.runInNewContext(compiled, { + module, + exports: module.exports, + require(name) { + if (name === './database') return { getSequelize }; + if (name === 'sequelize') return { Op }; + if (name === 'crypto') return crypto; + if (name === '@sveltejs/kit') return { error(status) { throw Object.assign(new Error('HTTP error'), { status }); } }; + if (name === '#lib/auth/userCreateError') return { USERNAME_TAKEN: 'Username taken' }; + throw new Error('Unexpected import: ' + name); + }, + TextEncoder, + Buffer + }, { filename: file, timeout: 5000 }); + return module.exports.User; +} + +async function fixture(t) { + // In-memory SQLite with the same UserId association used by Materialious. + // No filesystem database, live session or network is involved. + const sequelize = new Sequelize({ dialect: 'sqlite', storage: ':memory:', logging: false, dialectModule: sqlite3 }); + t.after(async () => sequelize.close()); + const UserTable = sequelize.define('User', { + id: { type: DataTypes.UUID, primaryKey: true, allowNull: false }, + username: { type: DataTypes.STRING, allowNull: false, unique: true } + }); + const ChannelSubscriptionTable = sequelize.define('Subscriptions', { + id: { type: DataTypes.STRING, primaryKey: true, allowNull: false }, + channelIdCipher: { type: DataTypes.STRING, allowNull: false }, + channelIdNonce: { type: DataTypes.STRING, allowNull: false }, + channelNameCipher: { type: DataTypes.STRING, allowNull: false }, + channelNameNonce: { type: DataTypes.STRING, allowNull: false }, + lastRSSFetch: { type: DataTypes.DATE, allowNull: false } + }); + UserTable.hasMany(ChannelSubscriptionTable); + await sequelize.sync({ force: true }); + + const a = crypto.randomUUID(); + const b = crypto.randomUUID(); + await UserTable.bulkCreate([{ id: a, username: 'test-a' }, { id: b, username: 'test-b' }]); + const User = loadActualUserModule(() => ({ ChannelSubscriptionTable })); + const actorA = new User({ id: a, username: 'test-a' }); + const actorB = new User({ id: b, username: 'test-b' }); + + const subscription = (id, owner) => ({ + id, + UserId: owner, + channelIdCipher: 'cipher', + channelIdNonce: 'nonce', + channelNameCipher: 'cipher', + channelNameNonce: 'nonce', + lastRSSFetch: new Date(0) + }); + + return { actorA, actorB, ChannelSubscriptionTable, a, b, subscription }; +} + +test('real SQLite queries keep subscriptions separated by owner', async (t) => { + const { actorA, actorB, ChannelSubscriptionTable, a, b, subscription } = await fixture(t); + await ChannelSubscriptionTable.bulkCreate([ + subscription('subscription-a', a), + subscription('subscription-b', b) + ]); + + assert.equal(await actorA.amSubscribed('subscription-b'), false); + assert.equal(await actorA.amSubscribed('subscription-a'), true); + assert.equal(await actorB.amSubscribed('subscription-a'), false); + + const aList = await actorA.subscriptions(); + const bList = await actorB.subscriptions(); + assert.deepEqual(Array.from(aList, (item) => item.get('id')), ['subscription-a']); + assert.deepEqual(Array.from(bList, (item) => item.get('id')), ['subscription-b']); + + // Updating the RSS timestamp must not touch another user's subscription. + await actorA.subscriptionRssUpdated('subscription-b'); + const unchanged = await ChannelSubscriptionTable.findByPk('subscription-b'); + assert.equal(unchanged.get('lastRSSFetch').getTime(), 0); + await actorB.subscriptionRssUpdated('subscription-b'); + const updated = await ChannelSubscriptionTable.findByPk('subscription-b'); + assert.ok(updated.get('lastRSSFetch').getTime() > 0); + + await actorA.removeSubscription('subscription-b'); + assert.equal(await ChannelSubscriptionTable.count({ where: { id: 'subscription-b' } }), 1); + await actorB.removeSubscription('subscription-b'); + assert.equal(await ChannelSubscriptionTable.count({ where: { id: 'subscription-b' } }), 0); +});