1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00

refactor: improve token type error message (#1709)

This commit is contained in:
olav 2022-06-17 09:00:13 +02:00 committed by GitHub
parent 28ecb158a9
commit e6b49e4bce
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 19 additions and 7 deletions

View File

@ -1,9 +1,11 @@
import apiTokenMiddleware from './api-token-middleware';
import getLogger from '../../test/fixtures/no-logger';
import { CLIENT } from '../types/permissions';
import { createTestConfig } from '../../test/config/test-config';
import ApiUser from '../types/api-user';
import { ALL, ApiTokenType } from '../types/models/api-token';
import apiTokenMiddleware, {
TOKEN_TYPE_ERROR_MESSAGE,
} from './api-token-middleware';
let config: any;
@ -86,6 +88,8 @@ test('should add user if known token', async () => {
});
test('should not add user if not /api/client', async () => {
expect.assertions(5);
const apiUser = new ApiUser({
username: 'default',
permissions: [CLIENT],
@ -93,16 +97,21 @@ test('should not add user if not /api/client', async () => {
environment: ALL,
type: ApiTokenType.CLIENT,
});
const apiTokenService = {
getUserForToken: jest.fn().mockReturnValue(apiUser),
};
const func = apiTokenMiddleware(config, { apiTokenService });
const cb = jest.fn();
const res = {
sendStatus: jest.fn(),
status: (code: unknown) => ({
send: (data: unknown) => {
expect(code).toEqual(403);
expect(data).toEqual({ message: TOKEN_TYPE_ERROR_MESSAGE });
},
}),
};
const req = {
@ -116,7 +125,6 @@ test('should not add user if not /api/client', async () => {
expect(cb).not.toHaveBeenCalled();
expect(req.header).toHaveBeenCalled();
expect(req.user).toBeUndefined();
expect(res.sendStatus).toHaveBeenCalledWith(403);
});
test('should not add user if disabled', async () => {

View File

@ -6,6 +6,9 @@ const isClientApi = ({ path }) => {
return path && path.startsWith('/api/client');
};
export const TOKEN_TYPE_ERROR_MESSAGE =
'invalid token: expected an admin token but got a client token instead';
const apiAccessMiddleware = (
{
getLogger,
@ -28,9 +31,11 @@ const apiAccessMiddleware = (
try {
const apiToken = req.header('authorization');
const apiUser = apiTokenService.getUserForToken(apiToken);
if (apiUser) {
if (apiUser.type === ApiTokenType.CLIENT && !isClientApi(req)) {
return res.sendStatus(403);
res.status(403).send({ message: TOKEN_TYPE_ERROR_MESSAGE });
return;
}
req.user = apiUser;
}
@ -38,9 +43,8 @@ const apiAccessMiddleware = (
logger.error(error);
}
return next();
next();
};
};
module.exports = apiAccessMiddleware;
export default apiAccessMiddleware;