Skip to content

feat: module to ease cors configuration #831

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

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
<module>powertools-test-suite</module>
<module>powertools-cloudformation</module>
<module>powertools-idempotency</module>
<module>powertools-cors</module>
</modules>

<scm>
Expand Down
117 changes: 117 additions & 0 deletions powertools-cors/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>powertools-parent</artifactId>
<groupId>software.amazon.lambda</groupId>
<version>1.12.0</version>
</parent>
<artifactId>powertools-cors</artifactId>
<name>AWS Lambda Powertools for Java library CORS Configuration</name>

<url>https://aws.amazon.com/lambda/</url>
<issueManagement>
<system>GitHub Issues</system>
<url>https://github.com/awslabs/aws-lambda-powertools-java/issues</url>
</issueManagement>
<scm>
<url>https://github.com/awslabs/aws-lambda-powertools-java.git</url>
</scm>
<developers>
<developer>
<name>AWS Lambda Powertools team</name>
<organization>Amazon Web Services</organization>
<organizationUrl>https://aws.amazon.com/</organizationUrl>
</developer>
</developers>

<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://aws.oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>

<dependencies>
<dependency>
<groupId>software.amazon.lambda</groupId>
<artifactId>powertools-core</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-events</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>

<!-- Test dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-tests</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit-pioneer</groupId>
<artifactId>junit-pioneer</artifactId>
<version>1.6.2</version>
<scope>test</scope>
</dependency>
</dependencies>

<profiles>
<profile>
<id>jdk16</id>
<activation>
<jdk>[16,)</jdk>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<argLine>
--add-opens java.base/java.util=ALL-UNNAMED
--add-opens java.base/java.lang=ALL-UNNAMED
</argLine>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.cors;

