Skip to content
Merged
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
11 changes: 11 additions & 0 deletions CONFORMANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,14 @@ binding changes, and the in-review statuses above remain in review.
dates, adjacent-crop conflicts, resize impact, portable round-tripping, invalid
imports, and storage errors. This is feature verification, not a claim that the
delegated JFA invariants are now enforced by this repository.
Private application chat uses the verified backend account `userId` as an
immutable conversation owner. Conversation/message routes and attachment
downloads enforce that boundary; shared integration keys supply no participant
identity. Legacy ownerless rows remain inaccessible pending explicit operator
assignment. Bindings: `backend/middleware/chatAuth.js`,
`conversationOwner.js`, `attachmentOwner.js`, the conditional conversation
model writes, and `backend/__tests__/conversationAccess.test.js`. This does not
promote private chat to a sealed commons dialog or change the in-review ledger
claims above. Legacy SSE endpoints remain retired with HTTP 410 until the
companion authenticated-stream change lands. See `backend/docs/conversation-ownership.md` for migration and client
integration limits.
66 changes: 66 additions & 0 deletions backend/__tests__/attachmentStorage.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const Message = require('../models/message');

// Same-name writes in the same millisecond must never alias another message.
test('same-name attachments retain distinct bytes and server-generated names', async () => {
Message.setDocClient({ put: () => ({ promise: async () => ({}) }) });
const now = Date.now;
const files = [];
Date.now = () => 123456789;
try {
for (const content of ['first', 'second']) {
const msg = await Message.sendMessage('mine', { file: { name: 'same.txt', data: Buffer.from(content).toString('base64') } });
files.push(msg.file);
}
assert.notEqual(files[0].path, files[1].path);
for (const [index, file] of files.entries()) {
assert.match(file.path, /^\/uploads\/[0-9a-f-]{36}\.txt$/);
assert.equal(file.originalname, 'same.txt');
assert.equal(fs.readFileSync(path.join(__dirname, '..', file.path), 'utf8'), ['first', 'second'][index]);
}
} finally {
Date.now = now;
for (const file of files) fs.rmSync(path.join(__dirname, '..', file.path), { force: true });
}
});

test('a generated-name collision refuses overwrite and does not persist a second message', async t => {
const crypto = require('node:crypto');
const collisionId = crypto.randomUUID();
const modulePath = require.resolve('../models/message');
const cached = require.cache[modulePath];
const destination = path.join(__dirname, '../uploads', collisionId + '.txt');
t.mock.method(crypto, 'randomUUID', () => collisionId);
delete require.cache[modulePath];
const model = require('../models/message');
const persisted = [];
model.setDocClient({ put: ({ Item }) => ({ promise: async () => { persisted.push(Item); return {}; } }) });
t.after(() => {
require.cache[modulePath] = cached;
fs.rmSync(destination, { force: true });
});
await model.sendMessage('mine', { id: 'first', file: { name: 'same.txt', data: Buffer.from('original').toString('base64') } });
await assert.rejects(model.sendMessage('foreign', {
id: 'second', file: { name: 'same.txt', data: Buffer.from('replacement').toString('base64') },
}), { code: 'EEXIST' });
assert.equal(fs.readFileSync(destination, 'utf8'), 'original');
assert.equal(persisted.length, 1);
assert.equal(persisted[0].id, 'first');
});

test('scoped attachment lookup follows empty filtered pages within its conversation partition', async () => {
let reads = 0;
Message.setDocClient({ query: params => ({ promise: async () => {
assert.equal(params.KeyConditionExpression, 'conversationId = :cid');
assert.deepEqual(params.ExpressionAttributeValues, { ':cid': 'mine', ':filePath': '/uploads/100%.txt' });
reads++;
if (!params.ExclusiveStartKey) return { Items: [], LastEvaluatedKey: { conversationId: 'mine', id: 'first' } };
assert.deepEqual(params.ExclusiveStartKey, { conversationId: 'mine', id: 'first' });
return { Items: [{ file: { path: '/uploads/100%.txt' } }] };
} }) });
assert.equal(await Message.findConversationAttachment('mine', '/uploads/100%.txt'), true);
assert.equal(reads, 2);
});
44 changes: 44 additions & 0 deletions backend/__tests__/chatRateLimit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const request = require('supertest');
const jwt = require('jsonwebtoken');
jest.mock('../lib/dynamodbClient', () => ({
scan: () => ({ promise: async () => ({ Items: [] }) }),
get: () => ({ promise: async () => ({}) }),
}));
jest.mock('../bull/pingJobs', () => ({ addPingJob: jest.fn() }));
jest.mock('../bull/smsQueue', () => ({ enqueueSms: jest.fn() }));
jest.mock('../federation/federationSyncJob', () => jest.fn());

