-
Notifications
You must be signed in to change notification settings - Fork 477
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
kabaluk
wants to merge
13
commits into
aws:master
Choose a base branch
from
kabaluk:add-from-custom-authorizer-attribute
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
57a23ae
Added FromCustomAuthorizerAttribute and tests.
kabaluk da724d0
Fixed function name on test.
kabaluk cc54ceb
Attempt at whitespace.
kabaluk c8752a3
Added FromCustomAuthorizerAttribute and tests.
kabaluk 4d44484
merge master
kabaluk e32534c
Must Fix Tests.
kabaluk b06c257
merge master.
kabaluk ec38c1a
Readded FromCustomAuthorizer
kabaluk 2876deb
Refactor the monolithic LambdaFunctionTemplate.tt into separate tt fi…
normj 14798bc
Update.
kabaluk e78a457
revert files.
kabaluk 4e4507e
merge master.
kabaluk a6e7821
Added unauthorized response as requested.
kabaluk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
...bda.Annotations.SourceGenerator/Models/Attributes/FromCustomAuthorizerAttributeBuilder.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
207 changes: 192 additions & 15 deletions
207
...ries/src/Amazon.Lambda.Annotations.SourceGenerator/Templates/APIGatewaySetupParameters.cs
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 19 additions & 0 deletions
19
Libraries/src/Amazon.Lambda.Annotations/APIGateway/FromCustomAuthorizerAttribute.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
81 changes: 81 additions & 0 deletions
81
...enerators.Tests/Snapshots/CustomAuthorizerHttpApiExample_HttpApiAuthorizer_Generated.g.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
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 = default(string); | ||
if (__request__.RequestContext?.Authorizer?.Lambda == null) | ||
{ | ||
validationErrors.Add("Could not find Lambda Authorizer data for request"); | ||
} | ||
else if (__request__.RequestContext?.Authorizer?.Lambda?.ContainsKey("authKey") == true) | ||
{ | ||
try | ||
{ | ||
authorizerValue = (string)Convert.ChangeType(__request__.RequestContext.Authorizer.Lambda["authKey"], typeof(string)); | ||
} | ||
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) | ||
{ | ||
validationErrors.Add($"Value {__request__.RequestContext.Authorizer.Lambda["authKey"]} at 'authKey' failed to satisfy constraint: {e.Message}"); | ||
} | ||
} | ||
|
||
// 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.3.0"); | ||
|
||
Environment.SetEnvironmentVariable(envName, envValue.ToString()); | ||
} | ||
} | ||
} |
81 changes: 81 additions & 0 deletions
81
...ourceGenerators.Tests/Snapshots/CustomAuthorizerRestExample_RestAuthorizer_Generated.g.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
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 = default(string); | ||
if (__request__.RequestContext?.Authorizer == null) | ||
{ | ||
validationErrors.Add("Could not find Authorizer data for request"); | ||
} | ||
else if (__request__.RequestContext?.Authorizer.ContainsKey("authKey") == true) | ||
{ | ||
try | ||
{ | ||
authorizerValue = (string)Convert.ChangeType(__request__.RequestContext.Authorizer["authKey"], typeof(string)); | ||
} | ||
catch (Exception e) when (e is InvalidCastException || e is FormatException || e is OverflowException || e is ArgumentException) | ||
{ | ||
validationErrors.Add($"Value {__request__.RequestContext.Authorizer["authKey"]} at 'authKey' failed to satisfy constraint: {e.Message}"); | ||
} | ||
} | ||
|
||
// 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.3.0"); | ||
|
||
Environment.SetEnvironmentVariable(envName, envValue.ToString()); | ||
} | ||
} | ||
} |
39 changes: 39 additions & 0 deletions
39
...notations.SourceGenerators.Tests/Snapshots/ServerlessTemplates/authorizerHttpApi.template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.3.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" | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
39 changes: 39 additions & 0 deletions
39
....Annotations.SourceGenerators.Tests/Snapshots/ServerlessTemplates/authorizerRest.template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.3.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" | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm wondering if there is missing data from the authorizer if we should be returning back
401
unauthorized instead of a bad parameter status code.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point. It should return 401.
I am away from pc for 2 weeks, feel free to change or i will once back.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would you be able to have a look at Norm's comments?