0
votes

I am building a REST service using serverless framework on AWS Lambda. I have created a custom authorizer that is called pre to any invocations of my lambdas. When I run serverless-offline, everything works. When I deploy, I get an error in AP Gateway. I have enabled loging in API gateway, but nothing is written to the log.

Here is my serverless.yml file:

provider:
  name: aws
  runtime: nodejs12.x
  stage: ${opt:stage, "dev"}
  region: eu-west-1

functions:

  authorize:
    handler: src/handlers/authorization.authorize

  listAlerts:
    handler: src/handlers/alert-handler.listAlerts
    events:
      - http:
          path: /alerts
          method: GET
          authorizer: ${self:custom.authorization.authorize}

custom:
  stage: ${opt:stage, self:provider.stage}
  authorization:
    authorize:
      name: authorize
      type: TOKEN
      identitySource: method.request.header.Authorization
      identityValidationExpression: Bearer (.*)
plugins:
  - serverless-plugin-typescript
  - serverless-offline
package:
    include:
    - src/**.*

My authorization handler looks like this. The method picks up my authentication token and verify it using JOSE, and returns a principalId for the user and some roles:

import jwksClient from "jwks-rsa";
import { JWT } from "jose";


export const authorize = async (event: CustomAuthorizerEvent): Promise<CustomAuthorizerResult> => {
    const prefix = "bearer ";
    if (!event.authorizationToken?.toLowerCase().startsWith(prefix)) {
        return Promise.reject("Unauthorized");
    }
    const token = event.authorizationToken?.substring(prefix.length);
    const signingKey = await getCachedSigningKey()
    const jwt = JWT.verify(token, signingKey);
    if ((typeof jwt) !== "object") {
        throw "Unauthorized";
    }
    const userId = jwt["sub"];
    const expires = Number(jwt["exp"]);
    const roles = jwt["assumed-roles"] as string[];
    if (Date.now() > expires * 1000 ) {
        throw "Unauthorized";
    }
    const principalId = userId;
    const policyDocument: PolicyDocument = {
        Version: "2012-10-17",
        Statement: [
            {
                Action: "execute-api:Invoke",
                Effect: "Allow",
                Resource: event.methodArn,
            }
        ]
    };

    return {
        principalId,
        policyDocument,
        context: {
            userId,
            roles
        }
    };
};

If do serverless offline start, the emulated API-gateway is started on port 3000. I call the API:

❯ http :3000/alerts/5480e8a1-e3d4-432d-985e-9542c91a49ce Authorization:"Bearer eyJraWQiO.......LHA12jM2UEXFy76dhKUj_iX6SXQQ"
HTTP/1.1 200 OK
Connection: keep-alive
Date: Wed, 04 Mar 2020 21:29:07 GMT
accept-ranges: bytes
access-control-allow-origin: *
cache-control: no-cache
content-length: 174
content-type: application/json; charset=utf-8

{
    "id": "5480e8a1-e3d4-432d-985e-9542c91a49ce",
    "message": "test",
    "subjects": [
        {
            "id": "6ee2c07d-6486-4601-9b4b-05f61c0d0caf",
            "referenceId": "5480e8a1-e3d4-432d-985e-9542c91a49ce"
        }
    ]
}

So, It works locally and my handler logs the userId and roles. Then I deploy to AWS with serverless deplpy without any warnings. I try to invoke my API-gateway endpoint:

❯ http https://og8...<bla-bla>..kcc.execute-api.eu-west-1.amazonaws.com/dev/alerts/alerts/ Authorization:"Bearer eyJraWQiOiJkZXYiL.....VOPI2LHA12jM2UEXFy76dhKUj_iX6SXQQ"
HTTP/1.1 500 Internal Server Error
Connection: keep-alive
Content-Length: 16
Content-Type: application/json
Date: Wed, 04 Mar 2020 21:32:22 GMT
Via: 1.1 e31ab4c27d99cec62ef37e2607db9b45.cloudfront.net (CloudFront)
X-Amz-Cf-Id: kfIhCZHCGoL3OcjPSX4QWdtK1Qequ2vJe9RNst4wBEf_d90fJLjWgQ==
X-Amz-Cf-Pop: ARN1-C1
X-Cache: Error from cloudfront
x-amz-apigw-id: I4mu_HOFjoEF6SQ=
x-amzn-ErrorType: AuthorizerConfigurationException
x-amzn-RequestId: 3cb89b9a-26db-4890-8edb-6aedcc51c09e

{
    "message": null
}

The invokation does not return instantly, but times out. What is going on?

2
It is most likely a permissions issue. I would validate that (1) the lambda permission is configured correctly to allow API Gateway to invoke the lambda. It could also be a packaging issue, so validate that the lambda works correctly when invoked directlyJoel Cornett

2 Answers

0
votes
  1. You have no such route /alerts/5480e8a1-e3d4-432d-985e-9542c91a49c in your configuration
  2. Please, open API GW Console and use Test to debug your problem enter image description here
0
votes

OK answering my own question, I had multiple problems above:

  • Can not call an async function. const signingKey = await getCachedSigningKey() will fail (This might be lack of permissions to do HTTP outside the VPC).
  • The context can only contain simple mappings. I tried to set an array here (x), but that is not allowed. Simple values only.

My final working solution looked like this if that can help anyone:

import { CustomAuthorizerEvent, CustomAuthorizerResult, PolicyDocument } from "aws-lambda";
import { JWT } from "jose";

export enum Role {
    User = "ROLE_USER",
    Admin = "ROLE_ADMIN",
}

export const getAuthorizerForRoles = (requiredRoles: Role[]) => async (event: CustomAuthorizerEvent): Promise<CustomAuthorizerResult> => {
    try {
        const prefix = "bearer ";
        if (!event.authorizationToken?.toLowerCase().startsWith(prefix)) {
            throw new Error(`Token does not start with ${prefix.trim()}`);
        }
        const token = event.authorizationToken?.substring(prefix.length);
            const signingKey = process.env.AUTH_SIGNING_KEY;
        const issuer = process.env.AUTH_ISSUER;
        if (!signingKey || !issuer) {
            throw new Error(`Auth properties not configure correct`);
        }
        const jwt = JWT.verify(token, signingKey, {
            issuer,
        });
        if ((typeof jwt) !== "object") {
            throw new Error(`The JWT has a unexpected structure`);
        }
        const userId = jwt["sub"];
        const expiresEpochMilliSec = Number(jwt["exp"]) * 1000;
        const expires = new Date(expiresEpochMilliSec);
        const assumedRoles = jwt["assumed-roles"] as string[];
        requiredRoles.forEach((requiredRole) => {
            if (!assumedRoles.includes(requiredRole)) {
                throw new Error(`The token does not contain the required role ${requiredRole}`);
            }
        });
        if (Date.now() > expires.valueOf()) {
            throw new Error(`The expired at ${expires}`);
        }
        const principalId = userId;
        const policyDocument: PolicyDocument = {
            Version: "2012-10-17",
            Statement: [
                {
                    Action: "execute-api:Invoke",
                    Effect: "Allow",
                    Resource: event.methodArn,
                }
            ]
        };

        const authResponse: CustomAuthorizerResult = {
            principalId,
            policyDocument,
            context: {
                userId,
                roles: assumedRoles.join(","),
            }
        };
        return authResponse;
    } catch (error) {
        console.log(error);
        throw "Unauthorized";
    }
};

export const authorizeUser = getAuthorizerForRoles([Role.User]);

export const authorizeAdmin = getAuthorizerForRoles([Role.Admin]);

As usual, the docs and log messages from AWS is bare-minimum..