cube icon indicating copy to clipboard operation
cube copied to clipboard

checkAuth custom error/response handling

Open jd2rogers2 opened this issue 5 years ago • 5 comments

Is your feature request related to a problem? Please describe. when i implement custom checkAuth as recommended by examples (https://cube.dev/docs/security#custom-authentication) i cannot access the response to create my own status code and message. all i can do is throw which forces a 500 (not accurate response code, should be 401 or 403)

Describe the solution you'd like checkAuth to take in the response so that i may mutate response i'd like to write something like below:

  checkAuth: async (req, res) => {
    const auth = req.headers.authorization;
    if (!auth) {
      res.status(401).send({ message: 'auth token not provided' });
      return;
    }

    // Replace `region` and `userPoolId` with your own
    const jwks = await fetch(
      'https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json'
    ).then((r) => r.json());
    const decoded = jwt.decode(auth, { complete: true });
    const jwk = _.find(jwks.keys, (x) => x.kid === decoded.header.kid);
    const pem = jwkToPem(jwk);

    const token = jwt.verify(auth, pem);
    if (!token) {
      res.status(401).send({ message: 'unauthorized' });
      return;
    }
    req.securityContext = token;
  },

Describe alternatives you've considered this could also be handled internally in node_modules/@cubejs-backend/api-gateway/dist/src/gateway.js > wrapCheckAuth but this doesn't allow for as much developer control i.e.

      if (req.securityContext && !req.authInfo) {
        req.authInfo = req.securityContext;
      } else if (req.authInfo) {
        if (!warningShowed) {
          this.logger('AuthInfo Deprecation', {
            warning: (
              'authInfo was renamed to securityContext, please migrate: ' +
              'https://github.com/cube-js/cube.js/blob/master/DEPRECATION.md#checkauthmiddleware'
            )
          });

          warningShowed = true;
        }

        req.securityContext = req.authInfo;
      } else if (!req.authInfo || !req.securityContext) {
        res.status(401).send('unauthorized');
      }

also, wrapCheckAuth will still need to take in res for this

Additional context Add any other context or screenshots about the feature request here.

related code: https://github.com/cube-js/cube.js/blob/90f2365eb21313fb5ea7a80583622e0ed742005c/packages/cubejs-api-gateway/src/gateway.ts#L844

https://github.com/cube-js/cube.js/blob/8e9c3bcafc3f9acbc8e1a53113202b4be19bb12c/packages/cubejs-api-gateway/src/SubscriptionServer.ts#L42

jd2rogers2 avatar Feb 08 '21 20:02 jd2rogers2

for anyone who finds there way here, i'm using a temporary workaround:

you can const { UserError } = require('@cubejs-backend/api-gateway'); and throw that instead and cube will catch it and respond with a 400

jd2rogers2 avatar Feb 09 '21 19:02 jd2rogers2

Hey @jd2rogers2

We're working on some updates to the auth and general and checkAuth method particularly. Some of the work is happening in this PR.

Let's keep this issue open for tracking the problem.

keydunov avatar Feb 10 '21 18:02 keydunov

Closed w #1962 ?

craigbeck avatar May 07 '21 18:05 craigbeck

Additional work around to get the desired response is to access the Response object from the req Request object like so.

req.res.status('401').json({ message: "unauthorized"})

While this will return a desired response to user it unfortunately surfaces an additional error Error: Cannot set headers after they are sent to the client. Work around above doesn't block the request from terminating even after a response has been sent to the user.

checkAuth should also include Response object as a param to prevent this.

Exploring options with initApp

eslynunez avatar Sep 22 '22 02:09 eslynunez

Follow up!

setting the initApp express error middleware does not capture errors for custom error response.

 initApp: (app) => {
     app.use((err, req, res, next) => {
     res.status(400).json({"message": "Why can't I get errors here?"})
     next()
   });
 },

Still think that providing access to the Response object in checkAuth would be a better solution for returning a custom response.

I found another work around using CubejsHandlerError this returns the appropriate status code and an error message but only in a response format set by CubeJs.

     throw new CubejsHandlerError(
          401,
          "Unauthorized",
          "Your request could not be authenticated"
      );

Actual response

{
    "error": "Your request could not be authenticated"
}

Desired response

{
    "type": "unauthorized",
    "description": "Your request could not be authenticated"
}

There doesn't seem to be a way atm to transform api responses.

eslynunez avatar Sep 23 '22 14:09 eslynunez