fix: revoke session in shared cache before database to keep replicas consistent

This commit is contained in:
2026-11-01 14:57:41 +03:00
parent e9bc51288b
commit 53035d475f
4 changed files with 64 additions and 25 deletions
+8 -1
View File
@@ -99,8 +99,15 @@ export class AuthService {
}
async revoke(tokenHash: string): Promise<void> {
const marked = await this.cache.setStrict(
cacheKey(tokenHash),
REVOKED,
CACHE_TTL_MS,
);
if (!marked) {
throw new ApiError('unavailable', 'session cache unavailable');
}
await this.prisma.session.deleteMany({ where: { tokenHash } });
await this.cache.set(cacheKey(tokenHash), REVOKED, CACHE_TTL_MS);
}
}
+16
View File
@@ -66,6 +66,22 @@ export class CacheService implements OnModuleDestroy {
}
}
async setStrict(key: string, value: string, ttlMs: number): Promise<boolean> {
if (!this.client) {
return true;
}
if (!this.trusted) {
return false;
}
try {
await this.client.set(key, value, 'PX', ttlMs);
return true;
} catch {
this.distrust();
return false;
}
}
onModuleDestroy(): void {
this.client?.disconnect();
}
+7 -1
View File
@@ -184,7 +184,13 @@ export const OPERATION_EXAMPLES: Record<string, OperationExamples> = {
'DELETE /api/v1/auth/sessions/current': {
responses: {
'401': UNAUTHORIZED,
'503': UNAVAILABLE,
'503': {
...UNAVAILABLE,
cache: example(
'Redis недоступен — отзыв не выполнен, повторите позже',
error('unavailable', 'session cache unavailable'),
),
},
},
},
'GET /api/v1/users/me': {
+33 -23
View File
@@ -41,46 +41,56 @@ describe('Уровень 4: expiry, отказы зависимостей, rollb
expect(res.headers['www-authenticate']).toBe('Bearer realm="messenger"');
});
it('без Redis вход, проверка сессии и logout работают через PostgreSQL', async () => {
it('без Redis вход и проверка сессии работают через PostgreSQL, logout — 503 без отзыва', async () => {
const { server } = await start({ CACHE_URL: UNREACHABLE_REDIS });
const user = await registerUser(server, 'noredis');
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(200);
await request(server)
const res = await request(server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(204);
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(401);
await request(server).get('/api/v1/users/me').expect(401);
});
it('logout при обрыве связи с Redis не оставляет рабочий токен после её восстановления', async () => {
const { app, server } = await start();
const user = await registerUser(server, 'partition');
.expect(503);
expect(res.body.error.code).toBe('unavailable');
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(200);
const cache = app.get(CacheService) as any;
await request(server).get('/api/v1/users/me').expect(401);
});
it('logout через реплику без связи с Redis не создаёт расхождения с репликой, у которой сессия в кэше', async () => {
const a = await start();
const b = await start();
const user = await registerUser(a.server, 'partition');
const me = (server: any, status: number) =>
request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(status);
const logout = (status: number) =>
request(a.server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(status);
const cache = a.app.get(CacheService) as any;
const redis = cache.client as Redis;
expect((await redis.keys('session:v1:*')).length).toBeGreaterThan(0);
await me(b.server, 200);
redis.disconnect();
await request(server)
.delete('/api/v1/auth/sessions/current')
.set('Authorization', bearer(user))
.expect(204);
await logout(503);
await me(b.server, 200);
await me(a.server, 200);
await redis.connect();
await sleep(200);
await request(server)
.get('/api/v1/users/me')
.set('Authorization', bearer(user))
.expect(401);
expect(cache.trusted).toBe(true);
await me(b.server, 200);
expect((await redis.keys('session:v1:*')).length).toBeGreaterThan(0);
await logout(204);
await me(b.server, 401);
await me(a.server, 401);
});
it('без PostgreSQL отвечает ограниченным 503 и не пускает анонима', async () => {