Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/pull-web.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 5 additions & 3 deletions materialious/src/lib/server/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ export class User {
async removeSubscription(id: string) {
await getSequelize().ChannelSubscriptionTable.destroy({
where: {
id
id,
UserId: this.id
}
});
}
Expand All @@ -72,7 +73,8 @@ export class User {
return (
(await getSequelize().ChannelSubscriptionTable.count({
where: {
id
id,
UserId: this.id
}
})) > 0
);
Expand All @@ -81,7 +83,7 @@ export class User {
async subscriptions(): Promise<ChannelSubscriptionModel[]> {
const subscriptions = await getSequelize().ChannelSubscriptionTable.findAll({
where: {
userId: this.data.id
UserId: this.id
}
});

Expand Down
2 changes: 2 additions & 0 deletions materialious/src/routes/api/user/history/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion materialious/src/routes/api/user/logout/+server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export function DELETE({ cookies }) {
cookies.delete('userid', { path: '/' });
cookies.delete('userid', { path: '/api' });

return new Response();
}
2 changes: 2 additions & 0 deletions materialious/src/routes/api/user/subscriptions/+server.ts
Original file line number Diff line number Diff line change
@@ -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({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -25,20 +26,23 @@ 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);

return new Response();
}

export async function DELETE({ locals, params }) {
if (!locals.userId) error(401, 'Unauthorized');
const user = await getUser(locals.userId);
await user.removeSubscription(params.id);

return new Response();
}

export async function GET({ locals, params }) {
if (!locals.userId) error(401, 'Unauthorized');
const user = await getUser(locals.userId);

return Response.json({
Expand Down
277 changes: 277 additions & 0 deletions materialious/tests/m1-account-boundaries.test.cjs
Original file line number Diff line number Diff line change
@@ -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']);
});
Loading
Loading