mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(lambda): re-sync S3 code for functions in every region (#9621)
The reactive S3 sync listed functions in the default Region only, so a function created in any other Region never picked up new code when its S3 object changed. The observer now scans every Region's functions and syncs each one in the Region its ARN names, under its own account. Buckets are per account unless the global bucket namespace is on, so two accounts can own same-named buckets, and matching by bucket name and key alone let an upload to one account's bucket redeploy another account's function. The observer now resolves the bucket written in the uploader's account and syncs a function only when its owner resolves its code bucket to the same owning account; with the global bucket namespace both resolve to the one bucket, so a shared code bucket still redeploys every function that uses it. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
d9ac9d2418
commit
622e589dc3
5 files changed
+186
-19
No files matched your search
@@ -199,13 +199,12 @@ public class LambdaFunctionStore implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #list(String)}, but across every account's partition. For async callers
|
||||
* that have no {@code RequestContext} and so would otherwise see only the default
|
||||
* account's functions.
|
||||
* Every function's {@code $LATEST}, across every Region and every account's partition. For
|
||||
* async callers that have no {@code RequestContext} and so would otherwise see only the
|
||||
* default account's functions in one Region.
|
||||
*/
|
||||
public List<LambdaFunction> listAllAccounts(String region) {
|
||||
String prefix = "lambda::" + region + "::";
|
||||
Predicate<String> filter = key -> key.startsWith(prefix) && key.endsWith("::$LATEST");
|
||||
public List<LambdaFunction> listAllAccounts() {
|
||||
Predicate<String> filter = key -> key.startsWith("lambda::") && key.endsWith("::$LATEST");
|
||||
if (backend instanceof AccountAwareStorageBackend<LambdaFunction> aware) {
|
||||
return aware.scanAllAccountEntries(filter).stream()
|
||||
.map(AccountAwareStorageBackend.AccountEntry::value)
|
||||
|
||||
@@ -4747,18 +4747,27 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
|
||||
return;
|
||||
}
|
||||
LOG.debugv("Observing S3 update: {0}/{1}", event.bucketName(), event.key());
|
||||
// For simplicity, we scan all functions in the default region
|
||||
// Most local dev setups use a single region.
|
||||
// This runs on the CDI event thread with no RequestContext, so an ambient scan
|
||||
// would only ever see the default account's partition — a function owned by any
|
||||
// other account would silently never hot-reload from S3.
|
||||
String region = regionResolver.getDefaultRegion();
|
||||
List<LambdaFunction> functions = functionStore.listAllAccounts(region);
|
||||
// This runs on the CDI event thread with no RequestContext, so an ambient scan would only
|
||||
// see the default account's functions in the default Region. Every function is scanned
|
||||
// instead, and each one syncs in its own Region and account.
|
||||
List<LambdaFunction> functions = functionStore.listAllAccounts();
|
||||
boolean async = reactiveS3SyncAsync();
|
||||
// The event fires on the uploader's request, so the bucket written is the one that name resolves to in
|
||||
// the uploader's account; buckets are per account unless the global bucket namespace is on.
|
||||
String writtenOwner = bucketOwner(event.bucketName());
|
||||
for (LambdaFunction fn : functions) {
|
||||
if (!event.bucketName().equals(fn.getS3Bucket()) || !event.key().equals(fn.getS3Key())) {
|
||||
continue;
|
||||
}
|
||||
// A function reads its code from the bucket its name resolves to in the function's own account, so
|
||||
// only a function whose bucket is the one written redeploys: another account's same-named bucket
|
||||
// must not replace its code.
|
||||
String ownerAccountId = ownerAccount(fn);
|
||||
if (writtenOwner == null
|
||||
|| !writtenOwner.equals(RequestScopes.callAs(ownerAccountId, () -> bucketOwner(event.bucketName())))) {
|
||||
continue;
|
||||
}
|
||||
String region = regionResolver.regionOf(fn.getFunctionArn());
|
||||
if (!async) {
|
||||
syncFromS3(fn, event.bucketName(), event.key(), region);
|
||||
continue;
|
||||
@@ -4771,13 +4780,24 @@ public class LambdaService implements ResourceProvider, VpcDependencyProvider {
|
||||
PendingReactiveSync source = new PendingReactiveSync(regionResolver.getAccountId(),
|
||||
event.bucketName(), event.key());
|
||||
if (pendingReactiveSyncs.put(functionArn, source) == null) {
|
||||
String ownerAccountId = ownerAccount(fn);
|
||||
String functionName = fn.getFunctionName();
|
||||
REACTIVE_SYNC_THREADS.execute(() -> syncQueued(ownerAccountId, region, functionName, functionArn));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The account that owns the bucket {@code bucketName} names for the current caller, or null when none does. */
|
||||
private String bucketOwner(String bucketName) {
|
||||
if (s3Service == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return s3Service.getBucketOwnerAccountId(bucketName);
|
||||
} catch (AwsException noSuchBucket) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads the function, which may have been redeployed or deleted while the sync was queued. */
|
||||
private void syncQueued(String ownerAccountId, String region, String functionName, String functionArn) {
|
||||
// Marked running before the pending source is taken, so the function never reports neither.
|
||||
|
||||
@@ -27,7 +27,7 @@ class LambdaFunctionStoreAccountScopeTest {
|
||||
|
||||
assertTrue(store.list(REGION).isEmpty(),
|
||||
"the ambient scan must not see another account's function");
|
||||
List<LambdaFunction> all = store.listAllAccounts(REGION);
|
||||
List<LambdaFunction> all = store.listAllAccounts();
|
||||
assertEquals(1, all.size());
|
||||
assertEquals("other-fn", all.get(0).getFunctionName());
|
||||
}
|
||||
@@ -45,7 +45,7 @@ class LambdaFunctionStoreAccountScopeTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAllAccountsKeepsTheRegionAndLatestFilter() {
|
||||
void listAllAccountsSeesEveryRegionButOnlyLatest() {
|
||||
LambdaFunctionStore store = accountAwareStore();
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, function("latest-fn", OTHER_ACCOUNT));
|
||||
LambdaFunction published = function("latest-fn", OTHER_ACCOUNT);
|
||||
@@ -53,10 +53,12 @@ class LambdaFunctionStoreAccountScopeTest {
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, published);
|
||||
store.saveForAccount(OTHER_ACCOUNT, "eu-west-1", function("elsewhere-fn", OTHER_ACCOUNT));
|
||||
|
||||
List<LambdaFunction> all = store.listAllAccounts(REGION);
|
||||
List<LambdaFunction> all = store.listAllAccounts();
|
||||
|
||||
assertEquals(1, all.size(), "published versions and other regions must stay excluded");
|
||||
assertEquals("$LATEST", all.get(0).getVersion());
|
||||
assertEquals(2, all.size(), "published versions must stay excluded, other Regions included");
|
||||
assertTrue(all.stream().allMatch(function -> "$LATEST".equals(function.getVersion())));
|
||||
assertEquals(List.of("elsewhere-fn", "latest-fn"), all.stream()
|
||||
.map(LambdaFunction::getFunctionName).sorted().toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -7,7 +7,9 @@ import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.Base64;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
@@ -25,6 +27,12 @@ class LambdaReactiveSyncIntegrationTest {
|
||||
private static final String BUCKET = "reactive-sync-bucket";
|
||||
private static final String KEY = "function.zip";
|
||||
private static final String FN = "reactive-sync-fn";
|
||||
private static final String REGIONAL_BUCKET = "reactive-sync-eu-bucket";
|
||||
private static final String REGIONAL_FN = "reactive-sync-eu-fn";
|
||||
private static final String S3_EU_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=000000000000/20261125/eu-west-1/s3/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
private static final String LAMBDA_EU_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=000000000000/20261125/eu-west-1/lambda/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
|
||||
private static byte[] makeZip(String body) {
|
||||
return LambdaCodeFixtures.nodeJsZip("exports.handler = async (e) => ({ body: '" + body + "' });");
|
||||
@@ -92,4 +100,126 @@ class LambdaReactiveSyncIntegrationTest {
|
||||
void cleanup() {
|
||||
given().when().delete("/2015-03-31/functions/" + FN).then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void uploadRedeploysAFunctionOutsideTheDefaultRegion() throws Exception {
|
||||
byte[] v1 = makeZip("eu-v1");
|
||||
byte[] v2 = makeZip("eu-v2");
|
||||
given().header("Authorization", S3_EU_AUTH)
|
||||
.body("<CreateBucketConfiguration><LocationConstraint>eu-west-1</LocationConstraint>"
|
||||
+ "</CreateBucketConfiguration>")
|
||||
.when().put("/" + REGIONAL_BUCKET).then().statusCode(200);
|
||||
given().header("Authorization", S3_EU_AUTH).body(v1)
|
||||
.when().put("/" + REGIONAL_BUCKET + "/" + KEY).then().statusCode(200);
|
||||
given()
|
||||
.header("Authorization", LAMBDA_EU_AUTH)
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "%s",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Role": "arn:aws:iam::000000000000:role/role",
|
||||
"Handler": "index.handler",
|
||||
"Code": {
|
||||
"S3Bucket": "%s",
|
||||
"S3Key": "%s"
|
||||
}
|
||||
}
|
||||
""".formatted(REGIONAL_FN, REGIONAL_BUCKET, KEY))
|
||||
.when()
|
||||
.post("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("CodeSha256", equalTo(sha256(v1)));
|
||||
|
||||
try {
|
||||
given().header("Authorization", S3_EU_AUTH).body(v2)
|
||||
.when().put("/" + REGIONAL_BUCKET + "/" + KEY).then().statusCode(200);
|
||||
|
||||
// Reactive sync runs synchronously in the test profile, so the redeploy is done when the PUT returns.
|
||||
given()
|
||||
.header("Authorization", LAMBDA_EU_AUTH)
|
||||
.when()
|
||||
.get("/2015-03-31/functions/" + REGIONAL_FN + "/configuration")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("FunctionArn", containsString(":eu-west-1:"))
|
||||
.body("CodeSha256", equalTo(sha256(v2)));
|
||||
} finally {
|
||||
given().header("Authorization", LAMBDA_EU_AUTH)
|
||||
.when().delete("/2015-03-31/functions/" + REGIONAL_FN).then().statusCode(204);
|
||||
given().header("Authorization", S3_EU_AUTH)
|
||||
.when().delete("/" + REGIONAL_BUCKET + "/" + KEY).then().statusCode(204);
|
||||
given().header("Authorization", S3_EU_AUTH)
|
||||
.when().delete("/" + REGIONAL_BUCKET).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Buckets are per account, so two accounts can each own a bucket of the same name. An upload to one account's
|
||||
* bucket must not redeploy the other account's function from the same-named bucket and key: reactive sync
|
||||
* runs synchronously in the test profile, so the function is checked as soon as the upload returns.
|
||||
*/
|
||||
@Test
|
||||
@Order(5)
|
||||
void anUploadToAnotherAccountsSameNamedBucketLeavesTheFunctionAlone() throws Exception {
|
||||
String victim = "000000000731";
|
||||
String attacker = "000000000732";
|
||||
String bucket = "reactive-sync-shared-name";
|
||||
byte[] own = makeZip("victim-v1");
|
||||
byte[] foreign = makeZip("attacker");
|
||||
for (String account : new String[] {victim, attacker}) {
|
||||
given().header("Authorization", auth(account, "s3")).when().put("/" + bucket).then().statusCode(200);
|
||||
}
|
||||
given().header("Authorization", auth(victim, "s3")).body(own)
|
||||
.when().put("/" + bucket + "/" + KEY).then().statusCode(200);
|
||||
given()
|
||||
.header("Authorization", auth(victim, "lambda"))
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "reactive-sync-victim-fn",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Role": "arn:aws:iam::%s:role/role",
|
||||
"Handler": "index.handler",
|
||||
"Code": {"S3Bucket": "%s", "S3Key": "%s"}
|
||||
}
|
||||
""".formatted(victim, bucket, KEY))
|
||||
.when()
|
||||
.post("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.body("CodeSha256", equalTo(sha256(own)));
|
||||
|
||||
try {
|
||||
given().header("Authorization", auth(attacker, "s3")).body(foreign)
|
||||
.when().put("/" + bucket + "/" + KEY).then().statusCode(200);
|
||||
|
||||
given().header("Authorization", auth(victim, "lambda"))
|
||||
.when()
|
||||
.get("/2015-03-31/functions/reactive-sync-victim-fn/configuration")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CodeSha256", equalTo(sha256(own)));
|
||||
} finally {
|
||||
given().header("Authorization", auth(victim, "lambda"))
|
||||
.when().delete("/2015-03-31/functions/reactive-sync-victim-fn").then().statusCode(204);
|
||||
for (String account : new String[] {victim, attacker}) {
|
||||
given().header("Authorization", auth(account, "s3"))
|
||||
.when().delete("/" + bucket + "/" + KEY).then().statusCode(204);
|
||||
given().header("Authorization", auth(account, "s3"))
|
||||
.when().delete("/" + bucket).then().statusCode(204);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String auth(String account, String service) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + account + "/20261125/us-east-1/" + service
|
||||
+ "/aws4_request, SignedHeaders=host, Signature=abc";
|
||||
}
|
||||
|
||||
private static String sha256(byte[] data) throws Exception {
|
||||
return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(data));
|
||||
}
|
||||
}
|
||||
@@ -2496,6 +2496,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void anS3PackageOverTheCompressedLimitGetsTheExtractionError() {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
LambdaService s3Backed = s3BackedService(s3, mock(WarmPool.class), new ZipExtractor());
|
||||
long size = 250L * 1024 * 1024 + 1;
|
||||
when(s3.openObject("code-bucket", "function.zip", null)).thenReturn(new S3Service.ObjectRead(
|
||||
@@ -2570,6 +2572,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void reactiveSyncHoldsThePublicationLockThroughExtraction() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
ZipExtractor extractor = spy(new ZipExtractor());
|
||||
LambdaService syncingService = s3BackedService(s3, warmPool, extractor);
|
||||
@@ -2617,6 +2621,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void reactiveSyncDisabled_leavesTheFunctionOnItsDeployedCode() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
LambdaService syncingService = s3BackedService(s3, warmPool, new ZipExtractor(),
|
||||
reactiveS3SyncConfig(false, false));
|
||||
@@ -2636,6 +2642,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void asyncReactiveSync_returnsBeforeTheRedeployAndReportsInProgressUntilItFinishes() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
ZipExtractor extractor = spy(new ZipExtractor());
|
||||
LambdaService syncingService = s3BackedService(s3, warmPool, extractor, reactiveS3SyncConfig(true, true));
|
||||
@@ -2668,6 +2676,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void asyncReactiveSync_coalescesUploadsThatArriveWhileOneIsRunning() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
ZipExtractor extractor = spy(new ZipExtractor());
|
||||
LambdaService syncingService = s3BackedService(s3, warmPool, extractor, reactiveS3SyncConfig(true, true));
|
||||
@@ -2706,6 +2716,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void asyncReactiveSync_deploysAnUploadToANewSourceWhileTheOldOneIsStillQueued() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
LambdaService syncingService = s3BackedService(s3, warmPool, new ZipExtractor(),
|
||||
reactiveS3SyncConfig(true, true));
|
||||
@@ -2736,6 +2748,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void failedReactiveSync_reportsFailedUntilTheNextCodeUpdate() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
WarmPool warmPool = mock(WarmPool.class);
|
||||
LambdaService syncingService = s3BackedService(s3, warmPool, new ZipExtractor(),
|
||||
reactiveS3SyncConfig(true, false));
|
||||
@@ -2755,6 +2769,8 @@ class LambdaServiceTest {
|
||||
@Test
|
||||
void failedReactiveSync_isClearedByAConfigurationUpdate() throws Exception {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
// One account owns every bucket here, so a function and the upload name the same bucket.
|
||||
when(s3.getBucketOwnerAccountId(anyString())).thenReturn("000000000000");
|
||||
LambdaService syncingService = s3BackedService(s3, mock(WarmPool.class), new ZipExtractor(),
|
||||
reactiveS3SyncConfig(true, false));
|
||||
LambdaFunction latest = functionWhoseLastSyncFailed(syncingService, s3);
|
||||
|
||||
Reference in new issue
Block a user