A C#.Net AWS Lambda Authorizer to replace the one in Serverless Security Workshop

February 3, 2023

The Serverless Security Workshop is a good little exercise that teaches a number of security concepts to developers. It’s a little bit buggy, but if you can manage to get past that, it demonstrates how to secure a web api with Cognito using a ClientId and ClientSecret. Of course, the Authoriser Lambda is written in Javascript, as is the Api code. There isn’t that much out there that really shows how to do it in C# in .net 6, so I thought I would write a replacement for that.

The original workshop is here: https://catalog.us-east-1.prod.workshops.aws/workshops/026f84fd-f589-4a59-a4d1-81dc543fcd30/en-US

using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace AWSAuthorizationLambdaSample;

public class Function
{
    public class SecurityConstants
    {
        public const string Issuer = "https://cognito-idp.us-east-1.amazonaws.com/put-your-cognito-endpoint-here";
    }

    public class WildRydesScopes
    {
        public const string CustomizeUnicorns = "WildRydes/CustomizeUnicorn";
        public const string PartnerAdmin = "WildRydes/ManagePartners";
    }

    private static List? m_pems;

    public Function() { 
        //Like the original javascript, this caches the pems keys locally
        if (m_pems == null)
        {
            using HttpClient client = new();
            var jsonString = client.GetStringAsync("https://cognito-idp.put-your-region-here.amazonaws.com/put-your-cognito-endpoint-here/.well-known/jwks.json").Result;
            var jwksObject = JsonConvert.DeserializeObject(jsonString);
            if (jwksObject == null)
            {
                throw new UnauthorizedAccessException();
            }
            LambdaLogger.Log("\nJwksObject: " + JsonConvert.SerializeObject(jwksObject) + "\n");
            m_pems = jwksObject.keys;
        }
    }

    public async Task ValidateToken(APIGatewayCustomAuthorizerRequest apigAuthRequest, ILambdaContext context)
    {
        LambdaLogger.Log("\nValidateTokenV3");
        LambdaLogger.Log("\nEVENT: " + JsonConvert.SerializeObject(apigAuthRequest) + "\n");
        LambdaLogger.Log("\nCONTEXT: " + JsonConvert.SerializeObject(context) + "\n");

        var authToken = apigAuthRequest.AuthorizationToken;
        LambdaLogger.Log("\nauthToken:" + authToken + "\n");

        var handler = new JwtSecurityTokenHandler();

        var jsonToken = handler.ReadJwtToken(authToken);
        if (jsonToken == null)
        {
            throw new UnauthorizedAccessException();
        }
        LambdaLogger.Log("\nJsonToken: " + JsonConvert.SerializeObject(jsonToken) + "\n");

        var kid = (string)jsonToken.Header["kid"];
        LambdaLogger.Log("\nkid: " + kid + "\n");

        //Get the pems key that matches the key id in the token         
        var cognitoPublicKey = m_pems?.FirstOrDefault(k => k.kid == kid);
        if (cognitoPublicKey == null)
        {
            throw new UnauthorizedAccessException();
        }

        var tokenValidationParams = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidIssuer = SecurityConstants.Issuer,
            ValidateAudience = false, //validating audience doesn't work for some unknown reason
            ValidAudience = SecurityConstants.Issuer,
            IssuerSigningKey = new RsaSecurityKey(new RSAParameters()
            {
                //RSA only requires the modulus and exponent from the public key to decrypt the token
                Modulus = Base64UrlEncoder.DecodeBytes(cognitoPublicKey.n),
                Exponent = Base64UrlEncoder.DecodeBytes(cognitoPublicKey.e)
            }),
            ClockSkew = TimeSpan.FromMinutes(5),
            ValidateIssuerSigningKey = true
        };

        LambdaLogger.Log("tokenValidationParams:\n" + JsonConvert.SerializeObject(tokenValidationParams));

        var isAuthorized = false;
        var hasPartnerScope = false;
        var hasCustomizeUnicornsScope = false;
        var clientId = string.Empty;

