diff --git a/packages/@n8n/backend-test-utils/src/test-db.ts b/packages/@n8n/backend-test-utils/src/test-db.ts index 3d86f52aad4..936b85b2dec 100644 --- a/packages/@n8n/backend-test-utils/src/test-db.ts +++ b/packages/@n8n/backend-test-utils/src/test-db.ts @@ -106,7 +106,8 @@ type EntityName = | 'UserConsent' | 'DynamicCredentialEntry' | 'DynamicCredentialResolver' - | 'DynamicCredentialUserEntry'; + | 'DynamicCredentialUserEntry' + | 'TokenExchangeJti'; /** * Truncate specific DB tables in a test DB. diff --git a/packages/@n8n/db/src/migrations/common/1775116241000-CreateTokenExchangeJtiTable.ts b/packages/@n8n/db/src/migrations/common/1775116241000-CreateTokenExchangeJtiTable.ts new file mode 100644 index 00000000000..032570ddfcd --- /dev/null +++ b/packages/@n8n/db/src/migrations/common/1775116241000-CreateTokenExchangeJtiTable.ts @@ -0,0 +1,17 @@ +import type { MigrationContext, ReversibleMigration } from '../migration-types'; + +const tableName = 'token_exchange_jti'; + +export class CreateTokenExchangeJtiTable1775116241000 implements ReversibleMigration { + async up({ schemaBuilder: { createTable, column } }: MigrationContext) { + await createTable(tableName).withColumns( + column('jti').varchar(255).primary, + column('expiresAt').timestamp().notNull, + column('createdAt').timestamp().notNull, + ); + } + + async down({ schemaBuilder: { dropTable } }: MigrationContext) { + await dropTable(tableName); + } +} diff --git a/packages/@n8n/db/src/migrations/postgresdb/index.ts b/packages/@n8n/db/src/migrations/postgresdb/index.ts index c9bbd2e2f3d..428a59a6506 100644 --- a/packages/@n8n/db/src/migrations/postgresdb/index.ts +++ b/packages/@n8n/db/src/migrations/postgresdb/index.ts @@ -157,6 +157,7 @@ import { CreateCredentialDependencyTable1773000000000 } from '../common/17730000 import { AddRestoreFieldsToWorkflowBuilderSession1774280963551 } from '../common/1774280963551-AddRestoreFieldsToWorkflowBuilderSession'; import { CreateInstanceVersionHistoryTable1774854660000 } from '../common/1774854660000-CreateInstanceVersionHistoryTable'; import { CreateInstanceAiTables1775000000000 } from '../common/1775000000000-CreateInstanceAiTables'; +import { CreateTokenExchangeJtiTable1775116241000 } from '../common/1775116241000-CreateTokenExchangeJtiTable'; import type { Migration } from '../migration-types'; export const postgresMigrations: Migration[] = [ @@ -319,4 +320,5 @@ export const postgresMigrations: Migration[] = [ AddRestoreFieldsToWorkflowBuilderSession1774280963551, CreateInstanceVersionHistoryTable1774854660000, CreateInstanceAiTables1775000000000, + CreateTokenExchangeJtiTable1775116241000, ]; diff --git a/packages/@n8n/db/src/migrations/sqlite/index.ts b/packages/@n8n/db/src/migrations/sqlite/index.ts index d6e0929de75..89836e753dd 100644 --- a/packages/@n8n/db/src/migrations/sqlite/index.ts +++ b/packages/@n8n/db/src/migrations/sqlite/index.ts @@ -151,6 +151,7 @@ import { CreateCredentialDependencyTable1773000000000 } from '../common/17730000 import { AddRestoreFieldsToWorkflowBuilderSession1774280963551 } from '../common/1774280963551-AddRestoreFieldsToWorkflowBuilderSession'; import { CreateInstanceVersionHistoryTable1774854660000 } from '../common/1774854660000-CreateInstanceVersionHistoryTable'; import { CreateInstanceAiTables1775000000000 } from '../common/1775000000000-CreateInstanceAiTables'; +import { CreateTokenExchangeJtiTable1775116241000 } from '../common/1775116241000-CreateTokenExchangeJtiTable'; import type { Migration } from '../migration-types'; const sqliteMigrations: Migration[] = [ @@ -307,6 +308,7 @@ const sqliteMigrations: Migration[] = [ AddRestoreFieldsToWorkflowBuilderSession1774280963551, CreateInstanceVersionHistoryTable1774854660000, CreateInstanceAiTables1775000000000, + CreateTokenExchangeJtiTable1775116241000, ]; export { sqliteMigrations }; diff --git a/packages/cli/src/modules/token-exchange/__tests__/token-exchange.controller.test.ts b/packages/cli/src/modules/token-exchange/__tests__/token-exchange.controller.test.ts index 468666e8065..0cc180e8187 100644 --- a/packages/cli/src/modules/token-exchange/__tests__/token-exchange.controller.test.ts +++ b/packages/cli/src/modules/token-exchange/__tests__/token-exchange.controller.test.ts @@ -32,6 +32,8 @@ describe('TokenExchangeController', () => { jest.resetAllMocks(); tokenExchangeConfig.enabled = true; tokenExchangeConfig.maxTokenTtl = 900; + tokenExchangeConfig.jtiCleanupIntervalSeconds = 60; + tokenExchangeConfig.jtiCleanupBatchSize = 1000; req = mock({ ip: '127.0.0.1' }); res = mock(); res.status.mockReturnThis(); diff --git a/packages/cli/src/modules/token-exchange/controllers/embed-auth.controller.ts b/packages/cli/src/modules/token-exchange/controllers/embed-auth.controller.ts index 880d79b5e82..3310cc25a70 100644 --- a/packages/cli/src/modules/token-exchange/controllers/embed-auth.controller.ts +++ b/packages/cli/src/modules/token-exchange/controllers/embed-auth.controller.ts @@ -1,4 +1,5 @@ import { EmbedLoginBodyDto, EmbedLoginQueryDto } from '@n8n/api-types'; +import { Time } from '@n8n/constants'; import { Body, Get, Post, Query, RestController } from '@n8n/decorators'; import type { Response } from 'express'; @@ -16,12 +17,18 @@ export class EmbedAuthController { private readonly urlService: UrlService, ) {} - @Get('/', { skipAuth: true }) + @Get('/', { + skipAuth: true, + ipRateLimit: { limit: 20, windowMs: 1 * Time.minutes.toMilliseconds }, + }) async getLogin(req: AuthlessRequest, res: Response, @Query query: EmbedLoginQueryDto) { return await this.handleLogin(query.token, req, res); } - @Post('/', { skipAuth: true }) + @Post('/', { + skipAuth: true, + ipRateLimit: { limit: 20, windowMs: 1 * Time.minutes.toMilliseconds }, + }) async postLogin(req: AuthlessRequest, res: Response, @Body body: EmbedLoginBodyDto) { return await this.handleLogin(body.token, req, res); } diff --git a/packages/cli/src/modules/token-exchange/database/entities/token-exchange-jti.entity.ts b/packages/cli/src/modules/token-exchange/database/entities/token-exchange-jti.entity.ts new file mode 100644 index 00000000000..2c104486592 --- /dev/null +++ b/packages/cli/src/modules/token-exchange/database/entities/token-exchange-jti.entity.ts @@ -0,0 +1,14 @@ +import { DateTimeColumn } from '@n8n/db'; +import { Entity, PrimaryColumn } from '@n8n/typeorm'; + +@Entity('token_exchange_jti') +export class TokenExchangeJti { + @PrimaryColumn({ type: 'varchar', length: 255 }) + jti: string; + + @DateTimeColumn() + expiresAt: Date; + + @DateTimeColumn() + createdAt: Date; +} diff --git a/packages/cli/src/modules/token-exchange/database/repositories/token-exchange-jti.repository.ts b/packages/cli/src/modules/token-exchange/database/repositories/token-exchange-jti.repository.ts new file mode 100644 index 00000000000..dfb118146a5 --- /dev/null +++ b/packages/cli/src/modules/token-exchange/database/repositories/token-exchange-jti.repository.ts @@ -0,0 +1,126 @@ +import { GlobalConfig } from '@n8n/config'; +import { Service } from '@n8n/di'; +import { DataSource, Repository } from '@n8n/typeorm'; +import assert from 'node:assert'; + +import { TokenExchangeJti } from '../entities/token-exchange-jti.entity'; + +@Service() +export class TokenExchangeJtiRepository extends Repository { + private readonly dbType: 'postgresdb' | 'sqlite'; + + private readonly escapedTableName: string; + + constructor(dataSource: DataSource, globalConfig: GlobalConfig) { + super(TokenExchangeJti, dataSource.manager); + this.dbType = globalConfig.database.type; + const { schema, tableName } = this.metadata; + const esc = (name: string) => dataSource.driver.escape(name); + this.escapedTableName = schema ? `${esc(schema)}.${esc(tableName)}` : esc(tableName); + } + + /** + * Atomically consume a JTI. Returns `true` if this is the first use + * (row inserted), `false` if already consumed (replay attempt). + * + * Postgres uses a CTE with INSERT...RETURNING + EXISTS in a single query. + * SQLite uses a transactional 2-query approach (INSERT OR IGNORE + SELECT + * changes()) because the sqlite-pooled driver dispatches WITH-prefixed + * queries via `.all()` instead of `.run()`, which breaks DML execution. + */ + async atomicConsume(jti: string, expiresAt: Date): Promise { + const esc = (name: string) => this.manager.connection.driver.escape(name); + const tableName = this.escapedTableName; + + if (this.dbType === 'postgresdb') { + const [row] = (await this.query( + `WITH ins AS ( + INSERT INTO ${tableName} (${esc('jti')}, ${esc('expiresAt')}, ${esc('createdAt')}) + VALUES ($1, $2, NOW()) + ON CONFLICT (${esc('jti')}) DO NOTHING + RETURNING ${esc('jti')} + ) + SELECT EXISTS (SELECT 1 FROM ins) AS inserted`, + [jti, expiresAt], + )) as Array<{ inserted: boolean }>; + + return row.inserted; + } else if (this.dbType === 'sqlite') { + const qr = this.manager.connection.createQueryRunner(); + await qr.startTransaction(); + try { + await qr.query( + `INSERT OR IGNORE INTO ${tableName} (${esc('jti')}, ${esc('expiresAt')}, ${esc('createdAt')}) VALUES (?, datetime(?), datetime('now'))`, + [jti, expiresAt.toISOString()], + ); + const [{ cnt }] = (await qr.query('SELECT changes() as cnt')) as Array<{ + cnt: number; + }>; + await qr.commitTransaction(); + return cnt > 0; + } catch (e) { + await qr.rollbackTransaction(); + throw e; + } finally { + await qr.release(); + } + } + + assert.fail('Unknown database type'); + } + + /** + * Delete expired JTI rows in batches. Returns the number of deleted rows. + * + * Postgres uses a CTE with DELETE...RETURNING + COUNT(*) in a single query. + * SQLite uses a transactional 2-query approach (DELETE + SELECT changes()) + * for the same reason as atomicConsume (see above). + */ + async deleteExpiredBatch(batchSize: number): Promise { + const esc = (name: string) => this.manager.connection.driver.escape(name); + const tableName = this.escapedTableName; + + if (this.dbType === 'postgresdb') { + const [row] = (await this.query( + `WITH deleted AS ( + DELETE FROM ${tableName} + WHERE ${esc('jti')} IN ( + SELECT ${esc('jti')} FROM ${tableName} + WHERE ${esc('expiresAt')} < NOW() + LIMIT $1 + ) + RETURNING ${esc('jti')} + ) + SELECT COUNT(*) AS ${esc('count')} FROM deleted`, + [batchSize], + )) as Array<{ count: string | number }>; + + return Number(row.count); + } else if (this.dbType === 'sqlite') { + const qr = this.manager.connection.createQueryRunner(); + await qr.startTransaction(); + try { + await qr.query( + `DELETE FROM ${tableName} WHERE ${esc('jti')} IN ( + SELECT ${esc('jti')} FROM ${tableName} + WHERE ${esc('expiresAt')} < datetime('now') + LIMIT ? + )`, + [batchSize], + ); + const [{ cnt }] = (await qr.query('SELECT changes() as cnt')) as Array<{ + cnt: number; + }>; + await qr.commitTransaction(); + return Number(cnt); + } catch (e) { + await qr.rollbackTransaction(); + throw e; + } finally { + await qr.release(); + } + } + + assert.fail('Unknown database type'); + } +} diff --git a/packages/cli/src/modules/token-exchange/services/__tests__/jti-cleanup.service.test.ts b/packages/cli/src/modules/token-exchange/services/__tests__/jti-cleanup.service.test.ts new file mode 100644 index 00000000000..aa63db5edcf --- /dev/null +++ b/packages/cli/src/modules/token-exchange/services/__tests__/jti-cleanup.service.test.ts @@ -0,0 +1,149 @@ +import type { Logger } from '@n8n/backend-common'; +import type { TokenExchangeConfig } from '../../token-exchange.config'; +import { mock } from 'jest-mock-extended'; +import type { InstanceSettings } from 'n8n-core'; + +import type { TokenExchangeJtiRepository } from '../../database/repositories/token-exchange-jti.repository'; +import { JtiCleanupService } from '../jti-cleanup.service'; + +const logger = mock({ scoped: jest.fn().mockReturnThis() }); +const config = mock({ + jtiCleanupIntervalSeconds: 30, + jtiCleanupBatchSize: 500, +}); +const jtiRepository = mock(); +const instanceSettings = mock({ isLeader: true }); + +let service: JtiCleanupService; + +beforeEach(() => { + jest.useFakeTimers(); + jest.clearAllMocks(); + service = new JtiCleanupService(logger, config, jtiRepository, instanceSettings); +}); + +afterEach(() => { + service.shutdown(); + jest.useRealTimers(); +}); + +describe('JtiCleanupService', () => { + describe('init', () => { + it('should start cleanup when instance is leader', () => { + jtiRepository.deleteExpiredBatch.mockResolvedValue(0); + Object.assign(instanceSettings, { isLeader: true }); + + service.init(); + jest.advanceTimersByTime(30_000); + + expect(jtiRepository.deleteExpiredBatch).toHaveBeenCalled(); + }); + + it('should not start cleanup when instance is not leader', () => { + Object.assign(instanceSettings, { isLeader: false }); + + service.init(); + jest.advanceTimersByTime(60_000); + + expect(jtiRepository.deleteExpiredBatch).not.toHaveBeenCalled(); + }); + }); + + describe('startCleanup', () => { + it('should schedule cleanup at configured interval', () => { + jtiRepository.deleteExpiredBatch.mockResolvedValue(0); + + service.startCleanup(); + + expect(jtiRepository.deleteExpiredBatch).not.toHaveBeenCalled(); + + jest.advanceTimersByTime(30_000); + + expect(jtiRepository.deleteExpiredBatch).toHaveBeenCalledWith(500); + }); + + it('should not start if shutting down', () => { + service.shutdown(); + service.startCleanup(); + + jest.advanceTimersByTime(60_000); + + expect(jtiRepository.deleteExpiredBatch).not.toHaveBeenCalled(); + }); + }); + + describe('cleanup', () => { + it('should log total count when expired JTIs are deleted', async () => { + jtiRepository.deleteExpiredBatch.mockResolvedValue(42); + + service.startCleanup(); + jest.advanceTimersByTime(30_000); + + // Wait for the async cleanup to complete + await jest.advanceTimersByTimeAsync(0); + + expect(logger.scoped).toHaveBeenCalledWith('token-exchange'); + }); + + it('should loop until fewer than batchSize rows are deleted', async () => { + jtiRepository.deleteExpiredBatch + .mockResolvedValueOnce(500) // first batch: full + .mockResolvedValueOnce(500) // second batch: full + .mockResolvedValueOnce(123); // third batch: partial → stop + + service.startCleanup(); + jest.advanceTimersByTime(30_000); + await jest.advanceTimersByTimeAsync(0); + + expect(jtiRepository.deleteExpiredBatch).toHaveBeenCalledTimes(3); + }); + + it('should stop after one call when deleted count is below batchSize', async () => { + jtiRepository.deleteExpiredBatch.mockResolvedValue(10); + + service.startCleanup(); + jest.advanceTimersByTime(30_000); + await jest.advanceTimersByTimeAsync(0); + + expect(jtiRepository.deleteExpiredBatch).toHaveBeenCalledTimes(1); + }); + + it('should catch and log errors without throwing', async () => { + jtiRepository.deleteExpiredBatch.mockRejectedValue(new Error('DB error')); + + service.startCleanup(); + jest.advanceTimersByTime(30_000); + + // Wait for the async cleanup to complete — should not throw + await jest.advanceTimersByTimeAsync(0); + + expect(jtiRepository.deleteExpiredBatch).toHaveBeenCalled(); + }); + }); + + describe('stopCleanup', () => { + it('should stop the cleanup interval on leader stepdown', () => { + jtiRepository.deleteExpiredBatch.mockResolvedValue(0); + + service.startCleanup(); + service.stopCleanup(); + + jest.advanceTimersByTime(60_000); + + expect(jtiRepository.deleteExpiredBatch).not.toHaveBeenCalled(); + }); + }); + + describe('shutdown', () => { + it('should stop the cleanup interval', () => { + jtiRepository.deleteExpiredBatch.mockResolvedValue(0); + + service.startCleanup(); + service.shutdown(); + + jest.advanceTimersByTime(60_000); + + expect(jtiRepository.deleteExpiredBatch).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/cli/src/modules/token-exchange/services/__tests__/token-exchange.service.test.ts b/packages/cli/src/modules/token-exchange/services/__tests__/token-exchange.service.test.ts index 15b82dce665..50b253fa76b 100644 --- a/packages/cli/src/modules/token-exchange/services/__tests__/token-exchange.service.test.ts +++ b/packages/cli/src/modules/token-exchange/services/__tests__/token-exchange.service.test.ts @@ -106,6 +106,20 @@ describe('TokenExchangeService', () => { await expect(service.embedLogin('unknown-kid-token')).rejects.toThrow(AuthError); }); + it('should throw when jwt.verify returns unexpected payload format', async () => { + jest.spyOn(jwt, 'decode').mockReturnValue({ + header: { alg: 'RS256', kid: 'test-kid' }, + payload: validClaims, + signature: 'sig', + } as unknown as ReturnType); + jest + .spyOn(jwt, 'verify') + .mockReturnValue('string-payload' as unknown as ReturnType); + trustedKeyStore.getByKid.mockResolvedValue(resolvedKey); + + await expect(service.embedLogin('string-payload-token')).rejects.toThrow(AuthError); + }); + it('should throw when JWT signature verification fails', async () => { jest.spyOn(jwt, 'decode').mockReturnValue({ header: { alg: 'RS256', kid: 'test-kid' }, diff --git a/packages/cli/src/modules/token-exchange/services/jti-cleanup.service.ts b/packages/cli/src/modules/token-exchange/services/jti-cleanup.service.ts new file mode 100644 index 00000000000..03daec128a0 --- /dev/null +++ b/packages/cli/src/modules/token-exchange/services/jti-cleanup.service.ts @@ -0,0 +1,69 @@ +import { Logger } from '@n8n/backend-common'; +import { Time } from '@n8n/constants'; +import { OnLeaderStepdown, OnLeaderTakeover, OnShutdown } from '@n8n/decorators'; +import { Service } from '@n8n/di'; +import { InstanceSettings } from 'n8n-core'; + +import { TokenExchangeJtiRepository } from '../database/repositories/token-exchange-jti.repository'; +import { TokenExchangeConfig } from '../token-exchange.config'; + +@Service() +export class JtiCleanupService { + private cleanupInterval: NodeJS.Timeout | undefined; + + private isShuttingDown = false; + + private readonly logger: Logger; + + constructor( + logger: Logger, + private readonly config: TokenExchangeConfig, + private readonly jtiRepository: TokenExchangeJtiRepository, + private readonly instanceSettings: InstanceSettings, + ) { + this.logger = logger.scoped('token-exchange'); + } + + init() { + if (this.instanceSettings.isLeader) this.startCleanup(); + } + + @OnLeaderTakeover() + startCleanup() { + if (this.isShuttingDown) return; + + const intervalMs = this.config.jtiCleanupIntervalSeconds * Time.seconds.toMilliseconds; + this.cleanupInterval = setInterval(async () => await this.cleanup(), intervalMs); + + this.logger.debug(`JTI cleanup scheduled every ${this.config.jtiCleanupIntervalSeconds}s`); + } + + @OnLeaderStepdown() + stopCleanup() { + clearInterval(this.cleanupInterval); + this.cleanupInterval = undefined; + } + + private async cleanup() { + let totalDeleted = 0; + try { + let deleted: number; + do { + deleted = await this.jtiRepository.deleteExpiredBatch(this.config.jtiCleanupBatchSize); + totalDeleted += deleted; + } while (deleted >= this.config.jtiCleanupBatchSize); + + if (totalDeleted > 0) { + this.logger.debug('Cleaned up expired JTIs', { count: totalDeleted }); + } + } catch (error) { + this.logger.error('Failed to clean up expired JTIs', { error }); + } + } + + @OnShutdown() + shutdown() { + this.isShuttingDown = true; + this.stopCleanup(); + } +} diff --git a/packages/cli/src/modules/token-exchange/services/jti-store.service.ts b/packages/cli/src/modules/token-exchange/services/jti-store.service.ts index 16116234ca8..5efedf235be 100644 --- a/packages/cli/src/modules/token-exchange/services/jti-store.service.ts +++ b/packages/cli/src/modules/token-exchange/services/jti-store.service.ts @@ -1,18 +1,38 @@ import { Service } from '@n8n/di'; +import { TokenExchangeJtiRepository } from '../database/repositories/token-exchange-jti.repository'; + +const GRACE_PERIOD_MS = 60_000; + /** * Tracks consumed JTI (JWT ID) values to prevent token replay attacks. * - * This is a skeleton service — the real implementation backed by a - * database table will be introduced in IAM-461. + * JTI consumption is deliberately performed as an independent atomic operation, + * not wrapped in a broader transaction with subsequent steps (identity resolution, + * JWT generation). Rationale: + * + * 1. Replay protection must never be compromised by uncommitted state. If consume + * were inside a transaction, the insert would be invisible to concurrent requests + * until commit. A transaction rollback would re-open the JTI for replay. + * 2. Because consume is auto-committed, there are no competing transactions that + * could observe inconsistent state. + * 3. If steps after consumption fail, the JTI is burned (consumed but unused). + * The external system must mint a new token with a fresh JTI — this is the + * expected and more secure behavior. */ @Service() export class JtiStoreService { + constructor(private readonly jtiRepository: TokenExchangeJtiRepository) {} + /** * Attempt to consume a JTI. Returns `true` if consumed successfully * (first use), `false` if already consumed (replay). + * + * Adds a 60-second grace period on top of the token expiry to account + * for clock skew and processing time. */ - async consume(_jti: string, _expiresAt: Date): Promise { - return true; + async consume(jti: string, expiresAt: Date): Promise { + const expiresAtWithGrace = new Date(expiresAt.getTime() + GRACE_PERIOD_MS); + return await this.jtiRepository.atomicConsume(jti, expiresAtWithGrace); } } diff --git a/packages/cli/src/modules/token-exchange/token-exchange.config.ts b/packages/cli/src/modules/token-exchange/token-exchange.config.ts index a4fc8a1a9c3..daf92f01831 100644 --- a/packages/cli/src/modules/token-exchange/token-exchange.config.ts +++ b/packages/cli/src/modules/token-exchange/token-exchange.config.ts @@ -19,4 +19,12 @@ export class TokenExchangeConfig { */ @Env('N8N_TOKEN_EXCHANGE_TRUSTED_KEYS') trustedKeys: string = ''; + + /** Interval in seconds between JTI cleanup runs. */ + @Env('N8N_TOKEN_EXCHANGE_JTI_CLEANUP_INTERVAL_SECONDS') + jtiCleanupIntervalSeconds: number = 60; + + /** Maximum number of expired JTI rows to delete per cleanup run. */ + @Env('N8N_TOKEN_EXCHANGE_JTI_CLEANUP_BATCH_SIZE') + jtiCleanupBatchSize: number = 1000; } diff --git a/packages/cli/src/modules/token-exchange/token-exchange.module.ts b/packages/cli/src/modules/token-exchange/token-exchange.module.ts index 65a9852dbac..5fb2f767e5b 100644 --- a/packages/cli/src/modules/token-exchange/token-exchange.module.ts +++ b/packages/cli/src/modules/token-exchange/token-exchange.module.ts @@ -13,6 +13,11 @@ function isFeatureFlagEnabled(): boolean { instanceTypes: ['main'], }) export class TokenExchangeModule implements ModuleInterface { + async entities() { + const { TokenExchangeJti } = await import('./database/entities/token-exchange-jti.entity'); + return [TokenExchangeJti] as never; + } + async init() { if (!isFeatureFlagEnabled()) { return; @@ -23,5 +28,8 @@ export class TokenExchangeModule implements ModuleInterface { await import('./token-exchange.controller'); await import('./controllers/embed-auth.controller'); + + const { JtiCleanupService } = await import('./services/jti-cleanup.service'); + Container.get(JtiCleanupService).init(); } } diff --git a/packages/cli/test/integration/token-exchange/token-exchange-jti.repository.integration.test.ts b/packages/cli/test/integration/token-exchange/token-exchange-jti.repository.integration.test.ts new file mode 100644 index 00000000000..425e62c56d5 --- /dev/null +++ b/packages/cli/test/integration/token-exchange/token-exchange-jti.repository.integration.test.ts @@ -0,0 +1,111 @@ +import { testDb, testModules } from '@n8n/backend-test-utils'; +import { Container } from '@n8n/di'; + +import { TokenExchangeJtiRepository } from '@/modules/token-exchange/database/repositories/token-exchange-jti.repository'; + +describe('TokenExchangeJtiRepository', () => { + let repository: TokenExchangeJtiRepository; + + beforeAll(async () => { + await testModules.loadModules(['token-exchange']); + await testDb.init(); + repository = Container.get(TokenExchangeJtiRepository); + }); + + afterEach(async () => { + await testDb.truncate(['TokenExchangeJti']); + }); + + afterAll(async () => { + await testDb.terminate(); + }); + + describe('atomicConsume', () => { + const futureDate = new Date(Date.now() + 60 * 60 * 1000); + + it('should return true on first consume of a JTI', async () => { + const result = await repository.atomicConsume('jti-1', futureDate); + + expect(result).toBe(true); + }); + + it('should return false when the same JTI is consumed again', async () => { + await repository.atomicConsume('jti-1', futureDate); + + const result = await repository.atomicConsume('jti-1', futureDate); + + expect(result).toBe(false); + }); + + it('should persist the row in the database', async () => { + await repository.atomicConsume('jti-persisted', futureDate); + + const row = await repository.findOneBy({ jti: 'jti-persisted' }); + + expect(row).not.toBeNull(); + expect(row!.jti).toBe('jti-persisted'); + }); + + it('should allow consuming different JTIs independently', async () => { + const result1 = await repository.atomicConsume('jti-a', futureDate); + const result2 = await repository.atomicConsume('jti-b', futureDate); + + expect(result1).toBe(true); + expect(result2).toBe(true); + }); + + it('should allow only one consumer when called concurrently with the same JTI', async () => { + const results = await Promise.all([ + repository.atomicConsume('jti-race', futureDate), + repository.atomicConsume('jti-race', futureDate), + ]); + + const consumed = results.filter(Boolean); + expect(consumed).toHaveLength(1); + }); + }); + + describe('deleteExpiredBatch', () => { + it('should return 0 when table is empty', async () => { + const deleted = await repository.deleteExpiredBatch(100); + + expect(deleted).toBe(0); + }); + + it('should delete expired rows and return count', async () => { + const pastDate = new Date(Date.now() - 60 * 1000); + await repository.atomicConsume('expired-1', pastDate); + await repository.atomicConsume('expired-2', pastDate); + + const deleted = await repository.deleteExpiredBatch(100); + + expect(deleted).toBe(2); + expect(await repository.count()).toBe(0); + }); + + it('should not delete rows that have not expired', async () => { + const futureDate = new Date(Date.now() + 60 * 60 * 1000); + const pastDate = new Date(Date.now() - 60 * 1000); + await repository.atomicConsume('still-valid', futureDate); + await repository.atomicConsume('already-expired', pastDate); + + const deleted = await repository.deleteExpiredBatch(100); + + expect(deleted).toBe(1); + expect(await repository.findOneBy({ jti: 'still-valid' })).not.toBeNull(); + expect(await repository.findOneBy({ jti: 'already-expired' })).toBeNull(); + }); + + it('should respect batch size limit', async () => { + const pastDate = new Date(Date.now() - 60 * 1000); + await repository.atomicConsume('exp-1', pastDate); + await repository.atomicConsume('exp-2', pastDate); + await repository.atomicConsume('exp-3', pastDate); + + const deleted = await repository.deleteExpiredBatch(2); + + expect(deleted).toBe(2); + expect(await repository.count()).toBe(1); + }); + }); +});