Merge pull request 'feat(auth): clean expired revoked tokens' (#2) from feat/task-54-revocation-cleanup into master
Reviewed-on: agent-codex/liqa#2
This commit is contained in:
commit
9e4b692444
3 files changed
+194
No files matched your search
@@ -6,6 +6,7 @@ import { AuthGuard } from "./auth.guard";
|
|||||||
import { AuthService } from "./auth.service";
|
import { AuthService } from "./auth.service";
|
||||||
import { PasswordService } from "./password.service";
|
import { PasswordService } from "./password.service";
|
||||||
import { RevokedTokenEntity } from "./revoked-token.entity";
|
import { RevokedTokenEntity } from "./revoked-token.entity";
|
||||||
|
import { RevokedTokenCleanupService } from "./revoked-token-cleanup.service";
|
||||||
import { UserEntity } from "./user.entity";
|
import { UserEntity } from "./user.entity";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
@@ -14,6 +15,7 @@ import { UserEntity } from "./user.entity";
|
|||||||
providers: [
|
providers: [
|
||||||
AuthService,
|
AuthService,
|
||||||
PasswordService,
|
PasswordService,
|
||||||
|
RevokedTokenCleanupService,
|
||||||
{ provide: APP_GUARD, useClass: AuthGuard },
|
{ provide: APP_GUARD, useClass: AuthGuard },
|
||||||
],
|
],
|
||||||
exports: [AuthService, PasswordService],
|
exports: [AuthService, PasswordService],
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { Injectable, OnModuleInit } from "@nestjs/common";
|
||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { SchedulerRegistry } from "@nestjs/schedule";
|
||||||
|
import { InjectRepository } from "@nestjs/typeorm";
|
||||||
|
import { CronJob } from "cron";
|
||||||
|
import { LessThanOrEqual, Repository } from "typeorm";
|
||||||
|
import { TraceLogger } from "../common/trace-logger";
|
||||||
|
import { AppConfig } from "../config/app.config";
|
||||||
|
import { RevokedTokenEntity } from "./revoked-token.entity";
|
||||||
|
|
||||||
|
export const AUTH_REVOKED_TOKEN_CLEANUP_JOB = "auth-revoked-token-cleanup";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RevokedTokenCleanupService implements OnModuleInit {
|
||||||
|
private readonly logger = new TraceLogger(RevokedTokenCleanupService.name);
|
||||||
|
private readonly enabled: boolean;
|
||||||
|
private readonly cleanupCron: string;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectRepository(RevokedTokenEntity)
|
||||||
|
private readonly revokedTokens: Repository<RevokedTokenEntity>,
|
||||||
|
config: ConfigService<AppConfig, true>,
|
||||||
|
private readonly schedulerRegistry: SchedulerRegistry,
|
||||||
|
) {
|
||||||
|
this.enabled = config.get("AUTH_ENABLED");
|
||||||
|
this.cleanupCron = config.get("AUTH_REVOKED_TOKEN_CLEANUP_CRON");
|
||||||
|
}
|
||||||
|
|
||||||
|
async onModuleInit(): Promise<void> {
|
||||||
|
if (!this.enabled) return;
|
||||||
|
|
||||||
|
const job = CronJob.from({
|
||||||
|
cronTime: this.cleanupCron,
|
||||||
|
start: false,
|
||||||
|
waitForCompletion: true,
|
||||||
|
onTick: async () => {
|
||||||
|
try {
|
||||||
|
await this.cleanupExpiredTokens();
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to clean up expired revoked tokens: ${this.errorMessage(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
this.schedulerRegistry.addCronJob(AUTH_REVOKED_TOKEN_CLEANUP_JOB, job);
|
||||||
|
job.start();
|
||||||
|
this.logger.debug(
|
||||||
|
`Revoked-token cleanup cron registered: ${this.cleanupCron}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.cleanupExpiredTokens();
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.error(
|
||||||
|
`Failed to clean up expired revoked tokens at startup: ${this.errorMessage(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async cleanupExpiredTokens(): Promise<void> {
|
||||||
|
if (!this.enabled) return;
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const result = await this.revokedTokens.delete({
|
||||||
|
expiresAt: LessThanOrEqual(now),
|
||||||
|
});
|
||||||
|
if (result.affected) {
|
||||||
|
this.logger.debug(`Cleaned up ${result.affected} expired revoked tokens`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private errorMessage(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { SchedulerRegistry } from "@nestjs/schedule";
|
||||||
|
import { CronJob } from "cron";
|
||||||
|
import { DataSource, Repository } from "typeorm";
|
||||||
|
import { AppConfig } from "../src/config/app.config";
|
||||||
|
import { dataSourceOptions } from "../src/database/data-source";
|
||||||
|
import { RevokedTokenEntity } from "../src/auth/revoked-token.entity";
|
||||||
|
import {
|
||||||
|
AUTH_REVOKED_TOKEN_CLEANUP_JOB,
|
||||||
|
RevokedTokenCleanupService,
|
||||||
|
} from "../src/auth/revoked-token-cleanup.service";
|
||||||
|
|
||||||
|
describe("RevokedTokenCleanupService", () => {
|
||||||
|
let dataSource: DataSource;
|
||||||
|
let repository: Repository<RevokedTokenEntity>;
|
||||||
|
let addCronJob: jest.Mock;
|
||||||
|
let registry: SchedulerRegistry;
|
||||||
|
|
||||||
|
async function createService(
|
||||||
|
enabled: boolean,
|
||||||
|
cron = "0 3 * * *",
|
||||||
|
): Promise<RevokedTokenCleanupService> {
|
||||||
|
const config = {
|
||||||
|
get: jest.fn((key: keyof AppConfig) => {
|
||||||
|
if (key === "AUTH_ENABLED") return enabled;
|
||||||
|
if (key === "AUTH_REVOKED_TOKEN_CLEANUP_CRON") return cron;
|
||||||
|
throw new Error(`Unexpected config key ${key}`);
|
||||||
|
}),
|
||||||
|
} as unknown as ConfigService<AppConfig, true>;
|
||||||
|
|
||||||
|
return new RevokedTokenCleanupService(repository, config, registry);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
dataSource = new DataSource(dataSourceOptions(":memory:"));
|
||||||
|
await dataSource.initialize();
|
||||||
|
await dataSource.runMigrations();
|
||||||
|
repository = dataSource.getRepository(RevokedTokenEntity);
|
||||||
|
addCronJob = jest.fn();
|
||||||
|
registry = { addCronJob } as unknown as SchedulerRegistry;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(async () => {
|
||||||
|
await dataSource.destroy();
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("deletes only expired revocations, including expiry at the current instant", async () => {
|
||||||
|
const now = new Date("2026-11-05T12:00:00.000Z");
|
||||||
|
jest.useFakeTimers().setSystemTime(now);
|
||||||
|
await repository.insert([
|
||||||
|
{ tokenHash: "a".repeat(64), expiresAt: new Date(now.getTime() - 1) },
|
||||||
|
{ tokenHash: "b".repeat(64), expiresAt: now },
|
||||||
|
{ tokenHash: "c".repeat(64), expiresAt: new Date(now.getTime() + 1) },
|
||||||
|
]);
|
||||||
|
|
||||||
|
const service = await createService(true);
|
||||||
|
await service.cleanupExpiredTokens();
|
||||||
|
|
||||||
|
const retained = await repository.find();
|
||||||
|
expect(retained.map(({ tokenHash }) => tokenHash)).toEqual([
|
||||||
|
"c".repeat(64),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("tolerates an empty table and repeated cleanup runs", async () => {
|
||||||
|
const service = await createService(true);
|
||||||
|
|
||||||
|
await expect(service.cleanupExpiredTokens()).resolves.toBeUndefined();
|
||||||
|
await expect(service.cleanupExpiredTokens()).resolves.toBeUndefined();
|
||||||
|
await expect(repository.count()).resolves.toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("cleans at startup and registers the configured in-process cron job", async () => {
|
||||||
|
const now = new Date("2026-11-05T12:00:00.000Z");
|
||||||
|
jest.useFakeTimers().setSystemTime(now);
|
||||||
|
await repository.insert({
|
||||||
|
tokenHash: "d".repeat(64),
|
||||||
|
expiresAt: new Date(now.getTime() - 1),
|
||||||
|
});
|
||||||
|
const service = await createService(true, "*/5 * * * *");
|
||||||
|
|
||||||
|
await service.onModuleInit();
|
||||||
|
|
||||||
|
expect(addCronJob).toHaveBeenCalledTimes(1);
|
||||||
|
expect(addCronJob).toHaveBeenCalledWith(
|
||||||
|
AUTH_REVOKED_TOKEN_CLEANUP_JOB,
|
||||||
|
expect.any(CronJob),
|
||||||
|
);
|
||||||
|
expect(await repository.count()).toBe(0);
|
||||||
|
|
||||||
|
const job = addCronJob.mock.calls[0][1] as CronJob;
|
||||||
|
expect(job.cronTime.source).toBe("*/5 * * * *");
|
||||||
|
await repository.insert({
|
||||||
|
tokenHash: "e".repeat(64),
|
||||||
|
expiresAt: new Date(now.getTime() - 1),
|
||||||
|
});
|
||||||
|
await job.fireOnTick();
|
||||||
|
expect(await repository.count()).toBe(0);
|
||||||
|
job.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not schedule or write cleanup data when authentication is disabled", async () => {
|
||||||
|
const service = await createService(false);
|
||||||
|
await repository.insert({
|
||||||
|
tokenHash: "f".repeat(64),
|
||||||
|
expiresAt: new Date("2020-01-01T00:00:00.000Z"),
|
||||||
|
});
|
||||||
|
|
||||||
|
await service.onModuleInit();
|
||||||
|
await service.cleanupExpiredTokens();
|
||||||
|
|
||||||
|
expect(addCronJob).not.toHaveBeenCalled();
|
||||||
|
expect(await repository.count()).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user