        if (!string.IsNullOrWhiteSpace(apigAuthRequest.AuthorizationToken))
        {
            try
            {
                var tokenValidationResult = await handler.ValidateTokenAsync(apigAuthRequest.AuthorizationToken, tokenValidationParams);
                if (!tokenValidationResult.IsValid)
                {
                    throw new UnauthorizedAccessException();
                }

                isAuthorized = tokenValidationResult.IsValid;

                var scope = (string?)tokenValidationResult?.Claims["scope"];
                if (scope != null)
                {
                    hasPartnerScope = scope.Contains(WildRydesScopes.PartnerAdmin);
                    hasCustomizeUnicornsScope = scope.Contains(WildRydesScopes.CustomizeUnicorns);
                }

                clientId = (string?)tokenValidationResult?.Claims["client_id"];
                if (clientId == null)
                {
                    throw new UnauthorizedAccessException();
                }
            }
            catch (Exception ex)
            {
                LambdaLogger.Log($"Error occurred validating token: {ex.Message}");
                throw new UnauthorizedAccessException();
            }
        }
        var policy = new APIGatewayCustomAuthorizerPolicy
        {
            Version = "2012-10-17",
            Statement = new List()
        };
        var contextOutput = new APIGatewayCustomAuthorizerContextOutput();

        // string MethodArn = "arn:aws:execute-api:us-east-1:123456789012:example/prod/POST/{proxy+}";

        if (isAuthorized)
        {
            var resourceRoot = GetResourceRoot(apigAuthRequest.MethodArn);

            var policyStatement = new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
            {
                Action = new HashSet(new string[] { "execute-api:Invoke" }),
                Effect = "Allow",
                Resource = new HashSet()
            };

            // Start Policy Statements

            // 1. Any authenticated clients can list customisation options
            policyStatement.Resource.Add(resourceRoot + "/GET/horns");
            policyStatement.Resource.Add(resourceRoot + "/GET/socks");
            policyStatement.Resource.Add(resourceRoot + "/GET/glasses");
            policyStatement.Resource.Add(resourceRoot + "/GET/capes");

            // 2. When the scope matches the Partner Admin scope, then allow partner methods
            if (hasPartnerScope == true)
            {
                policyStatement.Resource.Add(resourceRoot + "/GET/partner*");
                policyStatement.Resource.Add(resourceRoot + "/POST/partner*");
                policyStatement.Resource.Add(resourceRoot + "/DELETE/partner*");
            }

            // 3. When the scope matches the unicorn customisations scope, retrieve the company id from the dynamo database
            //    otherwise it's not authorised
            if (hasCustomizeUnicornsScope == true)
            {
                policyStatement.Resource.Add(resourceRoot + "/GET/customizations*");
                policyStatement.Resource.Add(resourceRoot + "/POST/customizations*");
                policyStatement.Resource.Add(resourceRoot + "/DELETE/customizations*");

                // this is for the right to add customisations to the database.
                // a company can only add customisations to their own set of unicorns
                var companyId = await GetCompanyIdForClientAsync(clientId);
                contextOutput["CompanyID"] = companyId;
            }

            policy.Statement.Add(policyStatement);

            // End Policy Statements
        }
        else
        {
            throw new UnauthorizedAccessException();
        }
        return new APIGatewayCustomAuthorizerResponse
        {
            PolicyDocument = policy,
            Context = contextOutput
        };

    }

    public async Task GetCompanyIdForClientAsync(string clientId)
    {
        AmazonDynamoDBClient client = new AmazonDynamoDBClient();
        DynamoDBContext dbContext = new DynamoDBContext(client);
        var result = await dbContext.LoadAsync(clientId);
        if (result != null)
        {
            return result.CompanyID;
        }
        return null;
    }

    private string GetResourceRoot(string methodArn)
    {
        var tmp = methodArn.Split(':');
        var apiGatewayArnTmp = tmp[5].Split('/');
        return $"{tmp[0]}:{tmp[1]}:{tmp[2]}:{tmp[3]}:{tmp[4]}:{apiGatewayArnTmp[0]}/{apiGatewayArnTmp[1]}";
    }

}

The original JavaScript authorizer looks like this:

console.log('Loading function');

const jwt = require('jsonwebtoken');
const request = require('request');
const jwkToPem = require('jwk-to-pem');

const userPoolId = process.env["USER_POOL_ID"];
const region = process.env["AWS_REGION"]; //e.g. us-east-1
const iss = 'https://cognito-idp.' + region + '.amazonaws.com/' + userPoolId;

