mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(lambda): code-signing endpoints and account settings (#2646)
* feat(lambda): GetAccountSettings with usage-derived account limits Adds the Lambda GetAccountSettings operation. AccountUsage (total code size and function count) is derived from the caller's stored $LATEST functions in the region; AccountLimit reports the configured regional concurrency limit and its unreserved share after per-function reserved concurrency. * fix(lambda): widen the default Runtime API port pool to 12000-12499 One Runtime API port is held for the lifetime of each running Lambda container, so the width of the range is a hard ceiling on concurrent Lambda executions. The old default of 9200-9299 gave 100, which a multi-account AWS Landing Zone Accelerator deployment exhausts: it fans out several custom-resource Lambdas per account and can want well over a hundred at once. Exhaustion did not announce itself as a capacity limit either. The custom resource reported FAILED and CloudFormation rolled the stack back, so an operator saw an apparently unrelated CloudFormation error with no hint that a port pool was the cause. 12000 rather than a widened 9200 because the old range's tail collides with ports floci and its sidecars already use: 9200 is OpenSearch's own REST port, 9400-9499 is the OpenSearch host-binding pool, 9092 is Kafka and 9644 Redpanda's admin port. Both application.yml and the @WithDefault annotation are updated. application.yml is a config source, not a set of defaults, so a value set there wins over the annotation; changing only the annotation would have been a silent no-op (issue #2225). The new test asserts the two agree, so they cannot drift apart again. Refs #2206 * fix(lambda): make the Runtime API port-pool exhaustion error self-describing The old message did not name the pool, its width, or the property that widens it. It also rarely reaches an operator directly: the Lambda failure surfaces as a custom resource reporting FAILED and CloudFormation rolling the stack back, so this text is buried in floci's own log alongside a CloudFormation error that looks unrelated. The message now carries its own diagnosis — which pool ran dry, how many ports it had, that one port is held per running container so this is the concurrent-execution ceiling, and the two properties that widen it. Previously the only way to learn those knobs existed was to find this class in the source. Refs #2206 * feat(lambda): add ListFunctionsByCodeSigningConfig Net-new endpoint, GET /2020-04-22/code-signing-configs/{arn}/functions, always returns an empty FunctionArns list since this codebase has no CodeSigningConfig management (no Create/PutFunctionCodeSigningConfig), so no function can ever actually have one attached. Implemented as its own controller class with its own class-level @Path("/2020-04-22") rather than folding it into the existing LambdaCodeSigningController (/2020-06-30): a JAX-RS class-level @Path is load-bearing for route-matching priority, and stripping it to share one class across two API-version prefixes causes both endpoints to fall through to a more general catch-all route elsewhere in the app. * fix(lambda): scope code storage, publish-version counters, and S3 sync-reload to the owning account CodeStore resolved extracted code to baseDir/<functionName> with no account segment, so two accounts' same-named functions in one region shared a single on-disk directory and overwrote each other's package -- while codeObjectKey already wrote the same package to an account-prefixed S3 key. Cross-account invoke resolves a function by the ARN's own account, so a collision here silently serves one account's code under the other's ARN. The PublishVersion counter was keyed region+"::"+functionName and the delete path removed that same unscoped key; both now key on the owning account, via the shared ownerAccount() helper the S3 key already used. onS3ObjectUpdated runs on the CDI event thread with no RequestContext, so its ambient scan only ever saw the default account's partition and its save wrote back into that partition. It now lists across every account (keeping the region and $LATEST filters) and saves into the function's own account. listAll(), whose only caller is the startup concurrency rehydration, is broadened the same way so a restart no longer drops non-default accounts' reserved concurrency. Recovered from 613db7bd1, re-derived onto upstream's current shape: CodeStore's methods are re-signed rather than overloaded (the unscoped forms had no remaining consumer), and the sync-reload uses a new region-filtered listAllAccounts() instead of widening listAll() at that call site. * fix(lambda): carry persisted version counters across the account-scoped key change The counter map is persisted precisely so a restart cannot re-issue a version number that already names a snapshot. Re-keying it on the owning account made every pre-existing entry unreachable, so the next PublishVersion on an upgraded deployment would have started again at 1 and overwritten the live :1 snapshot. The counter now adopts and clears the pre-account key on a miss, and deleting a function clears both forms. Also covers the widened listAll(): the reserved-concurrency pool is per region and shared across accounts, so the startup rehydration that feeds it has to see every account or a restart silently frees capacity that steady-state PutFunctionConcurrency had already accounted for. * fix(lambda): validate CodeSigningConfigArn on ListFunctionsByCodeSigningConfig The handler took @PathParam("codeSigningConfigArn") and never read it, so any input — including "not-an-arn" — got a 200 with an empty FunctionArns array. It also dropped the modeled Marker/MaxItems query parameters. Botocore models InvalidParameterValueException (400) and ResourceNotFoundException (404) for this operation, and carries a pattern on the CodeSigningConfigArn shape: arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}((-gov)|(-iso(b?)))?-[a-z]+-\d{1} :\d{12}:code-signing-config:csc-[a-z0-9]{17} (max 200 chars). That pattern is now applied verbatim, whole-string. The 404 for a well-formed ARN is a derivation, not an observation against real AWS: ResourceNotFoundException is modeled for this operation, the only resource the path parameter can name is a code-signing config, and Floci implements no CreateCodeSigningConfig / PutFunctionCodeSigningConfig — therefore every well-formed ARN necessarily names a config that does not exist. The previous always-empty 200 asserted the opposite (config exists, has no functions), which is the stronger and false claim. Validation order matches AWS: ARN shape, then MaxItems range (botocore MaxListItems: min 1, max 10000), then resource resolution — so a bad MaxItems is reported as such instead of being masked by the not-found. Marker is accepted and stateless: the result set is always empty, so no NextMarker is ever emitted. The pre-existing test asserted the 200-empty behaviour using an ARN whose csc- suffix was 9 characters, which the model's pattern rejects; it is replaced by six cases covering the two error classes and both MaxItems bounds. docs/services/lambda.md's two "always empty" claims are corrected to match. * docs(lambda): derive the operation count from the routed operations The branch adds two operations (GetAccountSettings and ListFunctionsByCodeSigningConfig) but bumped docs/services/index.md by one, 30 -> 31. Rather than hand-correcting to 32, the count was re-derived from the routes, because 30 could not be reconstructed from anything in the tree. index.md's own preamble states the rule for REST services: "the count reflects distinct AWS SDK operations, collapsing routes where one JAX-RS handler fans out via query-string or header markers". Counting JAX-RS methods across the Lambda controllers on upstream/main gives: LambdaController 24 LambdaConcurrencyController 3 LambdaEventInvokeController 5 LambdaLayerController 5 LambdaTagController 3 LambdaUrlController 4 -- 44 Two collapses applied. LambdaCodeSigningController's /2020-06-30 route and LambdaController's /2015-03-31 route are the same SDK operation (GetFunctionCodeSigningConfig) and count once. LambdaUrlInvocationController (5) and the lambda-package ApiGatewayController (5) are data-plane proxies with {proxy: .*} catch-alls, not Lambda SDK operations, so they are excluded. 44 + GetAccountSettings + ListFunctionsByCodeSigningConfig = 46. Corroboration that 44 is the real base and 30 is drift: docs/services/lambda.md's Supported Operations table lists 34 rows on upstream/main and omits exactly the 5 layer and 5 event-invoke operations — 34 + 10 = 44. Those 10 missing table rows are pre-existing and left alone here; only the count is in scope. * fix(lambda): match the current CodeSigningConfigArn pattern for isolated partitions The inlined regex predated the model's (eusc-)? prefix and widened -iso(b?) alternation, so a well-formed ARN in aws-iso-e/iso-f or the European sovereign cloud was rejected as malformed instead of reaching the modeled 404. * fix(lambda): validate FunctionName length, Role ARN, and Handler on config paths botocore models FunctionName up to 256 chars with dots allowed in the name segment; LambdaArnUtils rejected dots and never bounded length. Also close the gap where UpdateFunctionConfiguration accepted a malformed Role ARN or a whitespace-containing/oversized Handler and stored it verbatim. * fix(lambda): close leaked directory-listing streams and block dot-segment traversal in CodeStore Files.walk/Files.list returned streams that were never closed, leaking file descriptors and making delete() flaky on platforms that refuse to remove an open file. Separately, sanitizeName replaced disallowed characters but let a segment consisting entirely of dots (".", "..") pass through untouched, so an account or function name of exactly ".." resolved outside baseDir via Path.resolve instead of being rejected. * fix(lambda): reclaim pre-account-scoped code directories on delete and update A function created before code storage was account-scoped left its extracted code at <codePath>/<functionName>. DeleteFunction only ever targeted the new <codePath>/<accountId>/<functionName> path, and UpdateFunctionCode re-extracted to the new path without touching the old one, so the legacy directory (and its disk usage) lingered indefinitely after either operation. CodeStore now also clears the legacy path on delete, and re-extraction reclaims it on success. * fix(lambda): reject an explicit null Handler on UpdateFunctionConfiguration validateHandler treated null as "clear the handler", matching how Description is handled, but null is not a string at all -- and unlike Description, Handler names the file AWS invokes. A request with "Handler": null silently cleared it instead of failing with a 400, which would have broken every subsequent invocation of the function instead of the one bad request that caused it. * fix(lambda): do not reclaim a legacy code directory another account's function still uses The pre-account-scoped layout gave every account's same-named function the exact same on-disk directory. CodeStore.delete() and code re-extraction both reclaimed that legacy directory unconditionally once a function migrated to the account-scoped path, so a delete or code update in one account could destroy the legacy directory while another account's never-migrated $LATEST still served invocations from it -- its next cold start would then fail with a missing code directory. CodeStore.delete() no longer touches the legacy path at all; only LambdaService calls deleteLegacy() explicitly, after checking every account's $LATEST functions (via the existing cross-account listAllAccounts) for one still pointing its codeLocalPath at that directory. * fix(lambda): check published versions, not just $LATEST, before reclaiming a legacy code directory publishVersion snapshots codeLocalPath verbatim (required so a version-qualified invoke doesn't launch a container with no code, #1987), so a version published while $LATEST was still on the pre-account-scoped legacy path keeps that directory alive on its own after $LATEST migrates. The unused-check only scanned $LATEST records via listAllAccounts(region), so a later delete or code update reclaimed the directory out from under that published version's own future invokes. Switched to functionStore.listAll(), which has no $LATEST or region filter, matching the fact that the legacy path itself carries neither. * fix(lambda): close a publish-vs-legacy-cleanup race on the code directory publishVersion read codeLocalPath and persisted a snapshot of it with no synchronization against extractZipCodeBytes's/deleteFunction's decision to reclaim the pre-account-scoped legacy code directory (added inbede98fc1andf3837be32). A version could be published in the narrow window between that decision (finding no live reference) and the actual delete, persisting a snapshot whose codeLocalPath names a directory that is about to be removed -- its own future invocation would then fail with "Code directory not found". publishVersion and the reclaim call in extractZipCodeBytes now both take the same per-function lock deleteFunction already used for this. Proven with a test that holds the lock externally and asserts publishVersion blocks until it is released, rather than relying on timing to catch the race in the act.
This commit is contained in:
1 parent
64c38c77b9
commit
c90c5adfcb
26 files changed
+1446
-97
No files matched your search
@@ -51,6 +51,29 @@ class PortAllocatorTest {
|
||||
assertThrows(IllegalStateException.class, allocator::allocate);
|
||||
}
|
||||
|
||||
/**
|
||||
* When the pool runs dry the exception is often the only artefact an operator ever sees —
|
||||
* it reaches them second-hand as a CloudFormation rollback, with floci's own logs the only
|
||||
* place the cause survives (issue #2206). "No free ports in range 9200-9299" does not say
|
||||
* which pool ran dry or how to widen it, leaving the reader to find PortAllocator in the
|
||||
* source to discover the knob exists. The message must carry its own diagnosis.
|
||||
*/
|
||||
@Test
|
||||
void exhaustionMessageNamesThePoolAndTheWideningProperty() {
|
||||
PortAllocator allocator = new PortAllocator(9200, 9200);
|
||||
allocator.allocate();
|
||||
|
||||
IllegalStateException thrown = assertThrows(IllegalStateException.class, allocator::allocate);
|
||||
String message = thrown.getMessage();
|
||||
|
||||
assertTrue(message.contains("Lambda Runtime API"),
|
||||
"message must name the pool that ran dry; got: " + message);
|
||||
assertTrue(message.contains("floci.services.lambda.runtime-api-max-port"),
|
||||
"message must name the property that widens the pool; got: " + message);
|
||||
assertTrue(message.contains("9200"),
|
||||
"message must still report the exhausted range; got: " + message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void releasedPortBecomesAvailableAgain() {
|
||||
PortAllocator allocator = new PortAllocator(9200, 9201);
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package io.github.hectorvent.floci.core.common.port;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.smallrye.config.WithDefault;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The Lambda Runtime API port pool's *default* width is a capacity ceiling on concurrent Lambda
|
||||
* executions, because one port is held for the lifetime of each running Lambda container.
|
||||
*
|
||||
* <p>The original default of 9200-9299 was exactly 100 ports, which cannot run a multi-account
|
||||
* landing zone: LZA's LoggingStack alone fans out roughly 8 custom-resource Lambdas per account,
|
||||
* so a 14-account org needs ~112 concurrently and exhausts the pool (issue #2206). Worse, the
|
||||
* failure does not present as a capacity limit — the custom resource reports FAILED and
|
||||
* CloudFormation rolls the stack back, so the operator sees an unrelated-looking CFN error.
|
||||
*
|
||||
* <p>These assertions pin the two properties that made the old default wrong, so a future edit
|
||||
* cannot quietly reintroduce either. They read the annotation rather than booting the config,
|
||||
* which keeps the guard fast and dependency-free.
|
||||
*/
|
||||
class RuntimeApiPortPoolDefaultTest {
|
||||
|
||||
/** Enough for a ~14-account landing zone (~112 concurrent) with headroom for Deploy. */
|
||||
private static final int MIN_USABLE_POOL_WIDTH = 500;
|
||||
|
||||
/**
|
||||
* The value that actually takes effect. {@code application.yml} is a config SOURCE, not a
|
||||
* set of defaults, so any key it sets WINS over the interface's {@code @WithDefault} — the
|
||||
* same trap that made {@code storage.mode} ignore its annotation (issue #2225). Reading only
|
||||
* the annotation would let a widened default pass this suite while the running emulator kept
|
||||
* the old 100-port pool, so resolve the yaml first and fall back to the annotation.
|
||||
*/
|
||||
private static int defaultOf(String method) throws Exception {
|
||||
Integer fromYaml = yamlValue(kebab(method));
|
||||
return fromYaml != null ? fromYaml : annotationDefaultOf(method);
|
||||
}
|
||||
|
||||
private static int annotationDefaultOf(String method) throws NoSuchMethodException {
|
||||
Method m = EmulatorConfig.LambdaServiceConfig.class.getMethod(method);
|
||||
WithDefault d = m.getAnnotation(WithDefault.class);
|
||||
assertNotNull(d, method + "() must carry an explicit @WithDefault");
|
||||
return Integer.parseInt(d.value());
|
||||
}
|
||||
|
||||
/** {@code runtimeApiBasePort} -> {@code runtime-api-base-port}. */
|
||||
private static String kebab(String method) {
|
||||
return method.replaceAll("([a-z0-9])([A-Z])", "$1-$2").toLowerCase(java.util.Locale.ROOT);
|
||||
}
|
||||
|
||||
/** The value under {@code floci.services.lambda.<key>} in application.yml, or null. */
|
||||
private static Integer yamlValue(String key) throws Exception {
|
||||
java.nio.file.Path yml = java.nio.file.Path.of("src/main/resources/application.yml");
|
||||
assertTrue(java.nio.file.Files.exists(yml), "application.yml not found at " + yml.toAbsolutePath());
|
||||
java.util.regex.Pattern p =
|
||||
java.util.regex.Pattern.compile("^\\s*" + java.util.regex.Pattern.quote(key) + ":\\s*(\\d+)\\s*$");
|
||||
for (String line : java.nio.file.Files.readAllLines(yml)) {
|
||||
java.util.regex.Matcher m = p.matcher(line);
|
||||
if (m.matches()) {
|
||||
return Integer.valueOf(m.group(1));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Test
|
||||
void annotationDefaultAndApplicationYamlAgree() throws Exception {
|
||||
for (String method : new String[] {"runtimeApiBasePort", "runtimeApiMaxPort"}) {
|
||||
Integer yaml = yamlValue(kebab(method));
|
||||
if (yaml != null) {
|
||||
assertEquals(annotationDefaultOf(method), yaml.intValue(),
|
||||
kebab(method) + " differs between @WithDefault and application.yml; the "
|
||||
+ "yaml wins at runtime, so the annotation would be a lie");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultPoolIsWideEnoughForAMultiAccountLandingZone() throws Exception {
|
||||
int base = defaultOf("runtimeApiBasePort");
|
||||
int max = defaultOf("runtimeApiMaxPort");
|
||||
int width = max - base + 1;
|
||||
|
||||
assertTrue(width >= MIN_USABLE_POOL_WIDTH,
|
||||
"default Runtime API pool is " + width + " ports (" + base + "-" + max + "); "
|
||||
+ "a multi-account LZA needs at least " + MIN_USABLE_POOL_WIDTH
|
||||
+ " or it exhausts mid-deploy and surfaces as a CloudFormation rollback");
|
||||
}
|
||||
|
||||
@Test
|
||||
void defaultPoolDoesNotOverlapPortsFlociAlreadyUses() throws Exception {
|
||||
int base = defaultOf("runtimeApiBasePort");
|
||||
int max = defaultOf("runtimeApiMaxPort");
|
||||
|
||||
// A pool this wide stops being obvious about what it covers, so the overlaps that matter
|
||||
// are asserted rather than reasoned about: 9200 OpenSearch, 9092 Kafka, 9644 Redpanda
|
||||
// admin, 9400-9499 the ECS proxy pool, 4566 the emulator's own port, 6379-6399 Redis.
|
||||
int[][] forbidden = {
|
||||
{4566, 4566}, {6379, 6399}, {9092, 9092},
|
||||
{9200, 9200}, {9400, 9499}, {9644, 9644},
|
||||
};
|
||||
for (int[] range : forbidden) {
|
||||
boolean overlaps = base <= range[1] && range[0] <= max;
|
||||
assertFalse(overlaps, "default Runtime API pool " + base + "-" + max
|
||||
+ " overlaps reserved ports " + range[0] + "-" + range[1]);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void basePortPrecedesMaxPort() throws Exception {
|
||||
assertTrue(defaultOf("runtimeApiBasePort") < defaultOf("runtimeApiMaxPort"),
|
||||
"base port must be below max port or the pool is empty");
|
||||
}
|
||||
|
||||
@Test
|
||||
void poolHonoursTheConfiguredWidthAtRuntime() throws Exception {
|
||||
// The annotation is only a default; prove the allocator actually hands out the whole
|
||||
// configured range, so widening the default genuinely raises the concurrency ceiling.
|
||||
int base = defaultOf("runtimeApiBasePort");
|
||||
int max = defaultOf("runtimeApiMaxPort");
|
||||
PortAllocator allocator = new PortAllocator(base, max);
|
||||
|
||||
java.util.Set<Integer> handed = new java.util.HashSet<>();
|
||||
for (int i = 0; i < MIN_USABLE_POOL_WIDTH; i++) {
|
||||
assertTrue(handed.add(allocator.allocate()),
|
||||
"allocator handed out a duplicate port after " + handed.size() + " allocations");
|
||||
}
|
||||
|
||||
assertEquals(MIN_USABLE_POOL_WIDTH, handed.size(),
|
||||
"allocator must yield at least " + MIN_USABLE_POOL_WIDTH
|
||||
+ " concurrent ports across the full configured range");
|
||||
}
|
||||
}
|
||||
+228
@@ -0,0 +1,228 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import io.github.hectorvent.floci.services.lambda.zip.CodeStore;
|
||||
import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Two accounts owning a same-named function in the same region must not share
|
||||
* on-disk extracted code or a PublishVersion counter. Cross-account invoke
|
||||
* resolves a function by the ARN's own account ({@code LambdaService.resolveInvokeTarget}),
|
||||
* so a collision here silently serves one account's code under the other's ARN.
|
||||
*/
|
||||
class LambdaAccountScopedCodeTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT_A = "111111111111";
|
||||
private static final String ACCOUNT_B = "222222222222";
|
||||
|
||||
@Test
|
||||
void sameFunctionNameInTwoAccountsKeepsItsOwnCodeOnDisk(@TempDir Path baseDir) throws Exception {
|
||||
CodeStore sharedCodeStore = new CodeStore(baseDir);
|
||||
LambdaService svcA = serviceFor(ACCOUNT_A, sharedCodeStore);
|
||||
LambdaService svcB = serviceFor(ACCOUNT_B, sharedCodeStore);
|
||||
|
||||
LambdaFunction a = svcA.createFunction(REGION, zipRequest("shared-fn", "module.exports.handler = 'A';"));
|
||||
LambdaFunction b = svcB.createFunction(REGION, zipRequest("shared-fn", "module.exports.handler = 'B';"));
|
||||
|
||||
assertNotEquals(a.getCodeLocalPath(), b.getCodeLocalPath(),
|
||||
"each account's function must extract to its own directory");
|
||||
assertEquals("module.exports.handler = 'A';",
|
||||
Files.readString(Path.of(a.getCodeLocalPath()).resolve("index.js")),
|
||||
"account A's code must survive account B's create");
|
||||
assertEquals("module.exports.handler = 'B';",
|
||||
Files.readString(Path.of(b.getCodeLocalPath()).resolve("index.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingOneAccountsFunctionLeavesTheOthersCodeIntact(@TempDir Path baseDir) throws Exception {
|
||||
CodeStore sharedCodeStore = new CodeStore(baseDir);
|
||||
LambdaService svcA = serviceFor(ACCOUNT_A, sharedCodeStore);
|
||||
LambdaService svcB = serviceFor(ACCOUNT_B, sharedCodeStore);
|
||||
|
||||
LambdaFunction a = svcA.createFunction(REGION, zipRequest("shared-fn", "A"));
|
||||
svcB.createFunction(REGION, zipRequest("shared-fn", "B"));
|
||||
|
||||
svcB.deleteFunction(REGION, "shared-fn");
|
||||
|
||||
assertTrue(sharedCodeStore.exists(ACCOUNT_A, "shared-fn"),
|
||||
"deleting B's function must not delete A's code");
|
||||
assertEquals("A", Files.readString(Path.of(a.getCodeLocalPath()).resolve("index.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishVersionCounterKeyCarriesTheOwningAccount() {
|
||||
LambdaFunction a = functionOwnedBy(ACCOUNT_A);
|
||||
LambdaFunction b = functionOwnedBy(ACCOUNT_B);
|
||||
|
||||
assertNotEquals(LambdaService.versionCounterKey(REGION, a), LambdaService.versionCounterKey(REGION, b),
|
||||
"same-named functions in different accounts must number versions independently");
|
||||
assertTrue(LambdaService.versionCounterKey(REGION, a).contains(ACCOUNT_A));
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishVersionAdoptsACounterPersistedUnderThePreAccountKey(@TempDir Path baseDir) throws Exception {
|
||||
// The counter map is persisted, and its whole point is that a restart must not re-issue
|
||||
// an already-used version number. Re-keying it must therefore carry the old value
|
||||
// forward rather than restart numbering from 1 over existing snapshots.
|
||||
LambdaService svc = serviceFor(ACCOUNT_A, new CodeStore(baseDir));
|
||||
svc.createFunction(REGION, zipRequest("legacy-fn", "A"));
|
||||
svc.versionCounters().put(REGION + "::legacy-fn", 3);
|
||||
|
||||
LambdaFunction published = svc.publishVersion(REGION, "legacy-fn", null);
|
||||
|
||||
assertEquals("4", published.getVersion());
|
||||
assertNull(svc.versionCounters().get(REGION + "::legacy-fn"),
|
||||
"the migrated legacy entry must not linger and be adopted twice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionCodeRemovesAPreAccountScopedLegacyDirectory(@TempDir Path baseDir) throws Exception {
|
||||
// A function created before account-scoping left its code at baseDir/<functionName>.
|
||||
// Updating its code after the upgrade re-extracts to the new account-scoped path but
|
||||
// must also reclaim the old directory, or it lingers on disk forever.
|
||||
CodeStore codeStore = new CodeStore(baseDir);
|
||||
LambdaService svc = serviceFor(ACCOUNT_A, codeStore);
|
||||
svc.createFunction(REGION, zipRequest("legacy-fn", "A"));
|
||||
Path legacyPath = codeStore.getLegacyCodePath("legacy-fn");
|
||||
Files.createDirectories(legacyPath);
|
||||
Files.writeString(legacyPath.resolve("index.js"), "stale");
|
||||
|
||||
svc.updateFunctionCode(REGION, "legacy-fn",
|
||||
Map.of("ZipFile", zipBase64("index.js", "B")));
|
||||
|
||||
assertFalse(Files.exists(legacyPath), "the pre-account-scoped directory must be reclaimed on update");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionCodeDoesNotDeleteALegacyDirectoryStillReferencedByAPublishedVersion(
|
||||
@TempDir Path baseDir) throws Exception {
|
||||
// publishVersion snapshots codeLocalPath verbatim (it must, or a version-qualified
|
||||
// invoke launches a container with no code - see #1987). If $LATEST was still on the
|
||||
// legacy path at publish time, that version's snapshot is now the ONLY thing keeping
|
||||
// the legacy directory alive once $LATEST itself migrates. The unused-check only scanned
|
||||
// $LATEST records, so it missed this and reclaimed the directory out from under the
|
||||
// published version's own future invokes.
|
||||
CodeStore codeStore = new CodeStore(baseDir);
|
||||
LambdaService svc = serviceFor(ACCOUNT_A, codeStore);
|
||||
svc.createFunction(REGION, zipRequest("legacy-version-fn", "v1"));
|
||||
|
||||
Path legacyPath = codeStore.getLegacyCodePath("legacy-version-fn");
|
||||
Files.createDirectories(legacyPath);
|
||||
Files.writeString(legacyPath.resolve("index.js"), "v1");
|
||||
LambdaFunction latest = svc.getFunction(REGION, "legacy-version-fn");
|
||||
latest.setCodeLocalPath(legacyPath.toAbsolutePath().normalize().toString());
|
||||
|
||||
LambdaFunction version = svc.publishVersion(REGION, "legacy-version-fn", null);
|
||||
assertEquals(legacyPath.toAbsolutePath().normalize().toString(), version.getCodeLocalPath(),
|
||||
"the published version must have snapshotted the legacy path");
|
||||
|
||||
svc.updateFunctionCode(REGION, "legacy-version-fn", Map.of("ZipFile", zipBase64("index.js", "v2")));
|
||||
|
||||
assertTrue(Files.exists(legacyPath),
|
||||
"a legacy directory a published version still references must survive this update");
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionCodeDoesNotDeleteALegacyDirectoryStillLiveForAnotherAccount(@TempDir Path baseDir) throws Exception {
|
||||
// Before account-scoping, two accounts' same-named functions shared the exact same
|
||||
// on-disk directory. If account B's function was never updated since the migration, its
|
||||
// $LATEST still points at that shared legacy directory. Account A updating its own code
|
||||
// must not delete it out from under B.
|
||||
CodeStore codeStore = new CodeStore(baseDir);
|
||||
LambdaFunctionStore sharedStore = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT_A));
|
||||
LambdaService svcA = new LambdaService(sharedStore, new WarmPool(), codeStore, new ZipExtractor(),
|
||||
new RegionResolver(REGION, ACCOUNT_A));
|
||||
svcA.createFunction(REGION, zipRequest("shared-fn", "A"));
|
||||
|
||||
Path legacyPath = codeStore.getLegacyCodePath("shared-fn");
|
||||
Files.createDirectories(legacyPath);
|
||||
Files.writeString(legacyPath.resolve("index.js"), "B-legacy");
|
||||
LambdaFunction bFn = new LambdaFunction();
|
||||
bFn.setFunctionName("shared-fn");
|
||||
bFn.setAccountId(ACCOUNT_B);
|
||||
bFn.setVersion("$LATEST");
|
||||
bFn.setCodeLocalPath(legacyPath.toAbsolutePath().normalize().toString());
|
||||
sharedStore.saveForAccount(ACCOUNT_B, REGION, bFn);
|
||||
|
||||
svcA.updateFunctionCode(REGION, "shared-fn", Map.of("ZipFile", zipBase64("index.js", "A-v2")));
|
||||
|
||||
assertTrue(Files.exists(legacyPath),
|
||||
"a legacy directory another account's $LATEST still points at must survive this update");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFunctionDoesNotDeleteALegacyDirectoryStillLiveForAnotherAccount(@TempDir Path baseDir) throws Exception {
|
||||
CodeStore codeStore = new CodeStore(baseDir);
|
||||
LambdaFunctionStore sharedStore = new LambdaFunctionStore(AccountAwareStorageBackend.inMemory(ACCOUNT_A));
|
||||
LambdaService svcA = new LambdaService(sharedStore, new WarmPool(), codeStore, new ZipExtractor(),
|
||||
new RegionResolver(REGION, ACCOUNT_A));
|
||||
svcA.createFunction(REGION, zipRequest("shared-fn", "A"));
|
||||
|
||||
Path legacyPath = codeStore.getLegacyCodePath("shared-fn");
|
||||
Files.createDirectories(legacyPath);
|
||||
Files.writeString(legacyPath.resolve("index.js"), "B-legacy");
|
||||
LambdaFunction bFn = new LambdaFunction();
|
||||
bFn.setFunctionName("shared-fn");
|
||||
bFn.setAccountId(ACCOUNT_B);
|
||||
bFn.setVersion("$LATEST");
|
||||
bFn.setCodeLocalPath(legacyPath.toAbsolutePath().normalize().toString());
|
||||
sharedStore.saveForAccount(ACCOUNT_B, REGION, bFn);
|
||||
|
||||
svcA.deleteFunction(REGION, "shared-fn");
|
||||
|
||||
assertTrue(Files.exists(legacyPath),
|
||||
"a legacy directory another account's $LATEST still points at must survive this delete");
|
||||
}
|
||||
|
||||
private LambdaFunction functionOwnedBy(String accountId) {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setAccountId(accountId);
|
||||
fn.setFunctionName("shared-fn");
|
||||
return fn;
|
||||
}
|
||||
|
||||
private LambdaService serviceFor(String accountId, CodeStore codeStore) {
|
||||
return new LambdaService(
|
||||
new LambdaFunctionStore(new InMemoryStorage<String, LambdaFunction>()),
|
||||
new WarmPool(),
|
||||
codeStore,
|
||||
new ZipExtractor(),
|
||||
new RegionResolver(REGION, accountId));
|
||||
}
|
||||
|
||||
private Map<String, Object> zipRequest(String name, String handlerSource) throws Exception {
|
||||
return new java.util.HashMap<>(Map.of(
|
||||
"FunctionName", name,
|
||||
"Runtime", "nodejs20.x",
|
||||
"Role", "arn:aws:iam::000000000000:role/test-role",
|
||||
"Handler", "index.handler",
|
||||
"Code", Map.of("ZipFile", zipBase64("index.js", handlerSource))
|
||||
));
|
||||
}
|
||||
|
||||
private String zipBase64(String entryName, String content) throws Exception {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||
zip.putNextEntry(new ZipEntry(entryName));
|
||||
zip.write(content.getBytes());
|
||||
zip.closeEntry();
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(out.toByteArray());
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.util.Base64;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* Verifies GetAccountSettings: {@code GET /2016-08-19/account-settings/}. Account limits mirror
|
||||
* AWS's fixed storage defaults plus the configured concurrency limit; usage reflects the caller's
|
||||
* stored functions. Distinct account ids in the credential keep the usage assertions isolated
|
||||
* from other Lambda tests.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class LambdaAccountSettingsIntegrationTest {
|
||||
|
||||
private static final String SETTINGS_PATH = "/2016-08-19/account-settings/";
|
||||
|
||||
@Test
|
||||
void accountSettings_emptyAccount_returnsAwsLimitsAndZeroUsage() {
|
||||
given()
|
||||
.header("Authorization", auth("000000000401"))
|
||||
.when()
|
||||
.get(SETTINGS_PATH)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("AccountLimit.TotalCodeSize", equalTo(80530636800L))
|
||||
.body("AccountLimit.CodeSizeUnzipped", equalTo(262144000))
|
||||
.body("AccountLimit.CodeSizeZipped", equalTo(52428800))
|
||||
.body("AccountLimit.ConcurrentExecutions", equalTo(1000))
|
||||
.body("AccountLimit.UnreservedConcurrentExecutions", equalTo(1000))
|
||||
.body("AccountUsage.TotalCodeSize", equalTo(0))
|
||||
.body("AccountUsage.FunctionCount", equalTo(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountSettings_reflectsStoredFunctionsAndReservedConcurrency() {
|
||||
String authorization = auth("000000000402");
|
||||
int codeSize = given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", authorization)
|
||||
.body("""
|
||||
{
|
||||
"FunctionName": "account-settings-fn",
|
||||
"Runtime": "nodejs20.x",
|
||||
"Role": "arn:aws:iam::000000000402:role/lambda-role",
|
||||
"Handler": "index.handler",
|
||||
"Code": {"ZipFile": "%s"}
|
||||
}
|
||||
""".formatted(zipBase64()))
|
||||
.when()
|
||||
.post("/2015-03-31/functions")
|
||||
.then()
|
||||
.statusCode(201)
|
||||
.extract().path("CodeSize");
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.header("Authorization", authorization)
|
||||
.body("{\"ReservedConcurrentExecutions\": 25}")
|
||||
.when()
|
||||
.put("/2017-10-31/functions/account-settings-fn/concurrency")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.header("Authorization", authorization)
|
||||
.when()
|
||||
.get(SETTINGS_PATH)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("AccountUsage.FunctionCount", equalTo(1))
|
||||
.body("AccountUsage.TotalCodeSize", equalTo(codeSize))
|
||||
.body("AccountLimit.ConcurrentExecutions", equalTo(1000))
|
||||
.body("AccountLimit.UnreservedConcurrentExecutions", equalTo(975));
|
||||
}
|
||||
|
||||
private static String auth(String accountId) {
|
||||
return "AWS4-HMAC-SHA256 Credential=" + accountId + "/20260101/us-east-1/lambda/aws4_request";
|
||||
}
|
||||
|
||||
private static String zipBase64() {
|
||||
try {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(out)) {
|
||||
zip.putNextEntry(new ZipEntry("index.js"));
|
||||
zip.write("exports.handler = async () => ({ ok: true });".getBytes());
|
||||
zip.closeEntry();
|
||||
}
|
||||
return Base64.getEncoder().encodeToString(out.toByteArray());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ class LambdaArnUtilsTest {
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:my-fn:prod, my-fn, prod, us-east-1",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:my-fn:$LATEST, my-fn, $LATEST, us-east-1",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:my_fn-1, my_fn-1, , us-east-1",
|
||||
"my.fn.v2, my.fn.v2, , ",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:my.fn.v2, my.fn.v2, , us-east-1",
|
||||
})
|
||||
void resolveAcceptsValidForms(String input, String expectedName, String expectedQualifier, String expectedRegion) {
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(input);
|
||||
@@ -56,6 +58,21 @@ class LambdaArnUtilsTest {
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveRejectsNameLongerThan256Chars() {
|
||||
String tooLong = "a".repeat(257);
|
||||
AwsException ex = assertThrows(AwsException.class, () -> LambdaArnUtils.resolve(tooLong));
|
||||
assertEquals("InvalidParameterValueException", ex.getErrorCode());
|
||||
assertEquals(400, ex.getHttpStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveAccepts256CharName() {
|
||||
String maxLen = "a".repeat(256);
|
||||
LambdaArnUtils.ResolvedFunctionRef ref = LambdaArnUtils.resolve(maxLen);
|
||||
assertEquals(maxLen, ref.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveRejectsNull() {
|
||||
assertThrows(AwsException.class, () -> LambdaArnUtils.resolve(null));
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* The S3 sync-reload observer runs with no {@code RequestContext}, so it sees the default
|
||||
* account's partition. It needs an all-accounts view to find the function an S3 update
|
||||
* belongs to, and an explicit-account save to put it back where it came from.
|
||||
*/
|
||||
class LambdaFunctionStoreAccountScopeTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String DEFAULT_ACCOUNT = "000000000000";
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
|
||||
@Test
|
||||
void listAllAccountsSeesFunctionsOutsideTheAmbientPartition() {
|
||||
LambdaFunctionStore store = accountAwareStore();
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, function("other-fn", OTHER_ACCOUNT));
|
||||
|
||||
assertTrue(store.list(REGION).isEmpty(),
|
||||
"the ambient scan must not see another account's function");
|
||||
List<LambdaFunction> all = store.listAllAccounts(REGION);
|
||||
assertEquals(1, all.size());
|
||||
assertEquals("other-fn", all.get(0).getFunctionName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAllAccountsKeepsTheRegionAndLatestFilter() {
|
||||
LambdaFunctionStore store = accountAwareStore();
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, function("latest-fn", OTHER_ACCOUNT));
|
||||
LambdaFunction published = function("latest-fn", OTHER_ACCOUNT);
|
||||
published.setVersion("1");
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, published);
|
||||
store.saveForAccount(OTHER_ACCOUNT, "eu-west-1", function("elsewhere-fn", OTHER_ACCOUNT));
|
||||
|
||||
List<LambdaFunction> all = store.listAllAccounts(REGION);
|
||||
|
||||
assertEquals(1, all.size(), "published versions and other regions must stay excluded");
|
||||
assertEquals("$LATEST", all.get(0).getVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveForAccountWritesIntoTheOwningPartitionNotTheAmbientOne() {
|
||||
LambdaFunctionStore store = accountAwareStore();
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, function("owned-fn", OTHER_ACCOUNT));
|
||||
|
||||
assertTrue(store.getForAccount(OTHER_ACCOUNT, REGION, "owned-fn").isPresent());
|
||||
assertTrue(store.get(REGION, "owned-fn").isEmpty(),
|
||||
"the ambient (default-account) partition must stay clean");
|
||||
}
|
||||
|
||||
@Test
|
||||
void listAllSeesEveryAccountSoRestartRehydrationCountsThemAll() {
|
||||
// The reserved-concurrency pool is per region and shared across accounts, so the
|
||||
// startup rehydration that feeds it has to see every account's functions or a restart
|
||||
// silently frees capacity that steady-state PutFunctionConcurrency had accounted for.
|
||||
LambdaFunctionStore store = accountAwareStore();
|
||||
store.saveForAccount(DEFAULT_ACCOUNT, REGION, function("default-fn", DEFAULT_ACCOUNT));
|
||||
store.saveForAccount(OTHER_ACCOUNT, REGION, function("other-fn", OTHER_ACCOUNT));
|
||||
|
||||
assertEquals(2, store.listAll().size());
|
||||
}
|
||||
|
||||
private LambdaFunctionStore accountAwareStore() {
|
||||
return new LambdaFunctionStore(AccountAwareStorageBackend.<LambdaFunction>inMemory(DEFAULT_ACCOUNT));
|
||||
}
|
||||
|
||||
private LambdaFunction function(String name, String accountId) {
|
||||
LambdaFunction fn = new LambdaFunction();
|
||||
fn.setFunctionName(name);
|
||||
fn.setAccountId(accountId);
|
||||
fn.setVersion("$LATEST");
|
||||
fn.setFunctionArn("arn:aws:lambda:" + REGION + ":" + accountId + ":function:" + name);
|
||||
return fn;
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package io.github.hectorvent.floci.services.lambda;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
/**
|
||||
* Wire-level test for {@code ListFunctionsByCodeSigningConfig}.
|
||||
*
|
||||
* <p>New class, not appended to {@code LambdaCodeSigningIntegrationTest} (which
|
||||
* uses ordered setUp/tearDown fixtures this operation doesn't need), so
|
||||
* falsifiability isolates per operation (CS-001).</p>
|
||||
*
|
||||
* <p>The identifier is validated even though Floci models no code-signing
|
||||
* configs: botocore models both {@code InvalidParameterValueException} and
|
||||
* {@code ResourceNotFoundException} for this operation, and the only resource
|
||||
* the ARN can name is a code-signing config. Since there is no
|
||||
* CreateCodeSigningConfig / PutFunctionCodeSigningConfig in this codebase, every
|
||||
* well-formed ARN necessarily names a config that does not exist, so the modeled
|
||||
* 404 — not a silent empty list — is the honest answer.</p>
|
||||
*/
|
||||
@QuarkusTest
|
||||
class LambdaListFunctionsByCodeSigningConfigConsumerTest {
|
||||
|
||||
/** Matches botocore's CodeSigningConfigArn pattern: csc- plus 17 lowercase alphanumerics. */
|
||||
private static final String WELL_FORMED_ARN =
|
||||
"arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0f6c334ab1234567c";
|
||||
|
||||
private static String path(String arn) {
|
||||
return "/2020-04-22/code-signing-configs/" + arn + "/functions";
|
||||
}
|
||||
|
||||
@Test
|
||||
void wellFormedButUnknownConfig_returnsResourceNotFound() {
|
||||
given()
|
||||
.when()
|
||||
.get(path(WELL_FORMED_ARN))
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The model's region alternation is {@code (eusc-)?[a-z]{2}((-gov)|(-iso([a-z]?)))?-[a-z]+-\d},
|
||||
* which admits the newer isolated partitions (iso-e/iso-f) and the European sovereign
|
||||
* cloud. A well-formed ARN in one of those must reach the modeled 404, not be rejected
|
||||
* as malformed.
|
||||
*/
|
||||
@Test
|
||||
void wellFormedIsolatedPartitionArn_returnsResourceNotFound() {
|
||||
given()
|
||||
.when()
|
||||
.get(path("arn:aws-iso-e:lambda:us-isoe-east-1:000000000000:"
|
||||
+ "code-signing-config:csc-0f6c334ab1234567c"))
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedArn_returnsInvalidParameterValue() {
|
||||
given()
|
||||
.when()
|
||||
.get(path("not-an-arn"))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shortSuffixArn_returnsInvalidParameterValue() {
|
||||
given()
|
||||
.when()
|
||||
.get(path("arn:aws:lambda:us-east-1:000000000000:code-signing-config:csc-0f6c334ab"))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxItemsBelowRange_returnsInvalidParameterValue() {
|
||||
given()
|
||||
.queryParam("MaxItems", 0)
|
||||
.when()
|
||||
.get(path(WELL_FORMED_ARN))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxItemsAboveRange_returnsInvalidParameterValue() {
|
||||
given()
|
||||
.queryParam("MaxItems", 10001)
|
||||
.when()
|
||||
.get(path(WELL_FORMED_ARN))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonNumericMaxItems_returnsInvalidParameterValue() {
|
||||
given()
|
||||
.queryParam("MaxItems", "many")
|
||||
.when()
|
||||
.get(path(WELL_FORMED_ARN))
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidParameterValueException"));
|
||||
}
|
||||
}
|
||||
@@ -222,6 +222,68 @@ class LambdaServiceTest {
|
||||
assertEquals(vpcConfig(), service.getFunction(REGION, "update-efs-vpc-function").getVpcConfig());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionConfigurationRejectsMalformedRoleArn() {
|
||||
service.createFunction(REGION, baseRequest("update-role-function"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.updateFunctionConfiguration(REGION, "update-role-function",
|
||||
Map.of("Role", "not-an-arn")));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertEquals("arn:aws:iam::000000000000:role/test-role",
|
||||
service.getFunction(REGION, "update-role-function").getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionConfigurationAcceptsValidRoleArn() {
|
||||
service.createFunction(REGION, baseRequest("update-role-valid-function"));
|
||||
|
||||
LambdaFunction updated = service.updateFunctionConfiguration(REGION, "update-role-valid-function",
|
||||
Map.of("Role", "arn:aws:iam::000000000000:role/new-role"));
|
||||
|
||||
assertEquals("arn:aws:iam::000000000000:role/new-role", updated.getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionConfigurationRejectsHandlerWithWhitespace() {
|
||||
service.createFunction(REGION, baseRequest("update-handler-function"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.updateFunctionConfiguration(REGION, "update-handler-function",
|
||||
Map.of("Handler", "index handler")));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertEquals("index.handler",
|
||||
service.getFunction(REGION, "update-handler-function").getHandler());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionConfigurationRejectsHandlerLongerThan128Chars() {
|
||||
service.createFunction(REGION, baseRequest("update-handler-length-function"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.updateFunctionConfiguration(REGION, "update-handler-length-function",
|
||||
Map.of("Handler", "h".repeat(129))));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFunctionConfigurationRejectsExplicitNullHandler() {
|
||||
service.createFunction(REGION, baseRequest("update-handler-null-function"));
|
||||
Map<String, Object> request = new java.util.HashMap<>();
|
||||
request.put("Handler", null);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> service.updateFunctionConfiguration(REGION, "update-handler-null-function", request));
|
||||
|
||||
assertEquals("InvalidParameterValueException", error.getErrorCode());
|
||||
assertEquals("index.handler",
|
||||
service.getFunction(REGION, "update-handler-null-function").getHandler(),
|
||||
"an explicit null must not silently clear the handler");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createFunctionFailsWhenMissingFunctionName() {
|
||||
Map<String, Object> req = baseRequest("x");
|
||||
@@ -885,4 +947,49 @@ class LambdaServiceTest {
|
||||
|
||||
assertEquals(expectedStatementIds, actualStatementIds);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishVersionWaitsForAConcurrentHolderOfTheFunctionsConcurrencyLock() throws Exception {
|
||||
// publishVersion reads codeLocalPath and persists a snapshot of it with no
|
||||
// synchronization against extractZipCodeBytes's own reclaim-the-legacy-directory
|
||||
// decision (which runs under this same per-function lock, e.g. from deleteFunction).
|
||||
// Without publishVersion also taking that lock, a version could be published in the
|
||||
// narrow window between that decision and the actual delete, persisting a snapshot
|
||||
// that references a directory which is about to be removed as "unused". Proving
|
||||
// publishVersion blocks on this lock closes that window regardless of the exact
|
||||
// interleaving, rather than relying on timing to catch it in the act.
|
||||
LambdaFunction fn = service.createFunction(REGION, baseRequest("lock-race-fn"));
|
||||
Object lock = service.lockForConcurrencyOp(fn.getFunctionArn());
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(1);
|
||||
CountDownLatch acquired = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Thread holder = new Thread(() -> {
|
||||
synchronized (lock) {
|
||||
acquired.countDown();
|
||||
try {
|
||||
release.await();
|
||||
} catch (InterruptedException ignored) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
});
|
||||
try {
|
||||
holder.start();
|
||||
assertTrue(acquired.await(2, java.util.concurrent.TimeUnit.SECONDS));
|
||||
|
||||
Future<LambdaFunction> publishFuture = pool.submit(
|
||||
() -> service.publishVersion(REGION, "lock-race-fn", null));
|
||||
assertThrows(java.util.concurrent.TimeoutException.class,
|
||||
() -> publishFuture.get(200, java.util.concurrent.TimeUnit.MILLISECONDS),
|
||||
"publishVersion must block while another operation holds this function's lock");
|
||||
|
||||
release.countDown();
|
||||
holder.join();
|
||||
assertNotNull(publishFuture.get(2, java.util.concurrent.TimeUnit.SECONDS));
|
||||
} finally {
|
||||
release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package io.github.hectorvent.floci.services.lambda.zip;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CodeStoreTest {
|
||||
|
||||
private static final String ACCOUNT_A = "111111111111";
|
||||
private static final String ACCOUNT_B = "222222222222";
|
||||
|
||||
@Test
|
||||
void sameFunctionNameInTwoAccountsResolvesToDistinctDirectories(@TempDir Path baseDir) {
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
|
||||
Path a = store.getCodePath(ACCOUNT_A, "shared-name");
|
||||
Path b = store.getCodePath(ACCOUNT_B, "shared-name");
|
||||
|
||||
assertNotEquals(a, b, "two accounts must not share one on-disk extraction directory");
|
||||
assertTrue(a.startsWith(baseDir.resolve(ACCOUNT_A)));
|
||||
assertTrue(b.startsWith(baseDir.resolve(ACCOUNT_B)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesOnlyTheOwningAccountsCode(@TempDir Path baseDir) throws IOException {
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
writeHandler(store.getCodePath(ACCOUNT_A, "shared-name"), "a");
|
||||
writeHandler(store.getCodePath(ACCOUNT_B, "shared-name"), "b");
|
||||
|
||||
store.delete(ACCOUNT_B, "shared-name");
|
||||
|
||||
assertTrue(store.exists(ACCOUNT_A, "shared-name"), "deleting B's code must not touch A's");
|
||||
assertFalse(store.exists(ACCOUNT_B, "shared-name"));
|
||||
assertEquals("a", Files.readString(store.getCodePath(ACCOUNT_A, "shared-name").resolve("index.js")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void accountSegmentIsSanitizedLikeTheFunctionName(@TempDir Path baseDir) {
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
|
||||
Path traversal = store.getCodePath("../../etc", "fn");
|
||||
|
||||
assertTrue(traversal.normalize().startsWith(baseDir.normalize()),
|
||||
"a hostile account segment must not escape the base directory");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareDotDotAccountSegmentCannotEscapeTheBaseDirectory(@TempDir Path baseDir) {
|
||||
// "../../etc" contains "/", which sanitizeName replaces with "_", neutralizing it as a
|
||||
// single segment. A segment that is EXACTLY ".." consists entirely of otherwise-allowed
|
||||
// characters (dots), so it survives that replacement untouched and still resolves to the
|
||||
// parent directory once handed to Path.resolve.
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
|
||||
Path traversal = store.getCodePath("..", "fn");
|
||||
|
||||
assertTrue(traversal.normalize().startsWith(baseDir.normalize()),
|
||||
"a bare '..' account segment must not escape the base directory");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareDotFunctionSegmentCannotResolveToTheAccountDirectoryItself(@TempDir Path baseDir) {
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
|
||||
Path traversal = store.getCodePath(ACCOUNT_A, ".");
|
||||
|
||||
assertTrue(traversal.normalize().startsWith(baseDir.normalize()));
|
||||
assertNotEquals(baseDir.resolve(ACCOUNT_A).normalize(), traversal.normalize(),
|
||||
"a bare '.' function segment must not collapse to the account directory itself");
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDoesNotTouchAPreAccountScopedLegacyDirectory(@TempDir Path baseDir) throws IOException {
|
||||
// The pre-account-scoped layout gave every account's same-named function the exact same
|
||||
// directory, so CodeStore itself cannot safely know whether another account's function
|
||||
// still depends on it. That decision belongs to the caller (LambdaService, which can
|
||||
// check every account's persisted functions) via the separate deleteLegacy() below -
|
||||
// delete() must only ever touch its own account-scoped path.
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
Path legacyPath = baseDir.resolve("legacy-fn");
|
||||
writeHandler(legacyPath, "legacy");
|
||||
writeHandler(store.getCodePath(ACCOUNT_A, "legacy-fn"), "current");
|
||||
|
||||
store.delete(ACCOUNT_A, "legacy-fn");
|
||||
|
||||
assertTrue(Files.exists(legacyPath), "delete() must not unilaterally remove the legacy directory");
|
||||
assertFalse(store.exists(ACCOUNT_A, "legacy-fn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteLegacyRemovesThePreAccountScopedDirectory(@TempDir Path baseDir) throws IOException {
|
||||
CodeStore store = new CodeStore(baseDir);
|
||||
Path legacyPath = store.getLegacyCodePath("legacy-fn");
|
||||
writeHandler(legacyPath, "legacy");
|
||||
|
||||
store.deleteLegacy("legacy-fn");
|
||||
|
||||
assertFalse(Files.exists(legacyPath));
|
||||
}
|
||||
|
||||
private void writeHandler(Path codePath, String content) throws IOException {
|
||||
Files.createDirectories(codePath);
|
||||
Files.writeString(codePath.resolve("index.js"), content);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user