mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambdaweb): enforce IamAuth on Web Function endpoints (#5855)
* fix(lambdaweb): accept role and user ARNs as resource policy principals AWS checks an ARN principal against a pattern that allows a slash, so a role or user ARN passes. Any other AWS principal value is still checked against the pattern without a slash. * feat(lambdaweb): verify SigV4 and InvokeWebFunctionEndpoint on IamAuth endpoints An IamAuth endpoint takes a request signed for the service lambda in the endpoint's region, in the Authorization header or a presigned query. The X-Amz-Content-SHA256 header is required and is the payload hash, as on AWS. A refused request gets the AWS 403 page with no error type. The check runs after the rateLimit 0 page and before the rate limit. Under IAM enforcement the signer also needs lambda:InvokeWebFunctionEndpoint on the endpoint ARN from its identity policy or the function's resource policy, with the auth type and the function tags as condition keys. An Authorization that is an AWS signature is dropped before the app on every endpoint, together with X-Amz-Security-Token. * fix(lambdaweb): give the app the path without dot segments and sign only the normalized path Lambda removes dot segments before the app sees the path, on every endpoint, and keeps repeated slashes and encoded dots. An IamAuth signature counts only over the path as signers normalize it. A signature over the path as sent is refused when the two differ. Floci forwarded the path as sent and took a signature over either form, so a request signed for /a/c could reach the app as /a/./b/../c. * fix(lambdaweb): answer 502 when the caller check fails inside Floci A malformed date or query is still a refused signature. Any other failure, such as in IAM storage, no longer looks like a 403. The endpoint answers it with 502 and no error type, as AWS answers its own failures. * fix(lambdaweb): check a principal against the ARN pattern only under AWS Lambda allows a path only in an ARN under the AWS key. A CanonicalUser or Federated value never matches that pattern. * docs(lambdaweb): MultiRegion SigV4, presigned queries and dot segments on the way to the app * chore(auth): share SigV4 signature parsing and age limits with API Gateway The API Gateway authorizer and Lambda Web IamAuth read a SigV4 signature from the Authorization header or a presigned query, and check its age, in the same way. Both now use one record in core.common.auth. Each still decides which placement wins and where it reads the session token, so neither behaves differently.
This commit is contained in:
1 parent
1d5940944e
commit
5eb4eecf99
16 files changed
+1243
-92
No files matched your search
@@ -0,0 +1,94 @@
|
||||
package io.github.hectorvent.floci.core.common.auth;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.auth.SigV4SignedRequest.Freshness;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SigV4SignedRequestTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-10-17T12:00:00Z");
|
||||
private static final DateTimeFormatter AMZ_DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final String AUTHORIZATION = "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request,"
|
||||
+ " SignedHeaders=Host;X-Amz-Date, Signature=abc123";
|
||||
|
||||
@Test
|
||||
void theHeaderSignatureNeedsEveryPartAndADate() {
|
||||
SigV4SignedRequest signed = SigV4SignedRequest.fromHeader(AUTHORIZATION, "20261017T120000Z");
|
||||
assertEquals("AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request", signed.credential());
|
||||
assertEquals("host;x-amz-date", signed.signedHeaders());
|
||||
assertEquals("abc123", signed.signature());
|
||||
assertFalse(signed.presigned());
|
||||
|
||||
assertNull(SigV4SignedRequest.fromHeader(AUTHORIZATION, null));
|
||||
assertNull(SigV4SignedRequest.fromHeader("Bearer abc", "20261017T120000Z"));
|
||||
assertNull(SigV4SignedRequest.fromHeader("AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request,"
|
||||
+ " SignedHeaders=host", "20261017T120000Z"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePresignedSignatureNeedsEveryPartAndKeepsAnExpiryItCannotRead() {
|
||||
Map<String, String> query = presigned(NOW, "300");
|
||||
SigV4SignedRequest signed = SigV4SignedRequest.fromQuery(query::get);
|
||||
assertTrue(signed.presigned());
|
||||
assertEquals(300L, signed.expiresSeconds());
|
||||
|
||||
query.put("X-Amz-Expires", "soon");
|
||||
assertNull(SigV4SignedRequest.fromQuery(query::get).expiresSeconds());
|
||||
query.remove("X-Amz-Signature");
|
||||
assertNull(SigV4SignedRequest.fromQuery(query::get));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHeaderSignatureIsFreshWithinFiveMinutesEitherWay() {
|
||||
assertEquals(Freshness.FRESH, header(NOW.minus(Duration.ofMinutes(4))).freshness(NOW));
|
||||
assertEquals(Freshness.FRESH, header(NOW.plus(Duration.ofMinutes(4))).freshness(NOW));
|
||||
assertEquals(Freshness.EXPIRED, header(NOW.minus(Duration.ofMinutes(6))).freshness(NOW));
|
||||
assertEquals(Freshness.NOT_YET_VALID, header(NOW.plus(Duration.ofMinutes(6))).freshness(NOW));
|
||||
assertEquals(Freshness.MALFORMED_DATE,
|
||||
SigV4SignedRequest.fromHeader(AUTHORIZATION, "20261017T99").freshness(NOW));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPresignedSignatureLastsItsExpiryOfUpToSevenDays() {
|
||||
assertEquals(Freshness.FRESH, query(NOW.minus(Duration.ofMinutes(4)), "300").freshness(NOW));
|
||||
assertEquals(Freshness.EXPIRED, query(NOW.minus(Duration.ofMinutes(6)), "300").freshness(NOW));
|
||||
assertEquals(Freshness.NOT_YET_VALID, query(NOW.plus(Duration.ofMinutes(6)), "300").freshness(NOW));
|
||||
assertEquals(Freshness.FRESH, query(NOW.minus(Duration.ofDays(6)), "604800").freshness(NOW));
|
||||
assertEquals(Freshness.BAD_EXPIRES, query(NOW, "604801").freshness(NOW));
|
||||
assertEquals(Freshness.BAD_EXPIRES, query(NOW, "0").freshness(NOW));
|
||||
assertEquals(Freshness.BAD_EXPIRES, query(NOW, null).freshness(NOW));
|
||||
}
|
||||
|
||||
private static SigV4SignedRequest header(Instant signedAt) {
|
||||
return SigV4SignedRequest.fromHeader(AUTHORIZATION, AMZ_DATE.format(signedAt));
|
||||
}
|
||||
|
||||
private static SigV4SignedRequest query(Instant signedAt, String expires) {
|
||||
Map<String, String> query = presigned(signedAt, expires);
|
||||
return SigV4SignedRequest.fromQuery(query::get);
|
||||
}
|
||||
|
||||
private static Map<String, String> presigned(Instant signedAt, String expires) {
|
||||
Map<String, String> query = new HashMap<>();
|
||||
query.put("X-Amz-Credential", "AKIDEXAMPLE/20261017/us-east-1/lambda/aws4_request");
|
||||
query.put("X-Amz-SignedHeaders", "host");
|
||||
query.put("X-Amz-Signature", "abc123");
|
||||
query.put("X-Amz-Date", AMZ_DATE.format(signedAt));
|
||||
if (expires != null) {
|
||||
query.put("X-Amz-Expires", expires);
|
||||
}
|
||||
return query;
|
||||
}
|
||||
}
|
||||
+45
@@ -161,6 +161,51 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
assertTrue(chunked.startsWith("HTTP/1.1 200 "), chunked);
|
||||
assertTrue(chunked.contains("\"bodyLength\":17"), chunked);
|
||||
assertTrue(chunked.contains("\"transfer-encoding\":\"chunked\""), chunked);
|
||||
|
||||
// The app gets the path without dot segments, as on AWS. Repeated slashes stay.
|
||||
String dotted = raw("GET /a//b/./c/../d?x=1 HTTP/1.1\r\nHost: " + domain + "\r\nConnection: close\r\n\r\n");
|
||||
assertTrue(dotted.contains("\"url\":\"/a//b/d?x=1\""), dotted);
|
||||
|
||||
// An AWS signature and its session token never reach the app. Other credentials do.
|
||||
given().header("Host", domain).header("Authorization", "Bearer abc").header("X-Amz-Security-Token", "tok")
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.body("headers.authorization", equalTo("Bearer abc"))
|
||||
.body("headers.x-amz-security-token", equalTo("tok"));
|
||||
given().header("Host", domain).header("Authorization", "AWS4-HMAC-SHA256 Credential=x")
|
||||
.header("X-Amz-Security-Token", "tok").header("X-Amz-Date", "20260101T000000Z")
|
||||
.when().get("/")
|
||||
.then().statusCode(200)
|
||||
.body("headers.authorization", nullValue())
|
||||
.body("headers.x-amz-security-token", nullValue())
|
||||
.body("headers.x-amz-date", equalTo("20260101T000000Z"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void anIamAuthEndpointServesSignedRequestsWithoutTheirSignature() throws Exception {
|
||||
String domain = createFunction(30);
|
||||
given().contentType("application/json").body("{\"authType\": \"IamAuth\"}")
|
||||
.when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")
|
||||
.then().statusCode(202);
|
||||
given().header("Host", domain).when().get("/").then().statusCode(403);
|
||||
|
||||
LambdaWebRequestSigner.Signed signed = new LambdaWebRequestSigner().sign("POST", domain, "/items?b=2&a=1");
|
||||
given().urlEncodingEnabled(false).header("Host", domain).headers(signed.headers()).body("hello body")
|
||||
.when().post(signed.pathAndQuery())
|
||||
.then().statusCode(200)
|
||||
.body("url", equalTo(signed.pathAndQuery()))
|
||||
.body("bodyLength", equalTo(10))
|
||||
.body("headers.authorization", nullValue())
|
||||
.body("headers.x-amz-content-sha256", equalTo("UNSIGNED-PAYLOAD"))
|
||||
.body("headers.x-amz-date", equalTo(signed.headers().get("X-Amz-Date")));
|
||||
|
||||
// A presigned request reaches the app with its query as sent.
|
||||
LambdaWebRequestSigner.Signed presigned = new LambdaWebRequestSigner().presigned().sign("GET", domain, "/q");
|
||||
given().urlEncodingEnabled(false).header("Host", domain).headers(presigned.headers())
|
||||
.when().get(presigned.pathAndQuery())
|
||||
.then().statusCode(200)
|
||||
.body("url", equalTo(presigned.pathAndQuery()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+40
-2
@@ -17,6 +17,7 @@ import java.util.Map;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -99,6 +100,39 @@ class LambdaWebDataPlaneIntegrationTest {
|
||||
return read.toString();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIamAuthEndpointRefusesARequestWithoutAValidSignature() {
|
||||
String functionName = "dp-iam-" + Long.toString(System.nanoTime(), 36);
|
||||
String domain = createFunction(functionName, "IamAuth");
|
||||
|
||||
Response unsigned = given().header("Host", domain).when().get("/");
|
||||
unsigned.then().statusCode(403)
|
||||
.header("content-type", "text/html")
|
||||
.header("connection", "keep-alive")
|
||||
.header("lambda-web-error-type", nullValue())
|
||||
.header("lambda-web-request-id", matchesPattern(REQUEST_ID))
|
||||
.header("content-length", "230")
|
||||
.body(equalTo(LambdaWebErrorPages.html(LambdaWebErrorPages.FORBIDDEN,
|
||||
unsigned.header("lambda-web-request-id"))));
|
||||
given().header("Host", domain).when().head("/")
|
||||
.then().statusCode(403).header("content-length", "230").body(equalTo(""));
|
||||
given().header("Host", domain).header("Authorization", "Bearer abc").when().get("/")
|
||||
.then().statusCode(403);
|
||||
LambdaWebRequestSigner.Signed forged = new LambdaWebRequestSigner()
|
||||
.credentials("test", "not-the-secret", null).sign("GET", domain, "/");
|
||||
given().header("Host", domain).headers(forged.headers()).when().get("/")
|
||||
.then().statusCode(403);
|
||||
|
||||
// A disabled endpoint answers before the signature is checked.
|
||||
given().contentType("application/json").body("{\"throttleConfig\": {\"rateLimit\": 0}}")
|
||||
.when().patch(BASE + "/web-functions/" + functionName + "/endpoints/dev")
|
||||
.then().statusCode(202);
|
||||
given().header("Host", domain).when().get("/")
|
||||
.then().statusCode(503).header("lambda-web-error-type", "Platform.EndpointDisabled");
|
||||
|
||||
given().when().delete(BASE + "/web-functions/" + functionName).then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
void httpOneDotZeroIsRefused() throws IOException {
|
||||
String response = raw("GET / HTTP/1.0\r\nHost: " + UNKNOWN_HOST + "\r\n\r\n");
|
||||
@@ -124,6 +158,10 @@ class LambdaWebDataPlaneIntegrationTest {
|
||||
}
|
||||
|
||||
private String createFunction(String functionName) {
|
||||
return createFunction(functionName, "ApplicationManaged");
|
||||
}
|
||||
|
||||
private String createFunction(String functionName, String authType) {
|
||||
s3Service.createBucket(BUCKET, "us-east-1");
|
||||
s3Service.putObject(BUCKET, "app.zip", "zip".getBytes(StandardCharsets.UTF_8), "application/zip", Map.of());
|
||||
return given().contentType("application/json")
|
||||
@@ -134,8 +172,8 @@ class LambdaWebDataPlaneIntegrationTest {
|
||||
"runtimeConfig": {"runtime": "nodejs24.x"}},
|
||||
"serviceConfig": {"executionRoleArn": "%s"}},
|
||||
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
|
||||
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
|
||||
""".formatted(functionName, BUCKET, ROLE))
|
||||
"authType": "%s", "autoDeploymentMode": "LatestRevision"}}
|
||||
""".formatted(functionName, BUCKET, ROLE, authType))
|
||||
.when().put(BASE + "/web-functions")
|
||||
.then().statusCode(202)
|
||||
.extract().path("endpoint.domainName");
|
||||
|
||||
+14
@@ -27,6 +27,20 @@ class LambdaWebDataPlaneTest {
|
||||
assertTrue(id.matches("[A-Z2-7]{26}"), id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAppGetsThePathWithoutDotSegmentsAndWithItsRepeatedSlashes() {
|
||||
assertEquals("/a/c", LambdaWebDataPlane.withoutDotSegments("/a/./b/../c"));
|
||||
assertEquals("/a/", LambdaWebDataPlane.withoutDotSegments("/a/b/.."));
|
||||
assertEquals("/a/b/", LambdaWebDataPlane.withoutDotSegments("/a/b/."));
|
||||
assertEquals("/a", LambdaWebDataPlane.withoutDotSegments("/./a"));
|
||||
assertEquals("/a", LambdaWebDataPlane.withoutDotSegments("/../a"));
|
||||
assertEquals("/a/b/", LambdaWebDataPlane.withoutDotSegments("/a/b/"));
|
||||
assertEquals("/", LambdaWebDataPlane.withoutDotSegments("/"));
|
||||
assertEquals("/a//b", LambdaWebDataPlane.withoutDotSegments("/a//b"));
|
||||
assertEquals("//a", LambdaWebDataPlane.withoutDotSegments("//a"));
|
||||
assertEquals("/a/%2e%2e/b", LambdaWebDataPlane.withoutDotSegments("/a/%2e%2e/b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void thePortComesFromTheHostOrTheScheme() {
|
||||
assertEquals(4566, LambdaWebDataPlane.port("x.001.lambda-web.us-east-1.localhost:4566", "http"));
|
||||
|
||||
+1
@@ -15,6 +15,7 @@ class LambdaWebErrorPagesTest {
|
||||
|
||||
@Test
|
||||
void pagesHaveTheRecordedContentLengths() {
|
||||
assertEquals(230, length(LambdaWebErrorPages.FORBIDDEN));
|
||||
assertEquals(225, length(LambdaWebErrorPages.INVALID_ENDPOINT));
|
||||
assertEquals(264, length(LambdaWebErrorPages.UNSUPPORTED_HTTP_VERSION));
|
||||
assertEquals(274, length(LambdaWebErrorPages.ENDPOINT_DISABLED));
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
/** Under IAM enforcement an IamAuth endpoint evaluates lambda:InvokeWebFunctionEndpoint for the signer. */
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class LambdaWebIamAuthIntegrationTest {
|
||||
|
||||
private static final String BASE = "/2025-03-07";
|
||||
private static final String BUCKET = "web-code-iam-auth";
|
||||
private static final String ROOT = auth("000000000000", "lambda");
|
||||
private static final String IAM_ROOT = auth("000000000000", "iam");
|
||||
private static final String APP = """
|
||||
const http = require('node:http');
|
||||
const [host, port] = process.env.AWS_LAMBDA_HTTP_ENDPOINT.split(':');
|
||||
http.createServer((req, res) => res.end('ok')).listen(Number(port), host);
|
||||
""";
|
||||
|
||||
@TestHTTPResource("/")
|
||||
static URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Inject
|
||||
S3Service s3Service;
|
||||
|
||||
@Inject
|
||||
LambdaWebEnvironmentManager environments;
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
private String functionName;
|
||||
private String functionArn;
|
||||
private String domain;
|
||||
|
||||
@BeforeEach
|
||||
void createFunction() throws IOException {
|
||||
functionName = "iam-auth-" + Long.toString(System.nanoTime(), 36);
|
||||
s3Service.createBucket(BUCKET, "us-east-1");
|
||||
s3Service.putObject(BUCKET, functionName + ".zip", zip(), "application/zip", Map.of());
|
||||
int port = baseUri.getPort();
|
||||
String name = functionName;
|
||||
cleanup.register(() -> {
|
||||
environments.stopManagedContainers();
|
||||
given().port(port).header("Authorization", ROOT).delete(BASE + "/web-functions/" + name);
|
||||
});
|
||||
ValidatableResponse created = given().header("Authorization", ROOT).contentType("application/json")
|
||||
.body("""
|
||||
{"functionName": "%s",
|
||||
"revisionConfig": {
|
||||
"buildConfig": {"codeConfig": {"s3Object": {"bucket": "%s", "key": "%s.zip"}},
|
||||
"runtimeConfig": {"runtime": "nodejs24.x"}},
|
||||
"serviceConfig": {"executionRoleArn": "arn:aws:iam::000000000000:role/web"}},
|
||||
"endpointConfig": {"endpointName": "prod", "endpointType": "HomeRegion",
|
||||
"authType": "IamAuth", "autoDeploymentMode": "LatestRevision"}}
|
||||
""".formatted(functionName, BUCKET, functionName))
|
||||
.when().put(BASE + "/web-functions")
|
||||
.then().statusCode(202);
|
||||
functionArn = created.extract().path("functionArn");
|
||||
domain = created.extract().path("endpoint.domainName");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignerWithoutInvokeOnTheEndpointIsRefused() {
|
||||
invoke(user(userName(), null)).statusCode(403);
|
||||
invoke(user(userName(), functionArn)).statusCode(403);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void anIdentityPolicyOrTheFunctionPolicyAllowsTheSigner() {
|
||||
Assumptions.assumeTrue(isDockerAvailable(), "Docker must be available for the Lambda Web data plane");
|
||||
invoke(user(userName(), functionArn + "/endpoint/prod")).statusCode(200);
|
||||
|
||||
String userName = userName();
|
||||
UserCredentials granted = user(userName, null);
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::000000000000:user/%s"},
|
||||
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s/endpoint/prod"}]}"""
|
||||
.formatted(userName, functionArn);
|
||||
given().header("Authorization", ROOT).contentType("application/json").body(Map.of("Policy", policy))
|
||||
.when().put(BASE + "/resource-policy/" + functionArn)
|
||||
.then().statusCode(200);
|
||||
invoke(granted).statusCode(200);
|
||||
}
|
||||
|
||||
private static String userName() {
|
||||
return "iam-auth-" + Long.toString(System.nanoTime(), 36);
|
||||
}
|
||||
|
||||
private UserCredentials user(String userName, String invokeResource) {
|
||||
UserCredentials credentials = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), IAM_ROOT, userName);
|
||||
if (invokeResource != null) {
|
||||
given().header("Authorization", IAM_ROOT).contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "PutUserPolicy").formParam("Version", "2010-05-08")
|
||||
.formParam("UserName", userName).formParam("PolicyName", "invoke")
|
||||
.formParam("PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s"}]}"""
|
||||
.formatted(invokeResource))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
return credentials;
|
||||
}
|
||||
|
||||
private ValidatableResponse invoke(UserCredentials credentials) {
|
||||
LambdaWebRequestSigner.Signed signed = new LambdaWebRequestSigner()
|
||||
.credentials(credentials.accessKeyId(), credentials.secretAccessKey(), null)
|
||||
.sign("GET", domain, "/");
|
||||
return given().header("Host", domain).headers(signed.headers()).when().get("/").then();
|
||||
}
|
||||
|
||||
private static byte[] zip() throws IOException {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
zip.putNextEntry(new ZipEntry("index.js"));
|
||||
zip.write(APP.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.CallerArns;
|
||||
import io.github.hectorvent.floci.services.iam.IamService.OwnedSecretKey;
|
||||
import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
import io.github.hectorvent.floci.services.iam.model.CallerContext;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebIamAuth.Inbound;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebService.WebFunctionTarget;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunction;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.model.WebFunctionEndpoint;
|
||||
import io.netty.handler.codec.http.QueryStringDecoder;
|
||||
import io.vertx.core.MultiMap;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class LambdaWebIamAuthTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
private static final String HOST = "abcdefghijklmnop.001.lambda-web.us-east-1.localhost:4566";
|
||||
private static final String FUNCTION_ARN = "arn:aws:lambda:us-east-1:" + ACCOUNT + ":web-function/app";
|
||||
private static final String ENDPOINT_ARN = FUNCTION_ARN + "/endpoint/prod";
|
||||
private static final String USER_KEY = "AKIAUSERKEY000000001";
|
||||
private static final String USER_SECRET = "user-secret";
|
||||
private static final String SESSION_KEY = "ASIASESSIONKEY000001";
|
||||
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
private final IamService iamService = mock(IamService.class);
|
||||
@SuppressWarnings("unchecked")
|
||||
private final Instance<ScpProvider> scpProvider = mock(Instance.class);
|
||||
private final LambdaWebIamAuth iamAuth = new LambdaWebIamAuth(config, iamService,
|
||||
new IamPolicyEvaluator(new ObjectMapper()), scpProvider);
|
||||
private final WebFunction function = new WebFunction();
|
||||
private final WebFunctionEndpoint endpoint = new WebFunctionEndpoint();
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
function.functionName = "app";
|
||||
function.functionArn = FUNCTION_ARN;
|
||||
endpoint.endpointName = "prod";
|
||||
endpoint.endpointArn = ENDPOINT_ARN;
|
||||
endpoint.authType = "IamAuth";
|
||||
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null))
|
||||
.thenReturn(Optional.of(new OwnedSecretKey(USER_SECRET, ACCOUNT)));
|
||||
when(iamService.findSecretKeyInAnyAccount(SESSION_KEY, "token"))
|
||||
.thenReturn(Optional.of(new OwnedSecretKey("session-secret", null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRequestSignedForLambdaInTheEndpointRegionPasses() {
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/items?b=2&a=1")));
|
||||
assertTrue(allows(signer().sign("POST", HOST, "/")));
|
||||
assertTrue(allows(signer().presigned().sign("GET", HOST, "/q?x=1")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSignatureCoversThePathAsSignersNormalizeIt() {
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/a/c").withPathAndQuery("/a/./b/../c")));
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/a/b").withPathAndQuery("/a//b")));
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/a").withPathAndQuery("/a/b/..")));
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/path%2Fenc/a%20b?c=x%2By")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSignatureOverThePathAsSentIsRefusedWhenSignersWouldNormalizeIt() {
|
||||
assertFalse(allows(signer().rawPath().sign("GET", HOST, "/a/./b/../c")));
|
||||
assertFalse(allows(signer().rawPath().sign("GET", HOST, "/a//b")));
|
||||
assertTrue(allows(signer().rawPath().sign("GET", HOST, "/a/b/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void signersResolveDotSegmentsAndDropEmptySegments() {
|
||||
assertEquals("/a/c", LambdaWebIamAuth.signedPath("/a/./b/../c"));
|
||||
assertEquals("/a/b", LambdaWebIamAuth.signedPath("/a//b"));
|
||||
assertEquals("/a", LambdaWebIamAuth.signedPath("//a"));
|
||||
assertEquals("/a", LambdaWebIamAuth.signedPath("/a/b/.."));
|
||||
assertEquals("/a/b/", LambdaWebIamAuth.signedPath("/a/b/"));
|
||||
assertEquals("/", LambdaWebIamAuth.signedPath("/a/.."));
|
||||
assertEquals("/", LambdaWebIamAuth.signedPath("/"));
|
||||
assertEquals("/a/%2e%2e/b", LambdaWebIamAuth.signedPath("/a/%2e%2e/b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnsignedOrForeignAuthorizationIsRefused() {
|
||||
LambdaWebRequestSigner.Signed signed = signer().sign("GET", HOST, "/");
|
||||
assertFalse(allows(signed.withHeader("Authorization", null)));
|
||||
assertFalse(allows(signed.withHeader("Authorization", "Bearer abc")));
|
||||
assertFalse(allows(signer().presigned().sign("GET", HOST, "/").withHeader("Authorization", "Bearer abc")),
|
||||
"the header wins over the query");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theContentSha256HeaderIsRequired() {
|
||||
assertFalse(allows(signer().sign("GET", HOST, "/").withHeader("X-Amz-Content-SHA256", null)));
|
||||
assertFalse(allows(signer().contentSha256(null).presigned().sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theScopeMustNameLambdaAndTheEndpointRegion() {
|
||||
assertFalse(allows(signer().region("us-west-2").sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().service("lambda-web").sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().service("execute-api").sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSigningTimeMustBeWithinFiveMinutes() {
|
||||
Instant now = Instant.now();
|
||||
assertTrue(allows(signer().signedAt(now.minus(Duration.ofMinutes(4))).sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().signedAt(now.minus(Duration.ofMinutes(6))).sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().signedAt(now.plus(Duration.ofMinutes(6))).sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().presigned().signedAt(now.minus(Duration.ofMinutes(6))).sign("GET", HOST, "/")),
|
||||
"a presigned request expires");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAlteredRequestIsRefused() {
|
||||
LambdaWebRequestSigner.Signed signed = signer().sign("GET", HOST, "/x?b=1");
|
||||
assertFalse(allows(signed.withPathAndQuery("/x?a=1")));
|
||||
assertFalse(allows(signed.withPathAndQuery("/y?b=1")));
|
||||
assertFalse(allows(signer().credentials("test", "other", null).sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theKeyMustBeKnownAndCarryItsSessionTokenOnlyWhenTemporary() {
|
||||
assertTrue(allows(signer().credentials(USER_KEY, USER_SECRET, null).sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().credentials("AKIAUNKNOWN000000001", "x", null).sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().credentials(USER_KEY, USER_SECRET, "token").sign("GET", HOST, "/")),
|
||||
"a long-term key with a session token");
|
||||
assertTrue(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sign("GET", HOST, "/")));
|
||||
assertFalse(allows(signer().credentials(SESSION_KEY, "session-secret", "token").sign("GET", HOST, "/")
|
||||
.withHeader("X-Amz-Security-Token", null)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMalformedDateOrQueryIsRefused() {
|
||||
assertFalse(allows(signer().sign("GET", HOST, "/").withHeader("X-Amz-Date", "20261017T99")));
|
||||
assertFalse(allows(signer().sign("GET", HOST, "/q?x=1").withPathAndQuery("/q?x=%zz")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailureInsideFlociIsNotTakenForARefusal() {
|
||||
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null)).thenThrow(new IllegalStateException("storage"));
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> allows(signer().credentials(USER_KEY, USER_SECRET, null).sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementTheCallerNeedsInvokeOnTheEndpoint() {
|
||||
enforceFor(ACCOUNT);
|
||||
assertTrue(allowsUserWith(allow(ENDPOINT_ARN, "")));
|
||||
assertTrue(allowsUserWith(allow(FUNCTION_ARN + "/endpoint/*", "")));
|
||||
assertFalse(allowsUserWith(allow(FUNCTION_ARN, "")));
|
||||
assertFalse(allowsUserWith());
|
||||
assertFalse(allowsUserWith(allow("*", ""), """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"lambda:InvokeWebFunctionEndpoint",
|
||||
"Resource":"%s"}]}""".formatted(ENDPOINT_ARN)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementTheAuthTypeAndTagConditionKeysAreSet() {
|
||||
enforceFor(ACCOUNT);
|
||||
function.tags.put("env", "probe");
|
||||
assertTrue(allowsUserWith(allow(ENDPOINT_ARN,
|
||||
",\"Condition\":{\"StringEquals\":{\"lambda:Resource/WebFunctionAuthType\":\"IamAuth\"}}")));
|
||||
assertFalse(allowsUserWith(allow(ENDPOINT_ARN,
|
||||
",\"Condition\":{\"StringEquals\":{\"lambda:Resource/WebFunctionAuthType\":\"ApplicationManaged\"}}")));
|
||||
assertTrue(allowsUserWith(allow(ENDPOINT_ARN,
|
||||
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/env\":\"probe\"}}")));
|
||||
assertFalse(allowsUserWith(allow(ENDPOINT_ARN,
|
||||
",\"Condition\":{\"StringEquals\":{\"aws:ResourceTag/env\":\"prod\"}}")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementTheResourcePolicyAllowsWithinTheAccountAndItsDenyWins() {
|
||||
enforceFor(ACCOUNT);
|
||||
function.policy = resourcePolicy("Allow", ACCOUNT);
|
||||
assertTrue(allowsUserWith());
|
||||
function.policy = resourcePolicy("Deny", ACCOUNT);
|
||||
assertFalse(allowsUserWith(allow(ENDPOINT_ARN, "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementAnotherAccountNeedsBothPolicies() {
|
||||
enforceFor(OTHER_ACCOUNT);
|
||||
assertFalse(allowsUserWith(allow(ENDPOINT_ARN, "")));
|
||||
function.policy = resourcePolicy("Allow", OTHER_ACCOUNT);
|
||||
assertFalse(allowsUserWith());
|
||||
assertTrue(allowsUserWith(allow(ENDPOINT_ARN, "")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTestKeyIsNotEvaluated() {
|
||||
enforceFor(ACCOUNT);
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
private void enforceFor(String callerAccount) {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null))
|
||||
.thenReturn(Optional.of(new OwnedSecretKey(USER_SECRET, callerAccount)));
|
||||
when(iamService.resolveAccountId(USER_KEY)).thenReturn(Optional.of(callerAccount));
|
||||
String userArn = "arn:aws:iam::" + callerAccount + ":user/caller";
|
||||
when(iamService.resolveCallerArns(USER_KEY)).thenReturn(Optional.of(
|
||||
new CallerArns(userArn, userArn, CallerArns.TYPE_USER, "AIDACALLER", "caller", false)));
|
||||
}
|
||||
|
||||
private boolean allowsUserWith(String... identityPolicies) {
|
||||
when(iamService.resolveCallerContext(eq(USER_KEY), any(Instant.class)))
|
||||
.thenReturn(CallerContext.of(List.of(identityPolicies)));
|
||||
return allows(signer().credentials(USER_KEY, USER_SECRET, null).sign("GET", HOST, "/"));
|
||||
}
|
||||
|
||||
private static String resourcePolicy(String effect, String callerAccount) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"%s","Principal":{"AWS":"arn:aws:iam::%s:user/caller"},
|
||||
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s"}]}"""
|
||||
.formatted(effect, callerAccount, ENDPOINT_ARN);
|
||||
}
|
||||
|
||||
private static String allow(String resource, String condition) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"lambda:InvokeWebFunctionEndpoint",
|
||||
"Resource":"%s"%s}]}""".formatted(resource, condition);
|
||||
}
|
||||
|
||||
private static LambdaWebRequestSigner signer() {
|
||||
return new LambdaWebRequestSigner();
|
||||
}
|
||||
|
||||
private boolean allows(LambdaWebRequestSigner.Signed signed) {
|
||||
String pathAndQuery = signed.pathAndQuery();
|
||||
int question = pathAndQuery.indexOf('?');
|
||||
String path = question < 0 ? pathAndQuery : pathAndQuery.substring(0, question);
|
||||
String query = question < 0 ? null : pathAndQuery.substring(question + 1);
|
||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", HOST);
|
||||
signed.headers().forEach(headers::add);
|
||||
MultiMap params = MultiMap.caseInsensitiveMultiMap();
|
||||
try {
|
||||
new QueryStringDecoder(pathAndQuery).parameters().forEach(params::add);
|
||||
} catch (IllegalArgumentException expected) {
|
||||
// The data plane keeps going with no parameters when the query does not decode.
|
||||
}
|
||||
return iamAuth.allows(new Inbound(signed.method(), path, query, headers, params),
|
||||
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint));
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package io.github.hectorvent.floci.services.lambdaweb;
|
||||
|
||||
import software.amazon.awssdk.http.SdkHttpFullRequest;
|
||||
import software.amazon.awssdk.http.SdkHttpMethod;
|
||||
import software.amazon.awssdk.http.SdkHttpRequest;
|
||||
import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner.AuthLocation;
|
||||
import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner;
|
||||
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
|
||||
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
|
||||
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Signs a request to a Lambda Web endpoint with the AWS SDK signer, as a client would. */
|
||||
final class LambdaWebRequestSigner {
|
||||
|
||||
/** What goes on the wire: the method, the path with its query, and the headers to add. */
|
||||
record Signed(String method, String pathAndQuery, Map<String, String> headers) {
|
||||
|
||||
Signed withPathAndQuery(String other) {
|
||||
return new Signed(method, other, headers);
|
||||
}
|
||||
|
||||
Signed withHeader(String name, String value) {
|
||||
Map<String, String> copy = new LinkedHashMap<>(headers);
|
||||
if (value == null) {
|
||||
copy.remove(name);
|
||||
} else {
|
||||
copy.put(name, value);
|
||||
}
|
||||
return new Signed(method, pathAndQuery, copy);
|
||||
}
|
||||
}
|
||||
|
||||
private String accessKeyId = "test";
|
||||
private String secretKey = "test";
|
||||
private String sessionToken;
|
||||
private String region = "us-east-1";
|
||||
private String service = "lambda";
|
||||
private Instant signedAt = Instant.now();
|
||||
private boolean presigned;
|
||||
private boolean normalizePath = true;
|
||||
private String contentSha256 = "UNSIGNED-PAYLOAD";
|
||||
|
||||
LambdaWebRequestSigner credentials(String accessKeyId, String secretKey, String sessionToken) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
this.secretKey = secretKey;
|
||||
this.sessionToken = sessionToken;
|
||||
return this;
|
||||
}
|
||||
|
||||
LambdaWebRequestSigner region(String region) {
|
||||
this.region = region;
|
||||
return this;
|
||||
}
|
||||
|
||||
LambdaWebRequestSigner service(String service) {
|
||||
this.service = service;
|
||||
return this;
|
||||
}
|
||||
|
||||
LambdaWebRequestSigner signedAt(Instant signedAt) {
|
||||
this.signedAt = signedAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
LambdaWebRequestSigner presigned() {
|
||||
this.presigned = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** Signs the path as it is sent, without resolving its dot segments. */
|
||||
LambdaWebRequestSigner rawPath() {
|
||||
this.normalizePath = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/** The {@code X-Amz-Content-SHA256} value to send and sign, or null to send none. */
|
||||
LambdaWebRequestSigner contentSha256(String contentSha256) {
|
||||
this.contentSha256 = contentSha256;
|
||||
return this;
|
||||
}
|
||||
|
||||
Signed sign(String method, String host, String pathAndQuery) {
|
||||
URI uri = URI.create("http://" + host + pathAndQuery);
|
||||
SdkHttpFullRequest.Builder builder = SdkHttpFullRequest.builder()
|
||||
.method(SdkHttpMethod.fromValue(method))
|
||||
.uri(uri);
|
||||
if (contentSha256 != null) {
|
||||
builder.putHeader("X-Amz-Content-SHA256", contentSha256);
|
||||
}
|
||||
AwsCredentialsIdentity identity = sessionToken == null
|
||||
? AwsCredentialsIdentity.create(accessKeyId, secretKey)
|
||||
: AwsSessionCredentialsIdentity.create(accessKeyId, secretKey, sessionToken);
|
||||
SdkHttpRequest signed = AwsV4HttpSigner.create().sign(request -> request
|
||||
.identity(identity)
|
||||
.request(builder.build())
|
||||
.putProperty(AwsV4HttpSigner.SERVICE_SIGNING_NAME, service)
|
||||
.putProperty(AwsV4HttpSigner.REGION_NAME, region)
|
||||
.putProperty(AwsV4HttpSigner.PAYLOAD_SIGNING_ENABLED, false)
|
||||
.putProperty(AwsV4HttpSigner.NORMALIZE_PATH, normalizePath)
|
||||
.putProperty(AwsV4HttpSigner.AUTH_LOCATION, presigned ? AuthLocation.QUERY_STRING : AuthLocation.HEADER)
|
||||
.putProperty(AwsV4HttpSigner.EXPIRATION_DURATION, presigned ? Duration.ofMinutes(5) : null)
|
||||
.putProperty(HttpSigner.SIGNING_CLOCK, Clock.fixed(signedAt, ZoneOffset.UTC))).request();
|
||||
Map<String, String> headers = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, List<String>> header : signed.headers().entrySet()) {
|
||||
if (!"Host".equalsIgnoreCase(header.getKey())) {
|
||||
headers.put(header.getKey(), String.join(",", header.getValue()));
|
||||
}
|
||||
}
|
||||
if (contentSha256 != null) {
|
||||
headers.put("X-Amz-Content-SHA256", contentSha256);
|
||||
}
|
||||
String query = signed.encodedQueryParameters().map(encoded -> "?" + encoded).orElse("");
|
||||
return new Signed(method, signed.encodedPath() + query, headers);
|
||||
}
|
||||
}
|
||||
@@ -475,6 +475,21 @@ class LambdaWebServiceTest {
|
||||
+ " input and try again.", message(() -> service.putResourcePolicy(REGION, missing,
|
||||
policy("{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"*\"},"
|
||||
+ "\"Action\":\"lambda:InvokeWebFunctionEndpoint\",\"Resource\":\"" + resource + "\"}]}"))));
|
||||
// An ARN may carry a path, any other AWS principal may not.
|
||||
assertEquals("The provided input'arn:aws:iam::000000000000:role/has space'was invalid. Member must satisfy"
|
||||
+ " expression: [\\w+=/:,.@-]* Please check your input and try again.",
|
||||
message(() -> service.putResourcePolicy(REGION, missing,
|
||||
policy(members.formatted("{\"AWS\":\"arn:aws:iam::000000000000:role/has space\"}", invoke,
|
||||
"\"" + resource + "\"")))));
|
||||
assertEquals("The provided input'foo/bar'was invalid. Member must satisfy expression: [\\w+=,.@\\:-]*"
|
||||
+ " Please check your input and try again.", message(() -> service.putResourcePolicy(REGION, missing,
|
||||
policy(members.formatted("{\"AWS\":\"foo/bar\"}", invoke, "\"" + resource + "\"")))));
|
||||
assertEquals("ResourceNotFoundException", error(() -> service.putResourcePolicy(REGION, missing,
|
||||
policy(members.formatted("{\"AWS\":\"arn:aws:iam::000000000000:user/path/alice\"}", invoke,
|
||||
"\"" + resource + "\"")))).getErrorCode());
|
||||
assertEquals("ValidationException", error(() -> service.putResourcePolicy(REGION, missing,
|
||||
policy(members.formatted("{\"CanonicalUser\":\"arn:aws:iam::000000000000:foo/bar\"}", invoke,
|
||||
"\"" + resource + "\"")))).getErrorCode(), "only an AWS principal may carry a path");
|
||||
assertEquals("Lambda blocked the creation of this policy because it would grant public access to your function.",
|
||||
message(() -> service.putResourcePolicy(REGION, missing, policy("{\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"AWS\":[\"arn:aws:iam::000000000000:root\",\"*\"]},"
|
||||
|
||||
Reference in new issue
Block a user