const AWS = require('aws-sdk');
const ddbDocClient = new AWS.DynamoDB.DocumentClient({
    region: process.env.AWS_REGION
});

const companyDDBTable = process.env["PARTNER_DDB_TABLE"];
const CUSTOMIZE_SCOPE = "WildRydes/CustomizeUnicorn";

const PARTNER_ADMIN_SCOPE = "WildRydes/ManagePartners";

var pems;


exports.handler = (event, context, callback) => {
    console.log("received event:\n" + JSON.stringify(event, null, 2));

    //Download PEM for your UserPool if not already downloaded
    if (!pems) {
        //Download the JWKs and save it as PEM
        request({
            url: iss + '/.well-known/jwks.json',
            json: true
        }, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                pems = {};
                var keys = body['keys'];
                for (var i = 0; i < keys.length; i++) {
                    //Convert each key to PEM
                    var key_id = keys[i].kid;
                    var modulus = keys[i].n;
                    var exponent = keys[i].e;
                    var key_type = keys[i].kty;
                    var jwk = {kty: key_type, n: modulus, e: exponent};
                    var pem = jwkToPem(jwk);
                    pems[key_id] = pem;
                }
                //Now continue with validating the token
                ValidateToken(pems, event, context, callback);
            } else {
                //Unable to download JWKs, fail the call
                context.fail("error");
            }
        });
    } else {
        //PEMs are already downloaded, continue with validating the token
        ValidateToken(pems, event, context, callback);
    }
};

function ValidateToken(pems, event, context, callback) {

    var token = event.authorizationToken;

    // the auth header may come in the format of "Bearer " or ""
    var parts = token.split(' ');
    if (parts.length == 2) {
        var schema = parts.shift().toLowerCase();
        token = parts.join(' ');
        if ('bearer' != schema) {
            console.log("Schema " + schema + " not supported");
            context.fail("Unauthorized");
            return;
        }
    }

    //Fail if the token is not jwt
    var decodedJwt = jwt.decode(token, {complete: true});
    if (!decodedJwt) {
        console.log("Not a valid JWT token");
        context.fail("Unauthorized");
        return;
    }

    //Fail if token is not from your UserPool
    if (decodedJwt.payload.iss != iss) {
        console.log("invalid issuer");
        context.fail("Unauthorized");
        return;
    }

    //Reject the jwt if it's not an 'Access Token'
    if (decodedJwt.payload.token_use != 'access') {
        console.log("Not an access token");
        context.fail("Unauthorized");
        return;
    }

    //Get the kid from the token and retrieve corresponding PEM
    var kid = decodedJwt.header.kid;
    var pem = pems[kid];
    if (!pem) {
        console.log('Invalid access token');
        context.fail("Unauthorized");
        return;
    }

    //Verify the signature of the JWT token to ensure it's really coming from your User Pool

    jwt.verify(token, pem, {issuer: iss}, function (err, payload) {
        if (err) {
            console.log("error verifying token: " + JSON.stringify(err, null, 2));
            context.fail("Unauthorized");
        } else {
            console.log("Token payload: " + JSON.stringify(payload));
            //Valid token. Generate the API Gateway policy for the user
            //Always generate the policy on value of 'sub' claim and not for 'username' because username is reassignable
            //sub is UUID for a user which is never reassigned to another user.
            var principalId = payload.username;

            //Get AWS AccountId and API Options
            var apiOptions = {};
            var tmp = event.methodArn.split(':');
            var apiGatewayArnTmp = tmp[5].split('/');
            var awsAccountId = tmp[4];
            apiOptions.region = tmp[3];
            apiOptions.restApiId = apiGatewayArnTmp[0];
            apiOptions.stage = apiGatewayArnTmp[1];
            var method = apiGatewayArnTmp[2];
            var resource = '/'; // root resource
            if (apiGatewayArnTmp[3]) {
                resource += apiGatewayArnTmp[3];
            }
            //For more information on specifics of generating policy, refer to blueprint for API Gateway's Custom authorizer in Lambda console
            var policy = new AuthPolicy(principalId, awsAccountId, apiOptions);

            // Any authenticated clients can list customization options
            policy.allowMethod(AuthPolicy.HttpVerb.GET, "/horns");
            policy.allowMethod(AuthPolicy.HttpVerb.GET, "/socks");
            policy.allowMethod(AuthPolicy.HttpVerb.GET, "/glasses");
            policy.allowMethod(AuthPolicy.HttpVerb.GET, "/capes");

            // When the scope matches the partner admin scope
            if (payload.scope.includes(PARTNER_ADMIN_SCOPE)) {
                policy.allowMethod(AuthPolicy.HttpVerb.GET, "/partner*");
                policy.allowMethod(AuthPolicy.HttpVerb.POST, "/partner*");
                policy.allowMethod(AuthPolicy.HttpVerb.DELETE, "/partner*");

                const authResponse = policy.build();
                console.log("authResponse:" + JSON.stringify(authResponse, null, 2));
                callback(null, authResponse);
                return;
            }

            // When the scope matches the unicorn customizations scope, ensure the company can be found in the ID loopup table
            if (payload.scope.includes(CUSTOMIZE_SCOPE)) {
                policy.allowMethod(AuthPolicy.HttpVerb.GET, "/customizations*");
                policy.allowMethod(AuthPolicy.HttpVerb.POST, "/customizations*");
                policy.allowMethod(AuthPolicy.HttpVerb.DELETE, "/customizations*");
                const authResponse = policy.build();

                // look up the backend ID for the company
                var params = {
                    TableName: companyDDBTable,
                    Key: {'ClientID': payload["client_id"]}
                };

                ddbDocClient.get(params).promise().then(data => {
                    console.log("DDB response:\n" + JSON.stringify(data));
                    if (data["Item"] && "CompanyID" in data["Item"]) {
                        authResponse.context = {
                            CompanyID: data["Item"]["CompanyID"]
                        };

                        // Uncomment here to pass on the client ID as the api key in the auth response
                        // authResponse.usageIdentifierKey = payload["client_id"];

                        console.log("authResponse:" + JSON.stringify(authResponse, null, 2));
                        callback(null, authResponse);
                        return;
                    } else {
                        console.log("did not find matching clientID");
                        context.fail("Unauthorized");
                        return;
                    }

                }).catch(err => {
                    console.error((err));
                    callback("Error: Internal Error");
                    return;
                });
            } else {
                console.log("did not find matching clientID");
                context.fail("Unauthorized");
                return;
            }
        }
    });
}

