autonomous.contact/tests/api/rooms/events/create_events.test.ts

123 lines
3.1 KiB
TypeScript

import * as asserts from 'jsr:@std/assert';
import { EPHEMERAL_SERVER, get_ephemeral_listen_server, get_new_user, set_user_permissions } from '../../../helpers.ts';
import { api, API_CLIENT } from '../../../../utils/api.ts';
import { generateTotp } from '@stdext/crypto/totp';
import { clear_room_events_cache } from '../../../../models/event.ts';
Deno.test({
name: 'API - ROOMS - EVENTS - Create',
permissions: {
env: true,
read: true,
write: true,
net: true
},
fn: async () => {
let test_server_info: EPHEMERAL_SERVER | null = null;
try {
test_server_info = await get_ephemeral_listen_server();
const client: API_CLIENT = api({
prefix: '/api',
hostname: test_server_info.hostname,
port: test_server_info.port
});
const owner_info = await get_new_user(client);
await set_user_permissions(client, owner_info.user, owner_info.session, [...owner_info.user.permissions, 'rooms.create']);
const room = await client.fetch('/rooms', {
method: 'POST',
headers: {
'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret)
},
json: {
name: 'test events room',
permissions: {
write_events: [owner_info.user.id]
}
}
});
asserts.assert(room);
const event_from_owner = await client.fetch(`/rooms/${room.id}/events`, {
method: 'POST',
headers: {
'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret)
},
json: {
type: 'test',
data: {
foo: 'bar'
}
}
});
asserts.assert(event_from_owner);
const other_user_info = await get_new_user(client);
try {
const _permission_denied_room = await client.fetch(`/rooms/${room.id}/events`, {
method: 'POST',
headers: {
'x-session_id': other_user_info.session.id,
'x-totp': await generateTotp(other_user_info.session.secret)
},
json: {
type: 'test',
data: {
other_user: true
}
}
});
asserts.fail('allowed adding an event to a room without permission');
} catch (error) {
asserts.assertEquals((error as Error).cause, 'permission_denied');
}
// make the room public write
const updated_by_owner_room = await client.fetch(`/rooms/${room.id}`, {
method: 'PUT',
headers: {
'x-session_id': owner_info.session.id,
'x-totp': await generateTotp(owner_info.session.secret)
},
json: {
permissions: {
...room.permissions,
write_events: []
}
}
});
asserts.assert(updated_by_owner_room);
asserts.assertEquals(updated_by_owner_room.permissions.write_events, []);
const event_from_other_user = await client.fetch(`/rooms/${room.id}/events`, {
method: 'POST',
headers: {
'x-session_id': other_user_info.session.id,
'x-totp': await generateTotp(other_user_info.session.secret)
},
json: {
type: 'test',
data: {
other_user: true
}
}
});
asserts.assert(event_from_other_user);
} finally {
clear_room_events_cache();
if (test_server_info) {
await test_server_info?.server?.stop();
}
}
}
});