Skip to content
Merged
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
19 changes: 18 additions & 1 deletion ignition-api/src/api-keys/api-key-scope.guard.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ApiKeyScopeGuard } from './api-key-scope.guard';
import { API_KEY_SCOPE_KEY } from './decorators/require-scope.decorator';

const mockReflector = (scopes: string[] | undefined) =>
({
Expand Down Expand Up @@ -61,6 +60,24 @@ describe('ApiKeyScopeGuard', () => {
);
});

it('error message includes required scope when no user is attached', () => {
const guard = new ApiKeyScopeGuard(mockReflector(['write']));
try {
guard.canActivate(buildContext(undefined));
} catch (err) {
expect((err as ForbiddenException).message).toContain('write');
}
});

it('error message includes required scope when user has no scope', () => {
const guard = new ApiKeyScopeGuard(mockReflector(['admin']));
try {
guard.canActivate(buildContext(null));
} catch (err) {
expect((err as ForbiddenException).message).toContain('admin');
}
});

it('error message includes key scope and required scope', () => {
const guard = new ApiKeyScopeGuard(mockReflector(['write']));
try {
Expand Down
8 changes: 6 additions & 2 deletions ignition-api/src/api-keys/api-key-scope.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,12 @@ export class ApiKeyScopeGuard implements CanActivate {

const user = request.user;

const requiredScopeDescription = requiredScopes.join(' or ');

if (!user || !user.scope) {
throw new ForbiddenException('API key scope information is missing');
throw new ForbiddenException(
`API key is missing a scope. Required: ${requiredScopeDescription}.`,
);
}

const keyScope = user.scope as ApiKeyScope;
Expand All @@ -82,7 +86,7 @@ export class ApiKeyScopeGuard implements CanActivate {
if (!hasRequiredScope) {
throw new ForbiddenException(
`API key scope '${keyScope}' is insufficient. ` +
`Required: ${requiredScopes.join(' or ')}.`,
`Required: ${requiredScopeDescription}.`,
);
}

Expand Down