1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-06 00:07:44 +01:00
unleash.unleash/src/lib/middleware/api-token-middleware.ts
Gastón Fournier 70499dc1d4
feat: allow api token middleware to fetch from db (#6344)
## About the changes
When edge is configured to automatically generate tokens, it requires
the token to be present in all unleash instances.
It's behind a flag which enables us to turn it on on a case by case
scenario.

The risk of this implementation is that we'd be adding load to the
database in the middleware that evaluates tokens (which are present in
mostly all our API calls. We only query when the token is missing but
because the /client and /frontend endpoints which will be the affected
ones are high throughput, we want to be extra careful to avoid DDoSing
ourselves

## Alternatives:
One alternative would be that we merge the two endpoints into one.
Currently, Edge does the following:
If the token is not valid, it tries to create a token using a service
account token and /api/admin/create-token endpoint. Then it uses the
token generated (which is returned from the prior endpoint) to query
/api/frontend. What if we could call /api/frontend with the same service
account we use to create the token? It may sound risky but if the same
application holding the service account token with permission to create
a token, can call /api/frontend via the generated token, shouldn't it be
able to call the endpoint directly?

The purpose of the token is authentication and authorization. With the
two tokens we are authenticating the same app with 2 different
authorization scopes, but because it's the same app we are
authenticating, can't we just use one token and assume that the app has
both scopes?

If the service account already has permissions to create a token and
then use that token for further actions, allowing it to directly call
/api/frontend does not necessarily introduce new security risks. The
only risk is allowing the app to generate new tokens. Which leads to the
third alternative: should we just remove this option from edge?
2024-02-27 16:08:44 +01:00

113 lines
3.9 KiB
TypeScript

import { ApiTokenType } from '../types/models/api-token';
import { IUnleashConfig } from '../types/option';
import { IApiRequest, IAuthRequest } from '../routes/unleash-types';
import { IUnleashServices } from '../server-impl';
import { IFlagContext } from '../types';
const isClientApi = ({ path }) => {
return path && path.indexOf('/api/client') > -1;
};
const isEdgeMetricsApi = ({ path }) => {
return path && path.indexOf('/edge/metrics') > -1;
};
const isProxyApi = ({ path }) => {
if (!path) {
return;
}
// Handle all our current proxy paths which will redirect to the new
// embedded proxy endpoint
return (
path.indexOf('/api/proxy') > -1 ||
path.indexOf('/api/development/proxy') > -1 ||
path.indexOf('/api/production/proxy') > -1 ||
path.indexOf('/api/frontend') > -1
);
};
const contextFrom = (
req: IAuthRequest<any, any, any, any> | IApiRequest<any, any, any, any>,
): IFlagContext | undefined => {
// this is what we'd get from edge:
// req_path: '/api/client/features',
// req_user_agent: 'unleash-edge-16.0.4'
return {
reqPath: req.path,
reqUserAgent: req.get ? req.get('User-Agent') ?? '' : '',
reqAppName:
req.headers?.['unleash-appname'] ?? req.query?.appName ?? '',
};
};
export const TOKEN_TYPE_ERROR_MESSAGE =
'invalid token: expected a different token type for this endpoint';
export const NO_TOKEN_WHERE_TOKEN_WAS_REQUIRED =
'This endpoint requires an API token. Please add an authorization header to your request with a valid token';
const apiAccessMiddleware = (
{
getLogger,
authentication,
flagResolver,
}: Pick<IUnleashConfig, 'getLogger' | 'authentication' | 'flagResolver'>,
{ apiTokenService }: Pick<IUnleashServices, 'apiTokenService'>,
): any => {
const logger = getLogger('/middleware/api-token.ts');
logger.debug('Enabling api-token middleware');
if (!authentication.enableApiToken) {
return (req, res, next) => next();
}
return async (req: IAuthRequest | IApiRequest, res, next) => {
if (req.user) {
return next();
}
try {
const apiToken = req.header('authorization');
if (!apiToken?.startsWith('user:')) {
const apiUser = apiToken
? await apiTokenService.getUserForToken(
apiToken,
contextFrom(req),
)
: undefined;
const { CLIENT, FRONTEND } = ApiTokenType;
if (apiUser) {
if (
(apiUser.type === CLIENT &&
!isClientApi(req) &&
!isEdgeMetricsApi(req)) ||
(apiUser.type === FRONTEND && !isProxyApi(req)) ||
(apiUser.type === FRONTEND &&
!flagResolver.isEnabled('embedProxy'))
) {
res.status(403).send({
message: TOKEN_TYPE_ERROR_MESSAGE,
});
return;
}
req.user = apiUser;
} else if (isClientApi(req) || isProxyApi(req)) {
// If we're here, we know that api token middleware was enabled, otherwise we'd returned a no-op middleware
// We explicitly only protect client and proxy apis, since admin apis are protected by our permission checker
// Reject with 401
res.status(401).send({
message: NO_TOKEN_WHERE_TOKEN_WAS_REQUIRED,
});
return;
}
}
} catch (error) {
logger.warn(error);
}
next();
};
};
export default apiAccessMiddleware;