mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
fix(sessions): close only the sockets of the session that ended
A ws token now carries the session it was minted under and the socket keeps it, so signing out on one device no longer drops the live socket of every other device. Ending all sessions still closes every socket of the account.
This commit is contained in:
@@ -529,7 +529,7 @@ describe('AuthController (authenticated)', () => {
|
||||
for (let i = 0; i < 120; i++) await s.check('ws_token', String(user.id), 120, 15 * 60 * 1000, now);
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user),
|
||||
ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req),
|
||||
),
|
||||
).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
// The login bucket is untouched: an exhausted socket loop must not lock the account out.
|
||||
@@ -551,15 +551,17 @@ describe('AuthController (authenticated)', () => {
|
||||
// Both users sit behind the same NAT address, and the first one burns its
|
||||
// whole ceiling.
|
||||
for (let i = 0; i < 120; i++) {
|
||||
await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user);
|
||||
await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req);
|
||||
}
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user),
|
||||
ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req),
|
||||
),
|
||||
).toEqual({ status: 429, body: { error: 'Too many attempts. Please try again later.' } });
|
||||
|
||||
expect(await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws2' }) }).wsToken(other)).toEqual({
|
||||
expect(
|
||||
await ac(asvc({}), s, { createWsToken: vi.fn().mockReturnValue({ token: 'ws2' }) }).wsToken(other, req),
|
||||
).toEqual({
|
||||
token: 'ws2',
|
||||
});
|
||||
expect(
|
||||
@@ -944,12 +946,25 @@ describe('AuthController (authenticated)', () => {
|
||||
it('ws-token maps error, else returns the token', async () => {
|
||||
expect(
|
||||
await thrownAsync(() =>
|
||||
ac(asvc({}), rl(), { createWsToken: vi.fn().mockRejectedValue(new DomainError(503, 'down')) }).wsToken(user),
|
||||
ac(asvc({}), rl(), { createWsToken: vi.fn().mockRejectedValue(new DomainError(503, 'down')) }).wsToken(
|
||||
user,
|
||||
req,
|
||||
),
|
||||
),
|
||||
).toEqual({ status: 503, body: { error: 'down' } });
|
||||
expect(await ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user)).toEqual(
|
||||
{ token: 'ws' },
|
||||
);
|
||||
expect(
|
||||
await ac(asvc({}), rl(), { createWsToken: vi.fn().mockReturnValue({ token: 'ws' }) }).wsToken(user, req),
|
||||
).toEqual({ token: 'ws' });
|
||||
});
|
||||
|
||||
it('ws-token is minted under the session of the request, so ending that session closes its socket', async () => {
|
||||
const createWsToken = vi.fn().mockReturnValue({ token: 'ws' });
|
||||
const ctl = ac(asvc({}), rl(), { createWsToken });
|
||||
await ctl.wsToken(user, req);
|
||||
expect(createWsToken).toHaveBeenLastCalledWith(1, undefined);
|
||||
const tracked = jwt.sign({ id: 1, pv: 0 }, JWT_SECRET, { algorithm: 'HS256', jwtid: 'sid-ws' });
|
||||
await ctl.wsToken(user, { ip: '9.9.9.9', headers: {}, cookies: { trek_session: tracked } } as unknown as Request);
|
||||
expect(createWsToken).toHaveBeenLastCalledWith(1, 'sid-ws');
|
||||
});
|
||||
|
||||
it('avatar saves when not in demo mode (env present but email is not a demo email)', async () => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
joinBook,
|
||||
leaveBook,
|
||||
broadcastToUser,
|
||||
closeSockets,
|
||||
getOnlineUserIds,
|
||||
joinRoom,
|
||||
registerSocket,
|
||||
@@ -309,6 +310,20 @@ describe('RealtimeGateway heartbeat', () => {
|
||||
pong![1]();
|
||||
expect(ws.isAlive).toBe(true);
|
||||
});
|
||||
|
||||
it('WSGW-023: the socket keeps the session its token was minted under, so it closes with that session only', async () => {
|
||||
consumeWithMeta.mockReturnValue({ userId: 3, pv: 2, session: 'sess-a' });
|
||||
const { ws: a } = await connect('/ws?token=x');
|
||||
consumeWithMeta.mockReturnValue({ userId: 3, pv: 2, session: 'sess-b' });
|
||||
const { ws: b } = await connect('/ws?token=y');
|
||||
setServer({ clients: new Set([a, b]) } as never);
|
||||
|
||||
closeSockets(4001, 'Session ended', 3, 'sess-a');
|
||||
|
||||
expect(a.closedWith).toEqual([4001, 'Session ended']);
|
||||
expect(b.closedWith).toBeNull();
|
||||
setServer(null);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ws-state fan-out', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* WSREV-001 to WSREV-012: a socket is let into a room with one access check,
|
||||
* WSREV-001 to WSREV-017: a socket is let into a room with one access check,
|
||||
* so the writes that end access ask the sockets already in again
|
||||
* (recheckTripAccess, recheckJourneyAccess), and the sockets of a user whose
|
||||
* sessions ended, or of every user once the database was replaced, are
|
||||
@@ -54,9 +54,9 @@ let rooms: InMemoryRoomRegistry;
|
||||
let clients: Set<FakeSocket>;
|
||||
|
||||
/** A socket of the user, open and registered, as the handshake leaves it. */
|
||||
function open(userId: number): FakeSocket {
|
||||
function open(userId: number, sessionId?: string): FakeSocket {
|
||||
const ws = socket();
|
||||
registerSocket(ws, { id: userId, username: `u${userId}` } as User);
|
||||
registerSocket(ws, { id: userId, username: `u${userId}` } as User, sessionId);
|
||||
clients.add(ws);
|
||||
return ws;
|
||||
}
|
||||
@@ -219,6 +219,22 @@ describe('closeSockets', () => {
|
||||
expect(theirs.sent).toContainEqual(expect.objectContaining({ type: 'journey:book:peers' }));
|
||||
});
|
||||
|
||||
it('WSREV-017: one ended session closes its own sockets and those of no known session, never another device', async () => {
|
||||
const ended = open(1, 'sess-a');
|
||||
const otherDevice = open(1, 'sess-b');
|
||||
const unknown = open(1);
|
||||
const theirs = open(2, 'sess-a');
|
||||
rooms.join(otherDevice, 5);
|
||||
|
||||
new RealtimeService().closeSessionSockets(1, 'sess-a', 'Session ended');
|
||||
|
||||
expect(ended.closedWith).toEqual([4001, 'Session ended']);
|
||||
expect(unknown.closedWith).toEqual([4001, 'Session ended']);
|
||||
expect(otherDevice.closedWith).toBeNull();
|
||||
expect(theirs.closedWith).toBeNull();
|
||||
expect(rooms.members(5)?.has(otherDevice)).toBe(true);
|
||||
});
|
||||
|
||||
it('WSREV-012: without a user closes every socket, which a replaced database asks for', async () => {
|
||||
const a = open(1);
|
||||
const b = open(2);
|
||||
|
||||
@@ -299,22 +299,27 @@ describe('SessionsService list and revoke', () => {
|
||||
expect(await svc.revokeAll(user.id)).toBe(1);
|
||||
});
|
||||
|
||||
it('SESS-019: ending sessions ends the user’s open sockets too, and nothing when no session ended', async () => {
|
||||
const close = vi.spyOn(RealtimeService.prototype, 'closeUserSockets').mockImplementation(() => undefined);
|
||||
it('SESS-019: ending sessions ends their open sockets too, and nothing when no session ended', async () => {
|
||||
const closeAll = vi.spyOn(RealtimeService.prototype, 'closeUserSockets').mockImplementation(() => undefined);
|
||||
const closeOne = vi.spyOn(RealtimeService.prototype, 'closeSessionSockets').mockImplementation(() => undefined);
|
||||
const { user } = createUser(testDb);
|
||||
const a = claimsOf(await svc.issue({ id: user.id, pv: 0 }));
|
||||
const b = claimsOf(await svc.issue({ id: user.id, pv: 0 }));
|
||||
|
||||
// One session ended: only its sockets, the other device stays connected.
|
||||
expect(await svc.revoke(user.id, a.jti)).toBe(true);
|
||||
expect(close).toHaveBeenLastCalledWith(user.id, 'Session ended');
|
||||
expect(closeOne).toHaveBeenLastCalledWith(user.id, a.jti, 'Session ended');
|
||||
expect(closeAll).not.toHaveBeenCalled();
|
||||
expect(await svc.revokeAll(user.id)).toBe(1);
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
expect(closeAll).toHaveBeenLastCalledWith(user.id, 'Session ended');
|
||||
|
||||
// Nothing left to end: the sockets stay.
|
||||
expect(await svc.revoke(user.id, b.jti)).toBe(false);
|
||||
expect(await svc.revokeAll(user.id)).toBe(0);
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
close.mockRestore();
|
||||
expect(closeOne).toHaveBeenCalledTimes(1);
|
||||
expect(closeAll).toHaveBeenCalledTimes(1);
|
||||
closeAll.mockRestore();
|
||||
closeOne.mockRestore();
|
||||
});
|
||||
|
||||
it('SESS-010: endSession ends the session a token names, and nothing for an untracked or missing token', async () => {
|
||||
|
||||
@@ -365,6 +365,13 @@ describe('ephemeral tokens', () => {
|
||||
expect(createEphemeralToken).toHaveBeenCalledWith(99999, 'ws', { pv: 0 });
|
||||
});
|
||||
|
||||
it('TOKEN-021: createWsToken carries the session it was asked under, so the socket can close with it', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(createEphemeralToken).mockReturnValueOnce('ws-tok');
|
||||
await asLegacyResult(svc.createWsToken(user.id, 'sess-1'));
|
||||
expect(createEphemeralToken).toHaveBeenCalledWith(user.id, 'ws', { pv: 0, session: 'sess-1' });
|
||||
});
|
||||
|
||||
it('TOKEN-008: createWsToken reports 503 when the store refuses', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
vi.mocked(createEphemeralToken).mockReturnValueOnce(null as unknown as string);
|
||||
|
||||
Reference in New Issue
Block a user