describe('account-keyed rate limits on private routes', () => {
let app;
const originalEnv = { ...process.env };
const globals = Object.fromEntries(['broadcast', 'emitToken', 'emitMessage'].map(key => [key, global[key]]));
const bearer = userId => `Bearer ${jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '1h' })}`;
beforeAll(() => {
process.env.MINIMAL_SERVER = 'false';
process.env.JWT_SECRET = 'rate-test-secret';
({ app } = require('../server'));
});
afterAll(() => {
process.env = originalEnv;
for (const [key, value] of Object.entries(globals)) {
if (value === undefined) delete global[key]; else global[key] = value;
}
});
test.each(['/conversations', '/messages/missing', '/uploads/missing.txt'])('%s rejects excess requests per verified account', async path => {
expect((await request(app).get(path)).status).toBe(403);
const account = 'limit-' + path;
const first = await request(app).get(path).set('Authorization', bearer(account));
expect(first.status).not.toBe(429);
expect(first.headers['ratelimit-limit']).toBeDefined();
const limit = Number(first.headers['ratelimit-limit']);
expect(limit).toBeGreaterThan(0);
for (let i = 1; i < limit; i++) {
const result = await request(app).get(path).set('Authorization', bearer(account));
expect(result.status).not.toBe(429);
}
const blocked = await request(app).get(path).set('Authorization', bearer(account));
expect(blocked.status).toBe(429);
expect(Number(blocked.headers['retry-after'])).toBeGreaterThan(0);
expect((await request(app).get(path).set('Authorization', bearer('another-' + path))).status).not.toBe(429);
});
});
65 changes: 65 additions & 0 deletions backend/__tests__/chatSharedRateLimit.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const { test } = require('node:test');
const assert = require('node:assert/strict');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const { randomUUID } = require('node:crypto');
const path = require('node:path');
const jwt = require('jsonwebtoken');

// Explicit integration run: CHAT_LIMIT_REDIS_URL must name disposable local Redis.
test('separate chat server processes share the verified account request budget', {
skip: !process.env.CHAT_LIMIT_REDIS_URL,
timeout: 30000,
}, async t => {
const redisUrl = new URL(process.env.CHAT_LIMIT_REDIS_URL);
assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(redisUrl.hostname));
const secret = 'local-chat-limit-integration-secret';
const account = randomUUID();
const workers = [];
t.after(async () => {
await Promise.all(workers.map(async child => {
if (child.exitCode === null) {
const exited = once(child, 'exit');
child.kill();
await exited;
}
}));
});
const source = `
const express = require('express');
const db = require('./lib/dynamodbClient');
db.scan = () => ({ promise: async () => ({ Items: [] }) });
const app = express();
app.use('/conversations', require('./routes/conversationRoutes'));
const redis = require('./middleware/rateLimit').getRedisClient();
const listen = () => {
const server = app.listen(0, '127.0.0.1', () => process.send(server.address().port));
};
if (redis.status === 'ready') listen(); else redis.once('ready', listen);
`;
const ports = [];
for (let i = 0; i < 2; i++) {
const child = spawn(process.execPath, ['-e', source], {
cwd: path.resolve(__dirname, '..'),
env: { ...process.env, REDIS_URL: redisUrl.href, RATE_LIMIT_REDIS_REQUIRED: 'true', JWT_SECRET: secret },
stdio: ['ignore', 'ignore', 'inherit', 'ipc'],
});
workers.push(child);
ports.push((await once(child, 'message'))[0]);
}
async function read(index, userId = account) {
const token = jwt.sign({ userId }, secret, { expiresIn: '1h', jwtid: randomUUID() });
return fetch(`http://127.0.0.1:${ports[index]}/conversations`, {
headers: { Authorization: `Bearer ${token}` },
});
}
for (let i = 0; i < 120; i++) {
const response = await read(i % 2);
assert.equal(response.status, 200, `request ${i + 1}`);
assert.deepEqual(await response.json(), []);
}
const denied = await read(0);
assert.equal(denied.status, 429, 'renewing tokens or switching servers must not reset the account budget');
assert.ok(Number(denied.headers.get('retry-after')) > 0);
assert.equal((await read(1, randomUUID())).status, 200, 'another account retains its own budget');
});
5 changes: 3 additions & 2 deletions backend/__tests__/conversation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ test('removing a conversation deletes its messages', async () => {
const tables = { Conversations: [], Messages: [] };
const mockClient = {
put: ({ TableName, Item }) => ({ promise: async () => { tables[TableName].push(Item); } }),
get: ({ TableName, Key }) => ({ promise: async () => ({ Item: tables[TableName].find(item => item.id === Key.id) }) }),
scan: ({ TableName }) => ({ promise: async () => ({ Items: tables[TableName] }) }),
update: ({ TableName, Key, UpdateExpression, ExpressionAttributeValues }) => ({
promise: async () => {
Expand Down Expand Up @@ -36,10 +37,10 @@ test('removing a conversation deletes its messages', async () => {
Conversation.setDocClient(mockClient);
Message.setDocClient(mockClient);

await mockClient.put({ TableName: 'Conversations', Item: { id: '1', title: 'seed', pinned: false, createdAt: new Date().toISOString() } }).promise();
await mockClient.put({ TableName: 'Conversations', Item: { id: '1', ownerId: 'owner', title: 'seed', pinned: false, createdAt: new Date().toISOString() } }).promise();
await mockClient.put({ TableName: 'Messages', Item: { id: 'm1', conversationId: '1', content: 'hi' } }).promise();

await Conversation.remove('1');
await Conversation.remove('1', 'owner');
const msgs = await Message.listMessages('1');
assert.equal(msgs.length, 0);
});
Expand Down
Loading
Loading