/**
 * AuthPolicy receives a set of allowed and denied methods and generates a valid
 * AWS policy for the API Gateway authorizer. The constructor receives the calling
 * user principal, the AWS account ID of the API owner, and an apiOptions object.
 * The apiOptions can contain an API Gateway RestApi Id, a region for the RestApi, and a
 * stage that calls should be allowed/denied for. For example
 * {
 *   restApiId: "xxxxxxxxxx",
 *   region: "us-east-1",
 *   stage: "dev"
 * }
 *
 * var testPolicy = new AuthPolicy("[principal user identifier]", "[AWS account id]", apiOptions);
 * testPolicy.allowMethod(AuthPolicy.HttpVerb.GET, "/users/username");
 * testPolicy.denyMethod(AuthPolicy.HttpVerb.POST, "/pets");
 * context.succeed(testPolicy.build());
 *
 * @class AuthPolicy
 * @constructor
 */
function AuthPolicy(principal, awsAccountId, apiOptions) {
    /**
     * The AWS account id the policy will be generated for. This is used to create
     * the method ARNs.
     *
     * @property awsAccountId
     * @type {String}
     */
    this.awsAccountId = awsAccountId;

    /**
     * The principal used for the policy, this should be a unique identifier for
     * the end user.
     *
     * @property principalId
     * @type {String}
     */
    this.principalId = principal;

    /**
     * The policy version used for the evaluation. This should always be "2012-10-17"
     *
     * @property version
     * @type {String}
     * @default "2012-10-17"
     */
    this.version = "2012-10-17";

    /**
     * The regular expression used to validate resource paths for the policy
     *
     * @property pathRegex
     * @type {RegExp}
     * @default '^\/[/.a-zA-Z0-9-\*]+

     */
    this.pathRegex = new RegExp('^[/.a-zA-Z0-9-\*]+
);

    // these are the internal lists of allowed and denied methods. These are lists
    // of objects and each object has 2 properties: A resource ARN and a nullable
    // conditions statement.
    // the build method processes these lists and generates the approriate
    // statements for the final policy
    this.allowMethods = [];
    this.denyMethods = [];

    if (!apiOptions || !apiOptions.restApiId) {
        this.restApiId = "*";
    } else {
        this.restApiId = apiOptions.restApiId;
    }
    if (!apiOptions || !apiOptions.region) {
        this.region = "*";
    } else {
        this.region = apiOptions.region;
    }
    if (!apiOptions || !apiOptions.stage) {
        this.stage = "*";
    } else {
        this.stage = apiOptions.stage;
    }
};