public interface Constants {
String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";

String ENV_ACCESS_CONTROL_ALLOW_HEADERS = "ACCESS_CONTROL_ALLOW_HEADERS";
String ENV_ACCESS_CONTROL_EXPOSE_HEADERS = "ACCESS_CONTROL_EXPOSE_HEADERS";
String ENV_ACCESS_CONTROL_ALLOW_ORIGIN = "ACCESS_CONTROL_ALLOW_ORIGIN";
String ENV_ACCESS_CONTROL_ALLOW_METHODS = "ACCESS_CONTROL_ALLOW_METHODS";
String ENV_ACCESS_CONTROL_ALLOW_CREDENTIALS = "ACCESS_CONTROL_ALLOW_CREDENTIALS";
String ENV_ACCESS_CONTROL_MAX_AGE = "ACCESS_CONTROL_MAX_AGE";

String WILDCARD = "*";

String DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS = "Authorization, *";
String DEFAULT_ACCESS_CONTROL_EXPOSE_HEADERS = WILDCARD;
String DEFAULT_ACCESS_CONTROL_ALLOW_METHODS = WILDCARD;
String DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN = WILDCARD;
boolean DEFAULT_ACCESS_CONTROL_ALLOW_CREDENTIALS = true;
int DEFAULT_ACCESS_CONTROL_MAX_AGE = 29;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.cors;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import static software.amazon.lambda.powertools.cors.Constants.*;

/**
* CrossOrigin annotation to be placed on a Lambda function configured with API Gateway as proxy.<br/>
* Your function must implement <pre>RequestHandler&lt;APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent&gt;</pre>
* It will automatically add the Cross-Origins Resource Sharing (CORS) headers in the response sent to API Gateway & the client.<br/>
* By default, it allows everything (all methods, headers and origins). Make sure to restrict to your need.
* <p></p>You can use the annotation alone and keep the default setup (or use environment variables instead, see below):<br/>
* <pre>
* &#64;CrossOrigin
* public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context ctx) {
* // ...
* return response;
* }
* </pre>
* </p>
* <p>You can use the annotation and customize the parameters:<br/>
* <pre>
* &#64;CrossOrigin(
* origins = "origin.com",
* allowedHeaders = "Content-Type",
* methods = "POST, OPTIONS"
* )
* public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context ctx) {
* // ...
* return response;
* }
* </pre>
* </p>
* <p>You can also use the following environment variables if you wish to externalize the configuration:<ul>
* <li><pre>ACCESS_CONTROL_ALLOW_HEADERS</pre></li>
* <li><pre>ACCESS_CONTROL_EXPOSE_HEADERS</pre></li>
* <li><pre>ACCESS_CONTROL_ALLOW_ORIGIN</pre></li>
* <li><pre>ACCESS_CONTROL_ALLOW_METHODS</pre></li>
* <li><pre>ACCESS_CONTROL_ALLOW_CREDENTIALS</pre></li>
* <li><pre>ACCESS_CONTROL_MAX_AGE</pre></li>
* </ul></p>
* Note that if you configure cross-origin both in environment variables and programmatically with the annotation,
* environment variables take the precedence over the annotation.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CrossOrigin {
/**
* Allowed methods (Access-Control-Request-Methods). You can set several methods separated by a comma (',').
* Default: * (allow all methods)
*/
String methods() default DEFAULT_ACCESS_CONTROL_ALLOW_METHODS;
/**
* Allowed origins (Access-Control-Allow-Origin). You can set several origins separated by a comma (',').
* If you do so, only the origin matching the client origin will be sent in the response.
* An origin must be a well-formed url: {protocol}://{host}[:{port}]
* Default: * (allow all origins)
*/
String origins() default DEFAULT_ACCESS_CONTROL_ALLOW_ORIGIN;
/**
* Allowed headers (Access-Control-Request-Headers). You can set several headers separated by a comma (',').
* Note that Authorization is not part of the wildcard and must be set explicitly
* Default: Authorization, * (allow all headers)
*/
String allowedHeaders() default DEFAULT_ACCESS_CONTROL_ALLOW_HEADERS;
/**
* Exposed headers (Access-Control-Expose-Headers). You can set several headers separated by a comma (',').
* Default: * (expose all headers)
*/
String exposedHeaders() default DEFAULT_ACCESS_CONTROL_EXPOSE_HEADERS;
/**
* If credential mode is allowed (ACCESS_CONTROL_ALLOW_CREDENTIALS)
* Default: true
*/
boolean allowCredentials() default DEFAULT_ACCESS_CONTROL_ALLOW_CREDENTIALS;
/**
* How long (in seconds) the preflight request is cached (default: 29)
*/
int maxAge() default DEFAULT_ACCESS_CONTROL_MAX_AGE;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2022 Amazon.com, Inc. or its affiliates.
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package software.amazon.lambda.powertools.cors.internal;

import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import software.amazon.lambda.powertools.cors.CrossOrigin;

import java.lang.reflect.Method;

import static software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor.isHandlerMethod;
import static software.amazon.lambda.powertools.core.internal.LambdaHandlerProcessor.placedOnRequestHandler;

@Aspect
public class CrossOriginAspect {

private static final Logger LOG = LogManager.getLogger(CrossOriginAspect.class);

@Pointcut("@annotation(crossOrigin)")
public void callAt(CrossOrigin crossOrigin) {
}

@Around(value = "callAt(crossOrigin) && execution(@CrossOrigin * *.*(..))", argNames = "pjp,crossOrigin")
public Object around(ProceedingJoinPoint pjp,
CrossOrigin crossOrigin) throws Throwable {
Object result = pjp.proceed(pjp.getArgs());

if (!isHandlerMethod(pjp) || !placedOnRequestHandler(pjp) || !isApiGatewayRequest(pjp)) {
LOG.warn("@Cors annotation must be used on a Lambda handler that receives APIGatewayProxyRequestEvent and return APIGatewayProxyResponseEvent");
return result;
}

CrossOriginHandler crossOriginHandler = new CrossOriginHandler(crossOrigin);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recommendation generated by Amazon CodeGuru Reviewer. Leave feedback on this recommendation by replying to the comment or by reacting to the comment using emoji.

Problem:
This line of code lacks validation when processing input data through the following parameter: 'crossOrigin' (index: 1 | type: CrossOrigin). The parameter is exposed to external callers, because its enclosing class and method are publicly accessible. This means that upstream validation, if it exists, can be bypassed. Other validated parameters: 'pjp'. The same parameter type is validated here for example: aws-lambda-powertools-java/powertools-cors/src/main/java/software/amazon/lambda/powertools/cors/internal/CrossOriginHandler.java:43. Malicious, malformed, or unbounded inputs can cause unexpected runtime behavior or crashes, and can slow performance.

Fix:
Add checks to ensure the validity of the parameter's value, such as testing it for nullness (for example, using the @nonnull annotation as described in the Lombok library), emptiness, or equality. Or to prevent direct calls to it, reduce the method's visibility.

Learn more about potential threats and guidance from the Common Weakness Enumeration website and the OWASP Cheat Sheet series.

return proceed(pjp, result, crossOriginHandler);
}

private Object proceed(ProceedingJoinPoint pjp, Object result, CrossOriginHandler crossOriginHandler) {
try {
APIGatewayProxyRequestEvent request = (APIGatewayProxyRequestEvent) pjp.getArgs()[0];
APIGatewayProxyResponseEvent response = (APIGatewayProxyResponseEvent) result;

return crossOriginHandler.process(request, response);
} catch (Exception e) {
// should not happen, but we don't want to fail because of this
LOG.error("Error while setting CORS headers. If you think this is an issue in PowerTools, please open an issue on GitHub.", e);
}
return result;
}

private boolean isApiGatewayRequest(ProceedingJoinPoint pjp) {
Method method = ((MethodSignature) pjp.getSignature()).getMethod();
return method.getReturnType().equals(APIGatewayProxyResponseEvent.class) &&
pjp.getArgs()[0] instanceof APIGatewayProxyRequestEvent;
}
}
Loading