mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(cloudfront): sign requests to a Lambda Web Function origin under OAC (#6037)
* feat(cloudfront): sign requests to a Lambda Web Function origin under OAC CreateOriginAccessControl now takes always-amz-auth for the lambda origin type and sigv4a for s3 and lambda, with the AWS validation messages. Distributions check the origin access control of a Lambda origin as AWS does, and refuse a Lambda@Edge origin trigger in front of an origin signed with always-amz-auth or sigv4a. Under always-amz-auth, CloudFront signs its requests to a Web Function endpoint of this Floci for the distribution. An IamAuth endpoint lets them through, or under IAM enforcement evaluates the function policy for cloudfront.amazonaws.com with aws:SourceArn and aws:SourceAccount. * fix(cloudfront): refuse unknown and in-use OAC changes as AWS does A distribution naming an origin access control that does not exist is InvalidOriginAccessControl. A control an origin uses can no longer change its origin type, its signing protocol, or whether it is always-amz-auth, which AWS answers with IllegalUpdate. * fix(cloudfront): match a Lambda origin by the end of its hostname CloudFront takes a Lambda origin only from a hostname under on.aws, and it matches the fixed labels case sensitively. Floci also takes one under its own host. The CloudFront check and the caller check now share the endpoint condition keys. The docs say when CloudFront forwards the viewer Authorization. * fix(cloudfront): read the Floci host for Lambda origins from the authority URI.getHost is null for a host with an underscore, such as a Compose service name, which broke CloudFront at startup. The Web Function endpoints are named from the authority, so the match reads it the same way.
This commit is contained in:
1 parent
1a598b7f0c
commit
8bff1ba0f3
9 files changed
+673
-68
No files matched your search
+9
-1
@@ -240,7 +240,15 @@ class CloudFrontManagementProtocolTest {
|
||||
.statusCode(400)
|
||||
.body(hasXPath(
|
||||
"//*[local-name()='Code']/text()",
|
||||
equalTo("InvalidArgument")));
|
||||
equalTo("MalformedXML")))
|
||||
.body(hasXPath(
|
||||
"//*[local-name()='Message']/text()",
|
||||
equalTo("3 validation errors detected: Value null at"
|
||||
+ " 'originAccessControlConfig.originAccessControlOriginType' failed to satisfy"
|
||||
+ " constraint: Member must not be null; Value null at"
|
||||
+ " 'originAccessControlConfig.signingProtocol' failed to satisfy constraint: Member"
|
||||
+ " must not be null; Value null at 'originAccessControlConfig.signingBehavior' failed"
|
||||
+ " to satisfy constraint: Member must not be null")));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+276
-13
@@ -129,6 +129,10 @@ class CloudFrontServiceTest {
|
||||
|
||||
/** A null {@code domainSuffix} is {@code floci.services.cloudfront.domain-suffix} left unset. */
|
||||
private CloudFrontService serviceWithDomainSuffix(String domainSuffix, String region) {
|
||||
return serviceWithDomainSuffix(domainSuffix, region, "http://localhost:4566");
|
||||
}
|
||||
|
||||
private CloudFrontService serviceWithDomainSuffix(String domainSuffix, String region, String baseUrl) {
|
||||
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
|
||||
when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
|
||||
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
|
||||
@@ -140,6 +144,7 @@ class CloudFrontServiceTest {
|
||||
|
||||
when(config.defaultAccountId()).thenReturn(ACCOUNT);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
when(config.effectiveBaseUrl()).thenReturn(baseUrl);
|
||||
when(config.dns()).thenReturn(dnsConfig);
|
||||
when(dnsConfig.extraSuffixes()).thenReturn(Optional.empty());
|
||||
when(config.services()).thenReturn(servicesConfig);
|
||||
@@ -531,23 +536,247 @@ class CloudFrontServiceTest {
|
||||
|
||||
OriginAccessControl missingName = originAccessControl();
|
||||
missingName.setName(null);
|
||||
assertInvalidOriginAccessControl(service, missingName);
|
||||
assertInvalidOriginAccessControl(service, missingName, "MalformedXML", "1 validation error detected: Value null"
|
||||
+ " at 'originAccessControlConfig.name' failed to satisfy constraint: Member must not be null");
|
||||
|
||||
OriginAccessControl emptyName = originAccessControl();
|
||||
emptyName.setName("");
|
||||
assertInvalidOriginAccessControl(service, emptyName, "InvalidArgument", "The parameter Name is too small or empty.");
|
||||
|
||||
OriginAccessControl longName = originAccessControl();
|
||||
longName.setName("x".repeat(65));
|
||||
assertInvalidOriginAccessControl(service, longName);
|
||||
assertInvalidOriginAccessControl(service, longName, "InvalidArgument", "The parameter Name is too big.");
|
||||
|
||||
OriginAccessControl invalidProtocol = originAccessControl();
|
||||
invalidProtocol.setSigningProtocol("sigv2");
|
||||
assertInvalidOriginAccessControl(service, invalidProtocol);
|
||||
assertInvalidOriginAccessControl(service, invalidProtocol, "MalformedXML", "1 validation error detected: Value"
|
||||
+ " 'sigv2' at 'originAccessControlConfig.signingProtocol' failed to satisfy constraint: Member must"
|
||||
+ " satisfy enum value set: [sigv4, sigv4a]");
|
||||
|
||||
OriginAccessControl invalidBehavior = originAccessControl();
|
||||
invalidBehavior.setSigningBehavior("sometimes");
|
||||
assertInvalidOriginAccessControl(service, invalidBehavior);
|
||||
assertInvalidOriginAccessControl(service, invalidBehavior, "MalformedXML", "1 validation error detected: Value"
|
||||
+ " 'sometimes' at 'originAccessControlConfig.signingBehavior' failed to satisfy constraint: Member"
|
||||
+ " must satisfy enum value set: [always-amz-auth, never, always, no-override]");
|
||||
|
||||
OriginAccessControl invalidOriginType = originAccessControl();
|
||||
invalidOriginType.setOriginAccessControlOriginType("custom");
|
||||
assertInvalidOriginAccessControl(service, invalidOriginType);
|
||||
assertInvalidOriginAccessControl(service, invalidOriginType, "MalformedXML", "1 validation error detected:"
|
||||
+ " Value 'custom' at 'originAccessControlConfig.originAccessControlOriginType' failed to satisfy"
|
||||
+ " constraint: Member must satisfy enum value set: [s3, execute-api, lambda, mediastore,"
|
||||
+ " mediapackagev2]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void originAccessControlEnumsAndNameAreReportedTogetherBeforeTheOtherRules() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
assertInvalidOriginAccessControl(service, new OriginAccessControl(), "MalformedXML", "4 validation errors"
|
||||
+ " detected: Value null at 'originAccessControlConfig.originAccessControlOriginType' failed to satisfy"
|
||||
+ " constraint: Member must not be null; Value null at 'originAccessControlConfig.signingProtocol'"
|
||||
+ " failed to satisfy constraint: Member must not be null; Value null at"
|
||||
+ " 'originAccessControlConfig.signingBehavior' failed to satisfy constraint: Member must not be null;"
|
||||
+ " Value null at 'originAccessControlConfig.name' failed to satisfy constraint: Member must not be null");
|
||||
|
||||
OriginAccessControl longNameAndBehavior = originAccessControl();
|
||||
longNameAndBehavior.setName("x".repeat(65));
|
||||
longNameAndBehavior.setSigningBehavior("always-amz-auth");
|
||||
assertInvalidOriginAccessControl(service, longNameAndBehavior, "InvalidArgument", "The parameter Name is too big.");
|
||||
}
|
||||
|
||||
@Test
|
||||
void alwaysAmzAuthIsForLambdaAndSigV4aForS3OrLambda() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
|
||||
assertInvalidOriginAccessControl(service, originAccessControl("sigv4", "always-amz-auth", "s3"),
|
||||
"InvalidArgument", "The parameter SigningBehavior always-amz-auth is only supported with lambda origin type.");
|
||||
assertInvalidOriginAccessControl(service, originAccessControl("sigv4a", "always-amz-auth", "mediastore"),
|
||||
"InvalidArgument", "The parameter SigningBehavior always-amz-auth is only supported with lambda origin type.");
|
||||
assertInvalidOriginAccessControl(service, originAccessControl("sigv4a", "always", "mediapackagev2"),
|
||||
"InvalidArgument", "The parameter OriginType sigv4a is only supported with s3 or lambda origin types.");
|
||||
|
||||
assertDoesNotThrow(() -> service.createOriginAccessControl(originAccessControl("sigv4a", "always-amz-auth", "lambda")));
|
||||
assertDoesNotThrow(() -> service.createOriginAccessControl(originAccessControl("sigv4a", "never", "lambda")));
|
||||
assertDoesNotThrow(() -> service.createOriginAccessControl(originAccessControl("sigv4a", "always", "s3")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExecuteApiOriginTypeIsRefused() {
|
||||
AwsException error = assertAws("AccessDenied", () -> serviceWithDomainSuffix("cloudfront.net")
|
||||
.createOriginAccessControl(originAccessControl("sigv4", "always", "execute-api")));
|
||||
|
||||
assertEquals("Access Denied.", error.getMessage());
|
||||
assertEquals(403, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLambdaOriginNeedsTheOriginAccessControlItsHostnameCallsFor() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
String regional = "abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-east-1.on.aws";
|
||||
String global = "abcdefghijklmnopqrstuvwxyz.lambda-web.global.on.aws";
|
||||
String functionUrl = "abcdefghijklmnopqrstuvwxyz0123.lambda-url.us-east-1.on.aws";
|
||||
String differ = "The origin type and OAC origin type differ";
|
||||
|
||||
assertOriginAccessControlRefused(service, regional, "sigv4", "never", "lambda",
|
||||
"Lambda-Web origins require always-amz-auth signing behavior.");
|
||||
assertOriginAccessControlRefused(service, "abcdefghijklmnop.001.lambda-web.us-east-1.localhost:4566", "sigv4",
|
||||
"always", "lambda", "Lambda-Web origins require always-amz-auth signing behavior.");
|
||||
assertOriginAccessControlRefused(service, regional, "sigv4", "always", "s3", differ);
|
||||
assertOriginAccessControlRefused(service, global, "sigv4", "always", "s3", differ);
|
||||
assertOriginAccessControlRefused(service, "example.com", "sigv4", "always-amz-auth", "lambda", differ);
|
||||
assertOriginAccessControlRefused(service, "bucket.s3.us-east-1.amazonaws.com", "sigv4", "always", "lambda", differ);
|
||||
assertOriginAccessControlRefused(service, global, "sigv4", "always-amz-auth", "lambda",
|
||||
"This origin domain requires SigV4a signing protocol.");
|
||||
assertOriginAccessControlRefused(service, global, "sigv4", "never", "lambda",
|
||||
"This origin domain requires SigV4a signing protocol.");
|
||||
assertOriginAccessControlRefused(service, regional, "sigv4a", "always", "lambda",
|
||||
"SigV4a signing protocol is not compatible with this origin domain.");
|
||||
assertOriginAccessControlRefused(service, "abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-west-2.on.aws", "sigv4a",
|
||||
"always-amz-auth", "lambda", "SigV4a signing protocol is not compatible with this origin domain.");
|
||||
assertOriginAccessControlRefused(service, functionUrl, "sigv4a", "always-amz-auth", "lambda",
|
||||
"SigV4a signing protocol is not compatible with this origin domain.");
|
||||
assertOriginAccessControlRefused(service, functionUrl, "sigv4", "always-amz-auth", "lambda",
|
||||
"always-amz-auth signing behavior requires a Lambda-Web origin.");
|
||||
|
||||
assertDoesNotThrow(() -> service.createDistribution(
|
||||
distributionWithOrigin(regional, oac(service, "sigv4", "always-amz-auth", "lambda"), null), Map.of()));
|
||||
assertDoesNotThrow(() -> service.createDistribution(
|
||||
distributionWithOrigin(global, oac(service, "sigv4a", "always-amz-auth", "lambda"), null), Map.of()));
|
||||
assertDoesNotThrow(() -> service.createDistribution(
|
||||
distributionWithOrigin(functionUrl, oac(service, "sigv4", "never", "lambda"), null), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyAHostnameUnderOnAwsOrThisFlociIsALambdaOrigin() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
String differ = "The origin type and OAC origin type differ";
|
||||
|
||||
for (String notLambda : List.of("api.lambda-web.us-east-1.example.com",
|
||||
"abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-east-1.on.aws.example.com",
|
||||
"abcdefghijklmnopqrstuvwxyz0123.lambda-url.us-east-1.example.com",
|
||||
"abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-east-1.amazonaws.com",
|
||||
"abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-east-1.floci.example.com",
|
||||
"abcdefghijklmnopqrstuvwxyz.001.LAMBDA-WEB.US-EAST-1.ON.AWS",
|
||||
"abc.lambda-web.Global.on.aws",
|
||||
"lambda-web.us-east-1.on.aws",
|
||||
"abc.lambda-web.foo.on.aws")) {
|
||||
assertOriginAccessControlRefused(service, notLambda, "sigv4a", "always-amz-auth", "lambda", differ);
|
||||
}
|
||||
for (String webFunction : List.of("ABC.lambda-web.us-east-1.on.aws", "a.b.c.lambda-web.us-east-1.on.aws",
|
||||
"abc.lambda-web.xx-fake-9.on.aws", "abcdefghijklmnop.001.lambda-web.us-east-1.localhost")) {
|
||||
assertOriginAccessControlRefused(service, webFunction, "sigv4a", "always-amz-auth", "lambda",
|
||||
"SigV4a signing protocol is not compatible with this origin domain.");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFlociHostWithAnUnderscoreNamesLambdaOriginsToo() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net", "us-east-1", "http://floci_host:4566");
|
||||
|
||||
for (String webFunction : List.of("abcdefghijklmnop.001.lambda-web.us-east-1.floci_host:4566",
|
||||
"abcdefghijklmnop.001.lambda-web.us-east-1.floci_host")) {
|
||||
assertOriginAccessControlRefused(service, webFunction, "sigv4a", "always-amz-auth", "lambda",
|
||||
"SigV4a signing protocol is not compatible with this origin domain.");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUpdateChecksTheOriginAccessControlOfALambdaOrigin() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
String never = oac(service, "sigv4", "never", "lambda");
|
||||
Distribution created = service.createDistribution(
|
||||
distributionWithOrigin("abcdefghijklmnopqrstuvwxyz0123.lambda-url.us-east-1.on.aws", never, null), Map.of());
|
||||
|
||||
AwsException error = assertAws("IllegalOriginAccessConfiguration", () -> service.updateDistribution(
|
||||
created.getId(), created.getEtag(), distributionWithOrigin(
|
||||
"abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-east-1.on.aws", never, null)));
|
||||
|
||||
assertEquals("Illegal configuration: Lambda-Web origins require always-amz-auth signing behavior.",
|
||||
error.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDistributionNamingAnUnknownOriginAccessControlIsRefused() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
AwsException created = assertAws("InvalidOriginAccessControl", () -> service.createDistribution(
|
||||
distributionWithOrigin("example.com", "E0000000000000", null), Map.of()));
|
||||
assertEquals("The specified origin access control does not exist or is not valid.", created.getMessage());
|
||||
assertEquals(400, created.getHttpStatus());
|
||||
|
||||
Distribution existing = service.createDistribution(distributionWithOrigin("example.com", null, null), Map.of());
|
||||
assertAws("InvalidOriginAccessControl", () -> service.updateDistribution(existing.getId(),
|
||||
existing.getEtag(), distributionWithOrigin("example.com", "E0000000000000", null)));
|
||||
assertNull(service.getDistribution(existing.getId()).getConfig().getOrigins().getFirst()
|
||||
.getOriginAccessControlId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOriginAccessControlInUseKeepsHowItSigns() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
String s3 = oac(service, "sigv4", "always", "s3");
|
||||
service.createDistribution(distributionWithOrigin("bucket.s3.us-east-1.amazonaws.com", s3, null), Map.of());
|
||||
String functionUrl = oac(service, "sigv4", "always", "lambda");
|
||||
service.createDistribution(distributionWithOrigin(
|
||||
"abcdefghijklmnopqrstuvwxyz0123.lambda-url.us-east-1.on.aws", functionUrl, null), Map.of());
|
||||
|
||||
assertDoesNotThrow(() -> updateOriginAccessControl(service, s3, "sigv4", "never", "s3"));
|
||||
assertDoesNotThrow(() -> updateOriginAccessControl(service, s3, "sigv4", "no-override", "s3"));
|
||||
assertDoesNotThrow(() -> updateOriginAccessControl(service, functionUrl, "sigv4", "never", "lambda"));
|
||||
assertIllegalUpdate(service, s3, "sigv4a", "no-override", "s3");
|
||||
assertIllegalUpdate(service, s3, "sigv4", "no-override", "mediastore");
|
||||
assertIllegalUpdate(service, functionUrl, "sigv4", "always-amz-auth", "lambda");
|
||||
assertIllegalUpdate(service, functionUrl, "sigv4a", "never", "lambda");
|
||||
|
||||
String unused = oac(service, "sigv4", "always", "s3");
|
||||
assertDoesNotThrow(() -> updateOriginAccessControl(service, unused, "sigv4a", "always", "lambda"));
|
||||
}
|
||||
|
||||
private static void updateOriginAccessControl(CloudFrontService service, String id, String protocol,
|
||||
String behavior, String originType) {
|
||||
service.updateOriginAccessControl(id, service.getOriginAccessControl(id).getEtag(),
|
||||
originAccessControl(protocol, behavior, originType));
|
||||
}
|
||||
|
||||
private static void assertIllegalUpdate(CloudFrontService service, String id, String protocol, String behavior,
|
||||
String originType) {
|
||||
AwsException error = assertAws("IllegalUpdate",
|
||||
() -> updateOriginAccessControl(service, id, protocol, behavior, originType));
|
||||
assertEquals("Cannot update origin type when associated to origins.", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lambdaEdgeOriginTriggersAreRefusedInFrontOfAnAlwaysAmzAuthOrSigV4aOrigin() {
|
||||
CloudFrontService service = serviceWithDomainSuffix("cloudfront.net");
|
||||
String regional = "abcdefghijklmnopqrstuvwxyz.001.lambda-web.us-east-1.on.aws";
|
||||
String amzAuth = oac(service, "sigv4", "always-amz-auth", "lambda");
|
||||
String message = "Lambda@Edge origin triggers are incompatible with SigV4a and always-amz-auth origins."
|
||||
+ " Use a different origin or disassociate the function.";
|
||||
|
||||
for (String eventType : List.of("origin-request", "origin-response")) {
|
||||
AwsException error = assertAws("InvalidLambdaFunctionAssociation", () -> service.createDistribution(
|
||||
distributionWithOrigin(regional, amzAuth, eventType), Map.of()));
|
||||
assertEquals(message, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
Distribution onABehavior = distributionWithOrigin(regional, amzAuth, null);
|
||||
CacheBehavior behavior = new CacheBehavior();
|
||||
behavior.setPathPattern("/api/*");
|
||||
behavior.setTargetOriginId("o");
|
||||
behavior.setLambdaFunctionAssociations(List.of(Map.<String, Object>of("LambdaFunctionARN",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:edge:1", "EventType", "origin-request")));
|
||||
onABehavior.getConfig().setCacheBehaviors(List.of(behavior));
|
||||
assertEquals(message, assertAws("InvalidLambdaFunctionAssociation",
|
||||
() -> service.createDistribution(onABehavior, Map.of())).getMessage());
|
||||
Distribution sigv4aS3 = distributionWithOrigin(
|
||||
"bucket.s3.us-east-1.amazonaws.com", oac(service, "sigv4a", "always", "s3"), "origin-request");
|
||||
assertEquals(message, assertAws("InvalidLambdaFunctionAssociation",
|
||||
() -> service.createDistribution(sigv4aS3, Map.of())).getMessage());
|
||||
|
||||
assertDoesNotThrow(() -> service.createDistribution(
|
||||
distributionWithOrigin(regional, amzAuth, "viewer-request"), Map.of()));
|
||||
assertDoesNotThrow(() -> service.createDistribution(distributionWithOrigin(
|
||||
"bucket.s3.us-east-1.amazonaws.com", oac(service, "sigv4", "always", "s3"), "origin-request"), Map.of()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -562,7 +791,7 @@ class CloudFrontServiceTest {
|
||||
() -> service.updateOriginAccessControl(
|
||||
existing.getId(), existing.getEtag(), invalid));
|
||||
|
||||
assertEquals("InvalidArgument", error.getErrorCode());
|
||||
assertEquals("MalformedXML", error.getErrorCode());
|
||||
assertEquals("test-oac", service.getOriginAccessControl(existing.getId()).getName());
|
||||
}
|
||||
|
||||
@@ -1232,14 +1461,49 @@ class CloudFrontServiceTest {
|
||||
}
|
||||
|
||||
private static OriginAccessControl originAccessControl() {
|
||||
return originAccessControl("sigv4", "always", "s3");
|
||||
}
|
||||
|
||||
private static OriginAccessControl originAccessControl(String protocol, String behavior, String originType) {
|
||||
OriginAccessControl oac = new OriginAccessControl();
|
||||
oac.setName("test-oac");
|
||||
oac.setSigningProtocol("sigv4");
|
||||
oac.setSigningBehavior("always");
|
||||
oac.setOriginAccessControlOriginType("s3");
|
||||
oac.setSigningProtocol(protocol);
|
||||
oac.setSigningBehavior(behavior);
|
||||
oac.setOriginAccessControlOriginType(originType);
|
||||
return oac;
|
||||
}
|
||||
|
||||
private static String oac(CloudFrontService service, String protocol, String behavior, String originType) {
|
||||
return service.createOriginAccessControl(originAccessControl(protocol, behavior, originType)).getId();
|
||||
}
|
||||
|
||||
/** A distribution whose only origin {@code o} is {@code domainName}, with an optional Lambda@Edge trigger. */
|
||||
private static Distribution distributionWithOrigin(String domainName, String oacId, String edgeEventType) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId("o");
|
||||
origin.setDomainName(domainName);
|
||||
origin.setOriginAccessControlId(oacId);
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setTargetOriginId("o");
|
||||
if (edgeEventType != null) {
|
||||
behavior.setLambdaFunctionAssociations(List.of(Map.<String, Object>of("LambdaFunctionARN",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:edge:1", "EventType", edgeEventType)));
|
||||
}
|
||||
Distribution distribution = distribution(false, List.of());
|
||||
distribution.getConfig().setOrigins(List.of(origin));
|
||||
distribution.getConfig().setDefaultCacheBehavior(behavior);
|
||||
return distribution;
|
||||
}
|
||||
|
||||
private static void assertOriginAccessControlRefused(CloudFrontService service, String domainName, String protocol,
|
||||
String behavior, String originType, String reason) {
|
||||
Distribution distribution = distributionWithOrigin(domainName, oac(service, protocol, behavior, originType), null);
|
||||
AwsException error = assertAws("IllegalOriginAccessConfiguration",
|
||||
() -> service.createDistribution(distribution, Map.of()));
|
||||
assertEquals("Illegal configuration: " + reason, error.getMessage(), domainName);
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
private static PublicKey validPublicKey(String name) throws Exception {
|
||||
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
|
||||
generator.initialize(2048);
|
||||
@@ -1287,10 +1551,9 @@ class CloudFrontServiceTest {
|
||||
}
|
||||
|
||||
private static void assertInvalidOriginAccessControl(
|
||||
CloudFrontService service, OriginAccessControl oac) {
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.createOriginAccessControl(oac));
|
||||
assertEquals("InvalidArgument", error.getErrorCode());
|
||||
CloudFrontService service, OriginAccessControl oac, String errorCode, String message) {
|
||||
AwsException error = assertAws(errorCode, () -> service.createOriginAccessControl(oac));
|
||||
assertEquals(message, error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
|
||||
|
||||
+62
-22
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.cloudfront.model.DefaultCacheBehavior
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Distribution;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.DistributionConfig;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.Origin;
|
||||
import io.github.hectorvent.floci.services.cloudfront.model.OriginAccessControl;
|
||||
import io.github.hectorvent.floci.services.lambdaweb.LambdaWebEnvironmentManager.Environment;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
@@ -47,6 +48,7 @@ import java.util.zip.ZipOutputStream;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.endsWith;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
import static org.hamcrest.Matchers.matchesPattern;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
@@ -222,26 +224,7 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
@Timeout(180)
|
||||
void aCloudFrontDistributionReachesTheEndpointAsItsOrigin() throws Exception {
|
||||
String domain = createFunction(30);
|
||||
Origin origin = new Origin();
|
||||
origin.setId("web");
|
||||
origin.setDomainName(domain.substring(0, domain.lastIndexOf(':')));
|
||||
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
|
||||
customOriginConfig.put("HTTPPort", "80");
|
||||
customOriginConfig.put("HTTPSPort", "443");
|
||||
customOriginConfig.put("OriginProtocolPolicy", "https-only");
|
||||
origin.setCustomOriginConfig(customOriginConfig);
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setTargetOriginId("web");
|
||||
behavior.setViewerProtocolPolicy("allow-all");
|
||||
behavior.setCachePolicyId("4135ea2d-6df8-44a3-9df3-4b5a84be39ad");
|
||||
behavior.setOriginRequestPolicyId("b689b0a8-53d0-40ab-baf2-68738e2966ac");
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(origin));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = new Distribution();
|
||||
distribution.setConfig(config);
|
||||
Distribution created = cloudFrontService.createDistribution(distribution, Map.of());
|
||||
Distribution created = distributionInFrontOf(domain, null);
|
||||
try {
|
||||
given().header("Host", created.getDomainName()).header("x-custom", "1").when().get("/a/b?x=1")
|
||||
.then().statusCode(200)
|
||||
@@ -258,6 +241,58 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void anAlwaysAmzAuthOriginAccessControlSignsForTheViewerInFrontOfAnIamAuthEndpoint() throws Exception {
|
||||
String domain = createFunction(30, 64, "INFO", "serve", "IamAuth");
|
||||
OriginAccessControl oac = new OriginAccessControl();
|
||||
oac.setName(functionName);
|
||||
oac.setSigningProtocol("sigv4");
|
||||
oac.setSigningBehavior("always-amz-auth");
|
||||
oac.setOriginAccessControlOriginType("lambda");
|
||||
OriginAccessControl createdOac = cloudFrontService.createOriginAccessControl(oac);
|
||||
Distribution created = distributionInFrontOf(domain, createdOac.getId());
|
||||
try {
|
||||
given().header("Host", domain).when().get("/").then().statusCode(403);
|
||||
given().header("Host", created.getDomainName()).header("Authorization", "Bearer app-token")
|
||||
.body("{}").when().post("/a")
|
||||
.then().statusCode(200)
|
||||
.body("method", equalTo("POST"))
|
||||
.body("headers.authorization", equalTo("Bearer app-token"))
|
||||
.body("headers", not(hasKey("lambda-web-cloudfront-key")))
|
||||
.body("headers", not(hasKey("lambda-web-cloudfront-source-arn")));
|
||||
} finally {
|
||||
cloudFrontService.removeDistribution(created.getId());
|
||||
cloudFrontService.deleteOriginAccessControl(createdOac.getId(), createdOac.getEtag());
|
||||
}
|
||||
}
|
||||
|
||||
/** The endpoint behind a distribution, named as on AWS: its host without a port, over HTTPS on 443. */
|
||||
private Distribution distributionInFrontOf(String domain, String originAccessControlId) {
|
||||
Origin origin = new Origin();
|
||||
origin.setId("web");
|
||||
origin.setDomainName(domain.substring(0, domain.lastIndexOf(':')));
|
||||
origin.setOriginAccessControlId(originAccessControlId);
|
||||
Map<String, Object> customOriginConfig = new LinkedHashMap<>();
|
||||
customOriginConfig.put("HTTPPort", "80");
|
||||
customOriginConfig.put("HTTPSPort", "443");
|
||||
customOriginConfig.put("OriginProtocolPolicy", "https-only");
|
||||
origin.setCustomOriginConfig(customOriginConfig);
|
||||
DefaultCacheBehavior behavior = new DefaultCacheBehavior();
|
||||
behavior.setTargetOriginId("web");
|
||||
behavior.setViewerProtocolPolicy("allow-all");
|
||||
behavior.setAllowedMethods(List.of("GET", "HEAD", "OPTIONS", "PUT", "PATCH", "POST", "DELETE"));
|
||||
behavior.setCachePolicyId("4135ea2d-6df8-44a3-9df3-4b5a84be39ad");
|
||||
behavior.setOriginRequestPolicyId("b689b0a8-53d0-40ab-baf2-68738e2966ac");
|
||||
DistributionConfig config = new DistributionConfig();
|
||||
config.setEnabled(true);
|
||||
config.setOrigins(List.of(origin));
|
||||
config.setDefaultCacheBehavior(behavior);
|
||||
Distribution distribution = new Distribution();
|
||||
distribution.setConfig(config);
|
||||
return cloudFrontService.createDistribution(distribution, Map.of());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(180)
|
||||
void theOutputGoesToTheLocalAndTheCentralizedLogGroupAsJsonEvents() throws Exception {
|
||||
@@ -474,6 +509,11 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
|
||||
private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment, String systemLogLevel,
|
||||
String mode) throws IOException {
|
||||
return createFunction(timeoutSeconds, maxConcurrencyPerEnvironment, systemLogLevel, mode, "ApplicationManaged");
|
||||
}
|
||||
|
||||
private String createFunction(int timeoutSeconds, int maxConcurrencyPerEnvironment, String systemLogLevel,
|
||||
String mode, String authType) throws IOException {
|
||||
functionName = "dp-docker-" + Long.toString(System.nanoTime(), 36);
|
||||
s3Service.createBucket(BUCKET, "us-east-1");
|
||||
s3Service.putObject(BUCKET, functionName + ".zip", zip(APP), "application/zip", Map.of());
|
||||
@@ -488,9 +528,9 @@ class LambdaWebDataPlaneDockerIntegrationTest {
|
||||
"environmentVariables": {"CUSTOM": "yes", "MODE": "%s"},
|
||||
"telemetryConfig": {"loggingConfig": {"systemLogLevel": "%s"}}}},
|
||||
"endpointConfig": {"endpointName": "dev", "endpointType": "HomeRegion",
|
||||
"authType": "ApplicationManaged", "autoDeploymentMode": "LatestRevision"}}
|
||||
"authType": "%s", "autoDeploymentMode": "LatestRevision"}}
|
||||
""".formatted(functionName, BUCKET, functionName, ROLE, timeoutSeconds,
|
||||
maxConcurrencyPerEnvironment, mode, systemLogLevel))
|
||||
maxConcurrencyPerEnvironment, mode, systemLogLevel, authType))
|
||||
.when().put(BASE + "/web-functions")
|
||||
.then().statusCode(202)
|
||||
.extract().path("endpoint.domainName");
|
||||
|
||||
@@ -20,7 +20,9 @@ import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -43,6 +45,7 @@ class LambdaWebIamAuthTest {
|
||||
private static final String USER_KEY = "AKIAUSERKEY000000001";
|
||||
private static final String USER_SECRET = "user-secret";
|
||||
private static final String SESSION_KEY = "ASIASESSIONKEY000001";
|
||||
private static final String DISTRIBUTION_ARN = "arn:aws:cloudfront::" + ACCOUNT + ":distribution/E2EXAMPLE";
|
||||
|
||||
private final EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
private final IamService iamService = mock(IamService.class);
|
||||
@@ -222,6 +225,59 @@ class LambdaWebIamAuthTest {
|
||||
assertTrue(allows(signer().sign("GET", HOST, "/")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cloudFrontSignsWithTheKeyOfThisProcess() {
|
||||
assertTrue(allowsCloudFront(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN)));
|
||||
|
||||
Map<String, String> forged = new HashMap<>(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN));
|
||||
forged.put("lambda-web-cloudfront-key", "0".repeat(64));
|
||||
assertFalse(allowsCloudFront(forged));
|
||||
LambdaWebIamAuth another = new LambdaWebIamAuth(config, iamService, new IamPolicyEvaluator(new ObjectMapper()),
|
||||
scpProvider);
|
||||
assertFalse(allowsCloudFront(another.cloudFrontSignature(DISTRIBUTION_ARN)));
|
||||
assertFalse(allowsCloudFront(iamAuth.cloudFrontSignature("E2EXAMPLE")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void underEnforcementTheFunctionPolicyMustAllowCloudFrontForTheDistribution() {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
assertFalse(allowsCloudFront(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN)), "no policy denies");
|
||||
|
||||
function.policy = cloudFrontPolicy(cloudFrontStatement("Allow", "aws:SourceArn", DISTRIBUTION_ARN));
|
||||
assertTrue(allowsCloudFront(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN)));
|
||||
assertFalse(allowsCloudFront(iamAuth.cloudFrontSignature(
|
||||
"arn:aws:cloudfront::" + ACCOUNT + ":distribution/E3OTHER")));
|
||||
|
||||
function.policy = cloudFrontPolicy(cloudFrontStatement("Allow", "aws:SourceAccount", ACCOUNT));
|
||||
assertTrue(allowsCloudFront(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN)));
|
||||
assertFalse(allowsCloudFront(iamAuth.cloudFrontSignature(
|
||||
"arn:aws:cloudfront::" + OTHER_ACCOUNT + ":distribution/E2EXAMPLE")));
|
||||
|
||||
String allowIamAuth = cloudFrontStatement("Allow", "lambda:Resource/WebFunctionAuthType", "IamAuth");
|
||||
function.policy = cloudFrontPolicy(allowIamAuth);
|
||||
assertTrue(allowsCloudFront(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN)));
|
||||
function.policy = cloudFrontPolicy(allowIamAuth, cloudFrontStatement("Deny", "aws:SourceArn", DISTRIBUTION_ARN));
|
||||
assertFalse(allowsCloudFront(iamAuth.cloudFrontSignature(DISTRIBUTION_ARN)));
|
||||
}
|
||||
|
||||
private boolean allowsCloudFront(Map<String, String> signature) {
|
||||
MultiMap headers = MultiMap.caseInsensitiveMultiMap().add("Host", HOST).addAll(signature);
|
||||
return iamAuth.allows(new Inbound("POST", "/", null, headers, MultiMap.caseInsensitiveMultiMap()),
|
||||
new WebFunctionTarget(ACCOUNT, "us-east-1", function, endpoint));
|
||||
}
|
||||
|
||||
private static String cloudFrontPolicy(String... statements) {
|
||||
return "{\"Version\":\"2012-10-17\",\"Statement\":[" + String.join(",", statements) + "]}";
|
||||
}
|
||||
|
||||
private static String cloudFrontStatement(String effect, String conditionKey, String conditionValue) {
|
||||
return """
|
||||
{"Effect":"%s","Principal":{"Service":"cloudfront.amazonaws.com"},
|
||||
"Action":"lambda:InvokeWebFunctionEndpoint","Resource":"%s",
|
||||
"Condition":{"StringEquals":{"%s":"%s"}}}"""
|
||||
.formatted(effect, ENDPOINT_ARN, conditionKey, conditionValue);
|
||||
}
|
||||
|
||||
private void enforceFor(String callerAccount) {
|
||||
when(config.services().iam().enforcementEnabled()).thenReturn(true);
|
||||
when(iamService.findSecretKeyInAnyAccount(USER_KEY, null))
|
||||
|
||||
Reference in new issue
Block a user