Beispiel #1
0
        public APIGatewayCustomAuthorizerResponse GatewayPolicy(Boolean allowed, string userEmail = "")
        {
            string effect = "Deny";

            if (allowed == true)
            {
                effect = "Allow";
            }

            APIGatewayCustomAuthorizerResponse response = new APIGatewayCustomAuthorizerResponse()
            {
                PrincipalID    = userEmail,
                PolicyDocument = new APIGatewayCustomAuthorizerPolicy {
                    Version   = "2012-10-17",
                    Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>()
                    {
                        new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement {
                            Action = new HashSet <string>()
                            {
                                "execute-api:Invoke"
                            },
                            Effect   = effect,
                            Resource = new HashSet <string>()
                            {
                                Environment.GetEnvironmentVariable("ApiGatewayArn")
                            }
                        }
                    }
                }
            };

            return(response);
        }
Beispiel #2
0
        private APIGatewayCustomAuthorizerResponse GetAllowResponse(string principalId)
        {
            var res = new APIGatewayCustomAuthorizerResponse()
            {
                PrincipalID    = principalId,
                PolicyDocument = new APIGatewayCustomAuthorizerPolicy()
                {
                    Version   = "2012-10-17",
                    Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>()
                    {
                        new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement()
                        {
                            Effect = "Allow",
                            Action = new HashSet <string>()
                            {
                                "execute-api:Invoke"
                            },
                            Resource = new HashSet <string>()
                            {
                                "arn:aws:execute-api:ap-southeast-1:022173912118:f3cmroo3se/*/GET/download/*",
                                "arn:aws:execute-api:ap-southeast-1:022173912118:f3cmroo3se/*/POST/upload/*"
                            }
                        }
                    }
                }
            };

            return(res);
        }
Beispiel #3
0
 private void AddAuthPolicyDocument(APIGatewayCustomAuthorizerResponse authPolicy)
 {
     authPolicy.PrincipalID    = "user";
     authPolicy.PolicyDocument = new APIGatewayCustomAuthorizerPolicy
     {
         Version   = "2012-10-17",
         Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>()
     };
 }
        public void APIGatewayAuthorizerResponseTest()
        {
            var context = new APIGatewayCustomAuthorizerContextOutput();

            context["field1"] = "value1";
            context["field2"] = "value2";

            var response = new APIGatewayCustomAuthorizerResponse
            {
                PrincipalID        = "prin1",
                UsageIdentifierKey = "usageKey",
                Context            = context,
                PolicyDocument     = new APIGatewayCustomAuthorizerPolicy
                {
                    Version   = "2012-10-17",
                    Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>
                    {
                        new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
                        {
                            Action = new HashSet <string> {
                                "execute-api:Invoke"
                            },
                            Effect   = "Allow",
                            Resource = new HashSet <string> {
                                "*"
                            }
                        }
                    }
                }
            };

            string serializedJson;

            using (MemoryStream stream = new MemoryStream())
            {
                var serializer = new JsonSerializer();
                serializer.Serialize(response, stream);

                stream.Position = 0;
                serializedJson  = Encoding.UTF8.GetString(stream.ToArray());
            }

            JObject root = Newtonsoft.Json.JsonConvert.DeserializeObject(serializedJson) as JObject;

            Assert.Equal("prin1", root["principalId"]);
            Assert.Equal("usageKey", root["usageIdentifierKey"]);
            Assert.Equal("value1", root["context"]["field1"]);
            Assert.Equal("value2", root["context"]["field2"]);

            Assert.Equal("2012-10-17", root["policyDocument"]["Version"]);
            Assert.Equal("execute-api:Invoke", root["policyDocument"]["Statement"][0]["Action"][0]);
            Assert.Equal("Allow", root["policyDocument"]["Statement"][0]["Effect"]);
            Assert.Equal("*", root["policyDocument"]["Statement"][0]["Resource"][0]);
        }
