Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added FromCustomAuthorizerAttribute and tests. #1466

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ public static AttributeModel Build(AttributeData att, GeneratorExecutionContext
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if(att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.FromCustomAuthorizerAttribute), SymbolEqualityComparer.Default))
{
var data = FromCustomAuthorizerAttributeBuilder.Build(att);
model = new AttributeModel<FromCustomAuthorizerAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.HttpApiAttribute), SymbolEqualityComparer.Default))
{
var data = HttpApiAttributeBuilder.Build(att);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Amazon.Lambda.Annotations.APIGateway;
using Microsoft.CodeAnalysis;

namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
public class FromCustomAuthorizerAttributeBuilder
{
public static FromCustomAuthorizerAttribute Build(AttributeData att)
{
var data = new FromCustomAuthorizerAttribute();
foreach (var pair in att.NamedArguments)
{
if (pair.Key == nameof(data.Name) && pair.Value.Value is string value)
{
data.Name = value;
}
}

return data;
}
}
}

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public static class TypeFullNames
public const string FromHeaderAttribute = "Amazon.Lambda.Annotations.APIGateway.FromHeaderAttribute";
public const string FromBodyAttribute = "Amazon.Lambda.Annotations.APIGateway.FromBodyAttribute";
public const string FromRouteAttribute = "Amazon.Lambda.Annotations.APIGateway.FromRouteAttribute";
public const string FromCustomAuthorizerAttribute = "Amazon.Lambda.Annotations.APIGateway.FromCustomAuthorizerAttribute";

public static HashSet<string> Requests = new HashSet<string>
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System;

namespace Amazon.Lambda.Annotations.APIGateway
{
/// <summary>
/// Maps this parameter to a custom authorizer item
/// </summary>
/// <remarks>
/// Will try to get the specified key from Custom Authorizer values
/// </remarks>
[AttributeUsage(AttributeTargets.Parameter)]
public class FromCustomAuthorizerAttribute : Attribute, INamedAttribute
{
/// <summary>
/// Key of the value
/// </summary>
public string Name { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
</ItemGroup>

<ItemGroup>
<None Remove="snapshots\serverlesstemplates\authorizerHttpApi.template" />
<None Remove="Snapshots\ServerlessTemplates\authorizerrest.template" />
<None Remove="Snapshots\ServerlessTemplates\customizeResponse.template" />
<None Remove="Snapshots\ServerlessTemplates\dynamicexample.template" />
<None Remove="Snapshots\ServerlessTemplates\subnamespace.template" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;

namespace TestServerlessApp
{
public class CustomAuthorizerHttpApiExample_HttpApiAuthorizer_Generated
{
private readonly CustomAuthorizerHttpApiExample customAuthorizerHttpApiExample;

public CustomAuthorizerHttpApiExample_HttpApiAuthorizer_Generated()
{
SetExecutionEnvironment();
customAuthorizerHttpApiExample = new CustomAuthorizerHttpApiExample();
}

public async System.Threading.Tasks.Task<Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse> HttpApiAuthorizer(Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();

var authorizerValue = __request__.RequestContext.Authorizer.Lambda["authKey"].ToString();
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
return errorResult;
}

await customAuthorizerHttpApiExample.HttpApiAuthorizer(authorizerValue, __context__);

return new Amazon.Lambda.APIGatewayEvents.APIGatewayHttpApiV2ProxyResponse
{
StatusCode = 200
};
}

private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";

var envValue = new StringBuilder();

// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}

envValue.Append("amazon-lambda-annotations_0.13.0.0");

Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;

namespace TestServerlessApp
{
public class CustomAuthorizerRestExample_RestAuthorizer_Generated
{
private readonly CustomAuthorizerRestExample customAuthorizerRestExample;

public CustomAuthorizerRestExample_RestAuthorizer_Generated()
{
SetExecutionEnvironment();
customAuthorizerRestExample = new CustomAuthorizerRestExample();
}

public async System.Threading.Tasks.Task<Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse> RestAuthorizer(Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest __request__, Amazon.Lambda.Core.ILambdaContext __context__)
{
var validationErrors = new List<string>();

var authorizerValue = __request__.RequestContext.Authorizer["authKey"].ToString();
// return 400 Bad Request if there exists a validation error
if (validationErrors.Any())
{
var errorResult = new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
Body = @$"{{""message"": ""{validationErrors.Count} validation error(s) detected: {string.Join(",", validationErrors)}""}}",
Headers = new Dictionary<string, string>
{
{"Content-Type", "application/json"},
{"x-amzn-ErrorType", "ValidationException"}
},
StatusCode = 400
};
return errorResult;
}

await customAuthorizerRestExample.RestAuthorizer(authorizerValue, __context__);

return new Amazon.Lambda.APIGatewayEvents.APIGatewayProxyResponse
{
StatusCode = 200
};
}

private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";

var envValue = new StringBuilder();

// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}

envValue.Append("amazon-lambda-annotations_0.13.0.0");

Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Description": "This template is partially managed by Amazon.Lambda.Annotations (v0.13.0.0).",
"Resources": {
"HttpApiAuthorizerTest": {
"Type": "AWS::Serverless::Function",
"Metadata": {
"Tool": "Amazon.Lambda.Annotations",
"SyncedEvents": [
"RootGet"
]
},
"Properties": {
"MemorySize": 256,
"Timeout": 30,
"Policies": [
"AWSLambdaBasicExecutionRole"
],
"PackageType": "Image",
"ImageUri": ".",
"ImageConfig": {
"Command": [
"TestProject::TestServerlessApp.CustomAuthorizerHttpApiExample_HttpApiAuthorizer_Generated::HttpApiAuthorizer"
]
},
"Events": {
"RootGet": {
"Type": "HttpApi",
"Properties": {
"Path": "/api/authorizer",
"Method": "GET"
}
}
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Description": "This template is partially managed by Amazon.Lambda.Annotations (v0.13.0.0).",
"Resources": {
"RestAuthorizerTest": {
"Type": "AWS::Serverless::Function",
"Metadata": {
"Tool": "Amazon.Lambda.Annotations",
"SyncedEvents": [
"RootGet"
]
},
"Properties": {
"MemorySize": 256,
"Timeout": 30,
"Policies": [
"AWSLambdaBasicExecutionRole"
],
"PackageType": "Image",
"ImageUri": ".",
"ImageConfig": {
"Command": [
"TestProject::TestServerlessApp.CustomAuthorizerRestExample_RestAuthorizer_Generated::RestAuthorizer"
]
},
"Events": {
"RootGet": {
"Type": "Api",
"Properties": {
"Path": "/rest/authorizer",
"Method": "GET"
}
}
}
}
}
}
}
Loading