diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 245c90e7..c7bafd26 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -99,8 +99,15 @@ export class AuthService { } async revoke(tokenHash: string): Promise { + 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); } } diff --git a/src/cache/cache.service.ts b/src/cache/cache.service.ts index b429706b..0c7c0cde 100644 --- a/src/cache/cache.service.ts +++ b/src/cache/cache.service.ts @@ -66,6 +66,22 @@ export class CacheService implements OnModuleDestroy { } } + async setStrict(key: string, value: string, ttlMs: number): Promise { + 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(); } diff --git a/src/docs/examples.ts b/src/docs/examples.ts index 5478c5aa..8440ce43 100644 --- a/src/docs/examples.ts +++ b/src/docs/examples.ts @@ -184,7 +184,13 @@ export const OPERATION_EXAMPLES: Record = { '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': { diff --git a/test/failures.e2e-spec.ts b/test/failures.e2e-spec.ts index 7118f57a..72d39854 100644 --- a/test/failures.e2e-spec.ts +++ b/test/failures.e2e-spec.ts @@ -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 () => {