Beispiel #5
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest aPIGatewayCustomAuthorizerRequest, ILambdaContext context)
        {
            context.Logger.Log(JsonConvert.SerializeObject(aPIGatewayCustomAuthorizerRequest));
            var authPolicy = new APIGatewayCustomAuthorizerResponse();

            // attach policy document for resource policy to allow or deny.
            AddAuthPolicyDocument(authPolicy);

            //Custom

            var response = AuthResponse(authPolicy, "Deny", aPIGatewayCustomAuthorizerRequest.MethodArn);

            context.Logger.Log(JsonConvert.SerializeObject(response));
            return(response);
        }
        public void TestCustomAuthorizerSerialization()
        {
            var response = new APIGatewayCustomAuthorizerResponse
            {
                PrincipalID = "com.amazon.someuser",
                Context     = new APIGatewayCustomAuthorizerContextOutput
                {
                    StringKey = "Hey I'm a string",
                    BoolKey   = true,
                    NumKey    = 9
                },
                PolicyDocument = new APIGatewayCustomAuthorizerPolicy
                {
                    Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>
                    {
                        new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
                        {
                            Effect = "Allow",
                            Action = new HashSet <string> {
                                "execute-api:Invoke"
                            },
                            Resource = new HashSet <string>
                            {
                                "arn:aws:execute-api:us-west-2:1234567890:apit123d45/Prod/GET/*"
                            }
                        }
                    }
                }
            };

            var json = JsonSerializer.Serialize(response, new JsonSerializerOptions
            {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            Assert.NotNull(json);
            var expected = "{\"principalId\":\"com.amazon.someuser\",\"policyDocument\":{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"execute-api:Invoke\"],\"Resource\":[\"arn:aws:execute-api:us-west-2:1234567890:apit123d45/Prod/GET/*\"]}]},\"context\":{\"stringKey\":\"Hey I'm a string\",\"boolKey\":true,\"numKey\":9},\"usageIdentifierKey\":null}";

            Assert.Equal(expected, json);
        }
Beispiel #7
0
        private APIGatewayCustomAuthorizerResponse GeneratePolicy(string principalId, string effect, string resource)
        {
            APIGatewayCustomAuthorizerResponse authResponse = new APIGatewayCustomAuthorizerResponse();

            authResponse.PolicyDocument           = new APIGatewayCustomAuthorizerPolicy();
            authResponse.PolicyDocument.Version   = "2012-10-17";// default version
            authResponse.PolicyDocument.Statement = new System.Collections.Generic.List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>();
            System.Collections.Generic.HashSet <string> Actions = new System.Collections.Generic.HashSet <string>();
            Actions.Add("execute-api:Invoke");
            System.Collections.Generic.HashSet <string> Resources = new System.Collections.Generic.HashSet <string>();
            Resources.Add(resource);

            authResponse.PolicyDocument.Statement.Add(new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement()
            {
                Action   = Actions,
                Effect   = effect,
                Resource = Resources
            });


            return(authResponse);
        }
Beispiel #8
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public APIGatewayCustomAuthorizerResponse FunctionHandler(APIGatewayCustomAuthorizerRequest apiRequest, ILambdaContext context)
        {
            bool authorized = false;

            if (!string.IsNullOrWhiteSpace(apiRequest.AuthorizationToken))
            {
                authorized = ValidateToken(apiRequest.AuthorizationToken, context);
            }

            var policy = new APIGatewayCustomAuthorizerPolicy
            {
                Version   = "2012-10-17",
                Statement = new List <APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement>
                {
                    new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement
                    {
                        Action   = new HashSet <string>(new string[] { "execute-api:Invoke" }),
                        Effect   = authorized ? "Allow" : "Deny",
                        Resource = new HashSet <string>(new string[] { apiRequest.MethodArn }) // api gateway endpoint arn
                    }
                }
            };

            var contextOutput = new APIGatewayCustomAuthorizerContextOutput();

            contextOutput["User"] = authorized ? AllowedUserName : "******";
            contextOutput["Path"] = apiRequest.MethodArn;

            var response = new APIGatewayCustomAuthorizerResponse
            {
                Context        = contextOutput,
                PolicyDocument = policy
            };

            return(response);
        }
        public async Task <APIGatewayCustomAuthorizerResponse> FunctionHandler(APIGatewayCustomAuthorizerRequest request)
        {
            var token = request.AuthorizationToken;
            var type  = AuthTokenType.JWT;

            var response  = new APIGatewayCustomAuthorizerResponse();
            var policy    = response.PolicyDocument;
            var statement = new APIGatewayCustomAuthorizerPolicy.IAMPolicyStatement()
            {
                Action   = new HashSet <string>(),
                Resource = new HashSet <string>()
            };

            if (Validator.Validate(type, token))
            {
                var vars      = request.MethodArn.Split(':');
                var apiVars   = vars[5].Split('/');
                var region    = vars[3];
                var accountId = vars[4];
                var apiId     = apiVars[0];
                var stage     = apiVars[1];

                Console.WriteLine(apiVars.Length);

                if (apiVars.Length > 4)
                {
                    int id;
                    if (int.TryParse(apiVars[4], out id))
                    {
                        var service = apiVars[3];

                        Console.WriteLine(service);
                        Console.WriteLine(id);

                        var req = new Request()
                        {
                            Operation = Operation.VerifyUser,
                            AuthToken = token,
                            Payload   = JObject.FromObject(new VerifyUserPayload()
                            {
                                ResourceId = id
                            })
                        };

                        var lambdaClient  = new AmazonLambdaClient();
                        var invokeRequest = new InvokeRequest()
                        {
                            FunctionName = Enum.GetName(typeof(Service), serviceMapping[service]),
                            Payload      = JsonConvert.SerializeObject(req)
                        };

                        var lambdaRes = await lambdaClient.InvokeAsync(invokeRequest);

                        var res = new StreamReader(lambdaRes.Payload).ReadToEnd();

                        if (res.Contains(Enum.GetName(typeof(VerifyResult), VerifyResult.Allow)))
                        {
                            var any = Resource.Any.GetStringValue();
                            this.AllowOperation(
                                statement,
                                CustomAuthorizerHelper.ComposeAction(Policy.Action.Invoke),
                                CustomAuthorizerHelper.ComposeResource(region, accountId, apiId, stage, new ResourceAccess(any, any))
                                );
                        }
                        else
                        {
                            this.DenyAll(statement);
                        }
                    }
                    else
                    {
                        var any = Resource.Any.GetStringValue();
                        this.AllowOperation(
                            statement,
                            CustomAuthorizerHelper.ComposeAction(Policy.Action.Invoke),
                            CustomAuthorizerHelper.ComposeResource(region, accountId, apiId, stage, new ResourceAccess(any, any))
                            );
                    }
                }
                else
                {
                    var any = Resource.Any.GetStringValue();
                    this.AllowOperation(
                        statement,
                        CustomAuthorizerHelper.ComposeAction(Policy.Action.Invoke),
                        CustomAuthorizerHelper.ComposeResource(region, accountId, apiId, stage, new ResourceAccess(any, any))
                        );
                }
            }
            else
            {
                this.DenyAll(statement);
            }

            policy.Statement.Add(statement);
            return(response);
        }
Beispiel #10
0
        private APIGatewayCustomAuthorizerResponse AuthResponse(APIGatewayCustomAuthorizerResponse authPolicyResponse, string access, string methodArn)
        {
            authPolicyResponse.PolicyDocument.Statement.Add(GetPolicy(access, methodArn));

            return(authPolicyResponse);
        }