/**
 * A set of existing HTTP verbs supported by API Gateway. This property is here
 * only to avoid spelling mistakes in the policy.
 *
 * @property HttpVerb
 * @type {Object}
 */
AuthPolicy.HttpVerb = {
    GET: "GET",
    POST: "POST",
    PUT: "PUT",
    PATCH: "PATCH",
    HEAD: "HEAD",
    DELETE: "DELETE",
    OPTIONS: "OPTIONS",
    ALL: "*"
};

AuthPolicy.prototype = (function () {
    /**
     * Adds a method to the internal lists of allowed or denied methods. Each object in
     * the internal list contains a resource ARN and a condition statement. The condition
     * statement can be null.
     *
     * @method addMethod
     * @param {String} The effect for the policy. This can only be "Allow" or "Deny".
     * @param {String} he HTTP verb for the method, this should ideally come from the
     *                 AuthPolicy.HttpVerb object to avoid spelling mistakes
     * @param {String} The resource path. For example "/pets"
     * @param {Object} The conditions object in the format specified by the AWS docs.
     * @return {void}
     */
    var addMethod = function (effect, verb, resource, conditions) {
        if (verb != "*" && !AuthPolicy.HttpVerb.hasOwnProperty(verb)) {
            throw new Error("Invalid HTTP verb " + verb + ". Allowed verbs in AuthPolicy.HttpVerb");
        }

        if (!this.pathRegex.test(resource)) {
            throw new Error("Invalid resource path: " + resource + ". Path should match " + this.pathRegex);
        }

        var cleanedResource = resource;
        if (resource.substring(0, 1) == "/") {
            cleanedResource = resource.substring(1, resource.length);
        }
        var resourceArn = "arn:aws:execute-api:" +
            this.region + ":" +
            this.awsAccountId + ":" +
            this.restApiId + "/" +
            this.stage + "/" +
            verb + "/" +
            cleanedResource;

        if (effect.toLowerCase() == "allow") {
            this.allowMethods.push({
                resourceArn: resourceArn,
                conditions: conditions
            });
        } else if (effect.toLowerCase() == "deny") {
            this.denyMethods.push({
                resourceArn: resourceArn,
                conditions: conditions
            })
        }
    };

    /**
     * Returns an empty statement object prepopulated with the correct action and the
     * desired effect.
     *
     * @method getEmptyStatement
     * @param {String} The effect of the statement, this can be "Allow" or "Deny"
     * @return {Object} An empty statement object with the Action, Effect, and Resource
     *                  properties prepopulated.
     */
    var getEmptyStatement = function (effect) {
        effect = effect.substring(0, 1).toUpperCase() + effect.substring(1, effect.length).toLowerCase();
        var statement = {};
        statement.Action = "execute-api:Invoke";
        statement.Effect = effect;
        statement.Resource = [];

        return statement;
    };

    /**
     * This function loops over an array of objects containing a resourceArn and
     * conditions statement and generates the array of statements for the policy.
     *
     * @method getStatementsForEffect
     * @param {String} The desired effect. This can be "Allow" or "Deny"
     * @param {Array} An array of method objects containing the ARN of the resource
     *                and the conditions for the policy
     * @return {Array} an array of formatted statements for the policy.
     */
    var getStatementsForEffect = function (effect, methods) {
        var statements = [];

        if (methods.length > 0) {
            var statement = getEmptyStatement(effect);

            for (var i = 0; i < methods.length; i++) {
                var curMethod = methods[i];
                if (curMethod.conditions === null || curMethod.conditions.length === 0) {
                    statement.Resource.push(curMethod.resourceArn);
                } else {
                    var conditionalStatement = getEmptyStatement(effect);
                    conditionalStatement.Resource.push(curMethod.resourceArn);
                    conditionalStatement.Condition = curMethod.conditions;
                    statements.push(conditionalStatement);
                }
            }

            if (statement.Resource !== null && statement.Resource.length > 0) {
                statements.push(statement);
            }
        }

        return statements;
    };

    return {
        constructor: AuthPolicy,

        /**
         * Adds an allow "*" statement to the policy.
         *
         * @method allowAllMethods
         */
        allowAllMethods: function () {
            addMethod.call(this, "allow", "*", "*", null);
        },

        /**
         * Adds a deny "*" statement to the policy.
         *
         * @method denyAllMethods
         */
        denyAllMethods: function () {
            addMethod.call(this, "deny", "*", "*", null);
        },

        /**
         * Adds an API Gateway method (Http verb + Resource path) to the list of allowed
         * methods for the policy
         *
         * @method allowMethod
         * @param {String} The HTTP verb for the method, this should ideally come from the
         *                 AuthPolicy.HttpVerb object to avoid spelling mistakes
         * @param {string} The resource path. For example "/pets"
         * @return {void}
         */
        allowMethod: function (verb, resource) {
            addMethod.call(this, "allow", verb, resource, null);
        },

        /**
         * Adds an API Gateway method (Http verb + Resource path) to the list of denied
         * methods for the policy
         *
         * @method denyMethod
         * @param {String} The HTTP verb for the method, this should ideally come from the
         *                 AuthPolicy.HttpVerb object to avoid spelling mistakes
         * @param {string} The resource path. For example "/pets"
         * @return {void}
         */
        denyMethod: function (verb, resource) {
            addMethod.call(this, "deny", verb, resource, null);
        },

        /**
         * Adds an API Gateway method (Http verb + Resource path) to the list of allowed
         * methods and includes a condition for the policy statement. More on AWS policy
         * conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition
         *
         * @method allowMethodWithConditions
         * @param {String} The HTTP verb for the method, this should ideally come from the
         *                 AuthPolicy.HttpVerb object to avoid spelling mistakes
         * @param {string} The resource path. For example "/pets"
         * @param {Object} The conditions object in the format specified by the AWS docs
         * @return {void}
         */
        allowMethodWithConditions: function (verb, resource, conditions) {
            addMethod.call(this, "allow", verb, resource, conditions);
        },

        /**
         * Adds an API Gateway method (Http verb + Resource path) to the list of denied
         * methods and includes a condition for the policy statement. More on AWS policy
         * conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition
         *
         * @method denyMethodWithConditions
         * @param {String} The HTTP verb for the method, this should ideally come from the
         *                 AuthPolicy.HttpVerb object to avoid spelling mistakes
         * @param {string} The resource path. For example "/pets"
         * @param {Object} The conditions object in the format specified by the AWS docs
         * @return {void}
         */
        denyMethodWithConditions: function (verb, resource, conditions) {
            addMethod.call(this, "deny", verb, resource, conditions);
        },

        /**
         * Generates the policy document based on the internal lists of allowed and denied
         * conditions. This will generate a policy with two main statements for the effect:
         * one statement for Allow and one statement for Deny.
         * Methods that includes conditions will have their own statement in the policy.
         *
         * @method build
         * @return {Object} The policy object that can be serialized to JSON.
         */
        build: function () {
            if ((!this.allowMethods || this.allowMethods.length === 0) &&
                (!this.denyMethods || this.denyMethods.length === 0)) {
                throw new Error("No statements defined for the policy");
            }

            var policy = {};
            policy.principalId = this.principalId;
            var doc = {};
            doc.Version = this.version;
            doc.Statement = [];

            doc.Statement = doc.Statement.concat(getStatementsForEffect.call(this, "Allow", this.allowMethods));
            doc.Statement = doc.Statement.concat(getStatementsForEffect.call(this, "Deny", this.denyMethods));

            policy.policyDocument = doc;

            return policy;
        }
    };

})();