Skip to content
Open
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
32 changes: 28 additions & 4 deletions back-end/libs/common/src/blacklist/blacklist.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { createHash } from 'crypto';

import { Test, TestingModule } from '@nestjs/testing';
import { ConfigService } from '@nestjs/config';
import { Redis } from 'ioredis';
Expand All @@ -6,6 +8,9 @@ import { mockDeep } from 'jest-mock-extended';
import { BlacklistService } from '@app/common';
import { REDIS_CLIENT } from '@app/common';

const hashKey = (jwt: string) =>
`blacklisted:token:${createHash('sha256').update(jwt).digest('hex')}`;

describe('BlacklistService', () => {
let service: BlacklistService;
const configService = mockDeep<ConfigService>();
Expand Down Expand Up @@ -43,7 +48,13 @@ describe('BlacklistService', () => {

await service.blacklistToken(jwt);

expect(client.set).toHaveBeenCalledWith(jwt, 'blacklisted', 'EX', expirationSeconds);
expect(client.set).toHaveBeenCalledWith(
hashKey(jwt),
'blacklisted',
'EX',
expirationSeconds,
);
expect(client.set).not.toHaveBeenCalledWith(jwt, expect.anything(), 'EX', expect.anything());
});
});

Expand All @@ -69,12 +80,19 @@ describe('BlacklistService', () => {
it('should return true if the token is blacklisted', async () => {
const jwt = 'testToken';

client.get.mockResolvedValue('blacklisted');
client.get.mockImplementation(async key => (key === hashKey(jwt) ? 'blacklisted' : null));

const result = await service.isTokenBlacklisted(jwt);

expect(result).toBe(true);
expect(client.get).toHaveBeenCalledWith(jwt);
});

it('should return true for a legacy raw-JWT blacklist entry', async () => {
const jwt = 'testToken';

client.get.mockImplementation(async key => (key === jwt ? 'blacklisted' : null));

await expect(service.isTokenBlacklisted(jwt)).resolves.toBe(true);
});

it('should return false if the token is not blacklisted', async () => {
Expand All @@ -85,7 +103,13 @@ describe('BlacklistService', () => {
const result = await service.isTokenBlacklisted(jwt);

expect(result).toBe(false);
expect(client.get).toHaveBeenCalledWith(jwt);
expect(client.get).toHaveBeenCalledWith(hashKey(jwt));
});

it('should propagate Redis errors so callers fail closed', async () => {
client.get.mockRejectedValue(new Error('redis down'));

await expect(service.isTokenBlacklisted('testToken')).rejects.toThrow('redis down');
});

it('should reject a JWT issued before the user was removed', async () => {
Expand Down
18 changes: 15 additions & 3 deletions back-end/libs/common/src/blacklist/blacklist.service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

import { createHash } from 'crypto';

import { Redis } from 'ioredis';

import { REDIS_CLIENT } from '../redis/redis-client.module';
Expand All @@ -9,6 +11,7 @@ import { REDIS_CLIENT } from '../redis/redis-client.module';
export class BlacklistService {
private BLACKLISTED = 'blacklisted';
private USER_INVALID_BEFORE_PREFIX = 'blacklisted:user:';
private TOKEN_PREFIX = 'blacklisted:token:';

// The shared connection's lifecycle (including closing it on shutdown) is
// owned by RedisClientModule, not this service.
Expand All @@ -19,7 +22,7 @@ export class BlacklistService {

async blacklistToken(jwt: string | null) {
if (jwt !== null) {
await this.client.set(jwt, this.BLACKLISTED, 'EX', this.getJwtExpirationSeconds());
await this.client.set(this.getTokenKey(jwt), this.BLACKLISTED, 'EX', this.getJwtExpirationSeconds());
}
}

Expand All @@ -38,8 +41,12 @@ export class BlacklistService {
}

async isTokenBlacklisted(jwt: string) {
const data = await this.client.get(jwt);
if (data === this.BLACKLISTED) {
const [hashed, legacy] = await Promise.all([
this.client.get(this.getTokenKey(jwt)),
// TODO: remove once all legacy raw-JWT keys have expired (JWT_EXPIRATION after deploy).
this.client.get(jwt),
]);
if (hashed === this.BLACKLISTED || legacy === this.BLACKLISTED) {
return true;
}

Expand All @@ -66,6 +73,11 @@ export class BlacklistService {
return Number(expirationDays) * 24 * 60 * 60;
}

/* Only a one-way fingerprint is stored so Redis contents can never be replayed as credentials. */
private getTokenKey(jwt: string): string {
return `${this.TOKEN_PREFIX}${createHash('sha256').update(jwt).digest('hex')}`;
}

private getUserInvalidationKey(userId: number): string {
return `${this.USER_INVALID_BEFORE_PREFIX}${userId}`;
}
Expand Down
Loading