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
8 changes: 8 additions & 0 deletions backend/src/analytic/analytic.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import {
Logger,
Query,
OnModuleInit,
UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AnalyticService } from './analytic.service';
import { OwnershipGuard } from '../common/guards/ownership.guard';
import { Ownership } from '../common/decorators/ownership.decorator';
import type { PaginatedUserPuzzleHistory } from './analytic.service';

class RecordSolveDto {
Expand Down Expand Up @@ -71,6 +75,8 @@ export class AnalyticController implements OnModuleInit {
}

@Get('users/:userId/history')
@UseGuards(AuthGuard('jwt'), OwnershipGuard)
@Ownership({ param: 'userId' })
async getUserPuzzleHistory(
@Param('userId') userId: string,
): Promise<Record<string, any>> {
Expand All @@ -86,6 +92,8 @@ export class AnalyticController implements OnModuleInit {
}

@Get('users/:userId/history/paginated')
@UseGuards(AuthGuard('jwt'), OwnershipGuard)
@Ownership({ param: 'userId' })
async getUserPuzzleHistoryPaginated(
@Param('userId') userId: string,
@Query('page') page?: string,
Expand Down
9 changes: 9 additions & 0 deletions backend/src/api-key/api-key.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ describe('ApiKeyController', () => {

const mockKey = {
key: 'k-1',
keyHash: 'hash-1',
keyHint: 'k-1',
ownerLabel: 'owner',
status: ApiKeyStatus.ACTIVE,
createdAt: new Date(),
Expand All @@ -16,6 +18,7 @@ describe('ApiKeyController', () => {
beforeEach(async () => {
serviceMock = {
generateApiKey: jest.fn().mockReturnValue(mockKey),
rotateApiKey: jest.fn().mockReturnValue({ ...mockKey, key: 'k-2' }),
revokeApiKey: jest.fn().mockReturnValue({ ...mockKey, status: ApiKeyStatus.REVOKED }),
getAllApiKeys: jest.fn().mockReturnValue([mockKey]),
validateApiKey: jest.fn().mockReturnValue(true),
Expand All @@ -39,6 +42,12 @@ describe('ApiKeyController', () => {
expect(serviceMock.generateApiKey).toHaveBeenCalledWith('owner', true, undefined);
});

it('rotates API key', () => {
const res = controller.rotateApiKey('k-1', { isAdmin: true });
expect(res.key).toBe('k-2');
expect(serviceMock.rotateApiKey).toHaveBeenCalledWith('k-1', true);
});

it('revokes API key', () => {
const res = controller.revokeApiKey('k-1', { isAdmin: true });
expect(res.status).toBe(ApiKeyStatus.REVOKED);
Expand Down
27 changes: 22 additions & 5 deletions backend/src/api-key/api-key.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ import {
Logger,
Query,
} from '@nestjs/common';
import { ApiKeyService, ApiKey, ApiKeyStatus } from './api-key.service';
import {
ApiKeyService,
ApiKey,
ApiKeyRecord,
ApiKeyStatus,
} from './api-key.service';
import {
IsString,
IsNotEmpty,
Expand Down Expand Up @@ -51,7 +56,7 @@ export class ApiKeyController {
@HttpCode(HttpStatus.CREATED)
generateApiKey(@Body() generateApiKeyDto: GenerateApiKeyDto): ApiKey {
this.logger.log(
`Received request to generate API key: ${JSON.stringify(generateApiKeyDto)}`,
`Received request to generate API key for: ${generateApiKeyDto.ownerLabel}`,
);
return this.apiKeyService.generateApiKey(
generateApiKeyDto.ownerLabel,
Expand All @@ -62,20 +67,32 @@ export class ApiKeyController {
);
}

@Post('rotate/:key')
@HttpCode(HttpStatus.OK)
rotateApiKey(
@Param('key') key: string,
@Body() adminActionDto: AdminActionDto,
): ApiKey {
this.logger.log(
`Received request to rotate API key (isAdmin: ${adminActionDto.isAdmin}).`,
);
return this.apiKeyService.rotateApiKey(key, adminActionDto.isAdmin);
}

@Post('revoke/:key')
@HttpCode(HttpStatus.OK)
revokeApiKey(
@Param('key') key: string,
@Body() adminActionDto: AdminActionDto,
): ApiKey {
): ApiKeyRecord {
this.logger.log(
`Received request to revoke API key ${key} (isAdmin: ${adminActionDto.isAdmin}).`,
`Received request to revoke API key (isAdmin: ${adminActionDto.isAdmin}).`,
);
return this.apiKeyService.revokeApiKey(key, adminActionDto.isAdmin);
}

@Get('all')
getAllApiKeys(@Query() adminActionDto: AdminActionDto): ApiKey[] {
getAllApiKeys(@Query() adminActionDto: AdminActionDto): ApiKeyRecord[] {
this.logger.log(
`Received request to get all API keys (isAdmin: ${adminActionDto.isAdmin}).`,
);
Expand Down
71 changes: 71 additions & 0 deletions backend/src/api-key/api-key.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Test } from '@nestjs/testing';
import { UnauthorizedException } from '@nestjs/common';
import { APIKeyGuard } from './api-key.guard';
import { ApiKeyService } from './api-key.service';

function mockContext(request: Record<string, any>): any {
return {
switchToHttp: () => ({ getRequest: () => request }),
};
}

describe('APIKeyGuard', () => {
let guard: APIKeyGuard;
let serviceMock: { validateApiKey: jest.Mock };

beforeEach(async () => {
serviceMock = { validateApiKey: jest.fn() };
const moduleRef = await Test.createTestingModule({
providers: [
APIKeyGuard,
{ provide: ApiKeyService, useValue: serviceMock },
],
}).compile();
guard = moduleRef.get(APIKeyGuard);
});

it('rejects requests without an x-api-key header', async () => {
const ctx = mockContext({ headers: {}, path: '/api-keys/protected' });
await expect(guard.canActivate(ctx)).rejects.toThrow(UnauthorizedException);
});

it('passes the route pattern to the service for scope checks', async () => {
serviceMock.validateApiKey.mockReturnValue(true);
const ctx = mockContext({
headers: { 'x-api-key': 'sh_valid' },
route: { path: '/api-keys/protected' },
path: '/api/v1/api-keys/protected',
});
await expect(guard.canActivate(ctx)).resolves.toBe(true);
expect(serviceMock.validateApiKey).toHaveBeenCalledWith(
'sh_valid',
'/api-keys/protected',
);
});

it('rejects keys the service deems invalid for the endpoint', async () => {
serviceMock.validateApiKey.mockReturnValue(false);
const ctx = mockContext({
headers: { 'x-api-key': 'sh_scoped-elsewhere' },
route: { path: '/api-keys/protected' },
});
await expect(guard.canActivate(ctx)).rejects.toThrow(UnauthorizedException);
expect(serviceMock.validateApiKey).toHaveBeenCalledWith(
'sh_scoped-elsewhere',
'/api-keys/protected',
);
});

it('falls back to the raw path when no route pattern is available', async () => {
serviceMock.validateApiKey.mockReturnValue(true);
const ctx = mockContext({
headers: { 'x-api-key': 'sh_valid' },
path: '/some/raw/path',
});
await expect(guard.canActivate(ctx)).resolves.toBe(true);
expect(serviceMock.validateApiKey).toHaveBeenCalledWith(
'sh_valid',
'/some/raw/path',
);
});
});
9 changes: 7 additions & 2 deletions backend/src/api-key/api-key.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,15 @@ export class APIKeyGuard implements CanActivate {
throw new UnauthorizedException('API Key missing');
}

const isValid = this.apiKeyService.validateApiKey(apiKey);
// Match against the route pattern (e.g. `/api-keys/protected`) so
// scope checks are stable regardless of the global `/api/v1` prefix.
const endpoint =
(request.route?.path as string | undefined) ?? request.path;

const isValid = this.apiKeyService.validateApiKey(apiKey, endpoint);

if (!isValid) {
this.logger.warn(`Invalid API Key: ${apiKey}`);
this.logger.warn('Invalid API Key for requested endpoint.');
throw new UnauthorizedException('Invalid API Key');
}

Expand Down
Loading