diff --git a/compatibility-tests/sdk-test-node/tests/lambda-layers.test.ts b/compatibility-tests/sdk-test-node/tests/lambda-layers.test.ts new file mode 100644 index 0000000000..4b35d0a2f7 --- /dev/null +++ b/compatibility-tests/sdk-test-node/tests/lambda-layers.test.ts @@ -0,0 +1,251 @@ +/** + * Lambda Layers compatibility tests. + * + * Verifies that the real @aws-sdk/client-lambda can round-trip through + * Floci's layer endpoints without wire-format issues. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { + LambdaClient, + PublishLayerVersionCommand, + GetLayerVersionCommand, + ListLayerVersionsCommand, + ListLayersCommand, + DeleteLayerVersionCommand, + CreateFunctionCommand, + GetFunctionConfigurationCommand, + UpdateFunctionConfigurationCommand, + DeleteFunctionCommand, +} from '@aws-sdk/client-lambda'; +import { makeClient, uniqueName, ACCOUNT, buildMinimalZip } from './setup'; + +describe('Lambda Layers', () => { + let lambda: LambdaClient; + let layerName: string; + let layerArn: string; + let layerVersionArn1: string; + let layerVersionArn2: string; + + beforeAll(() => { + lambda = makeClient(LambdaClient); + layerName = `compat-layer-${uniqueName()}`; + }); + + afterAll(async () => { + // Clean up any remaining layer versions + try { + await lambda.send(new DeleteLayerVersionCommand({ LayerName: layerName, VersionNumber: 1 })); + } catch { /* ignore */ } + try { + await lambda.send(new DeleteLayerVersionCommand({ LayerName: layerName, VersionNumber: 2 })); + } catch { /* ignore */ } + }); + + it('should publish layer version 1', async () => { + const layerContent = Buffer.from('module.exports.util = () => "v1";'); + const zipBuffer = buildMinimalZip('nodejs/node_modules/shared/index.js', layerContent); + + const response = await lambda.send( + new PublishLayerVersionCommand({ + LayerName: layerName, + Content: { ZipFile: zipBuffer }, + CompatibleRuntimes: ['nodejs20.x', 'nodejs22.x'], + CompatibleArchitectures: ['x86_64'], + Description: 'Shared utilities v1', + LicenseInfo: 'MIT', + }) + ); + + expect(response.Version).toBe(1); + expect(response.LayerArn).toContain(`:layer:${layerName}`); + expect(response.LayerVersionArn).toContain(`:layer:${layerName}:1`); + expect(response.Description).toBe('Shared utilities v1'); + expect(response.LicenseInfo).toBe('MIT'); + expect(response.CompatibleRuntimes).toContain('nodejs20.x'); + expect(response.CompatibleRuntimes).toContain('nodejs22.x'); + expect(response.CompatibleArchitectures).toContain('x86_64'); + expect(response.Content?.CodeSize).toBeGreaterThan(0); + expect(response.Content?.CodeSha256).toBeTruthy(); + expect(response.CreatedDate).toBeTruthy(); + + layerArn = response.LayerArn!; + layerVersionArn1 = response.LayerVersionArn!; + }); + + it('should publish layer version 2', async () => { + const layerContent = Buffer.from('module.exports.util = () => "v2";'); + const zipBuffer = buildMinimalZip('nodejs/node_modules/shared/index.js', layerContent); + + const response = await lambda.send( + new PublishLayerVersionCommand({ + LayerName: layerName, + Content: { ZipFile: zipBuffer }, + CompatibleRuntimes: ['nodejs22.x'], + Description: 'Shared utilities v2', + }) + ); + + expect(response.Version).toBe(2); + expect(response.LayerVersionArn).toContain(`:layer:${layerName}:2`); + expect(response.Description).toBe('Shared utilities v2'); + + layerVersionArn2 = response.LayerVersionArn!; + }); + + it('should get layer version 1', async () => { + const response = await lambda.send( + new GetLayerVersionCommand({ + LayerName: layerName, + VersionNumber: 1, + }) + ); + + expect(response.Version).toBe(1); + expect(response.LayerArn).toBe(layerArn); + expect(response.LayerVersionArn).toBe(layerVersionArn1); + expect(response.Description).toBe('Shared utilities v1'); + expect(response.Content?.CodeSha256).toBeTruthy(); + expect(response.Content?.CodeSize).toBeGreaterThan(0); + }); + + it('should fail to get non-existent layer version', async () => { + await expect( + lambda.send(new GetLayerVersionCommand({ LayerName: layerName, VersionNumber: 99 })) + ).rejects.toThrow(); + }); + + it('should list layer versions', async () => { + const response = await lambda.send( + new ListLayerVersionsCommand({ LayerName: layerName }) + ); + + expect(response.LayerVersions).toHaveLength(2); + expect(response.LayerVersions![0].Version).toBe(1); + expect(response.LayerVersions![1].Version).toBe(2); + }); + + it('should list layers and include our layer', async () => { + const response = await lambda.send(new ListLayersCommand({})); + + const ourLayer = response.Layers?.find((l) => l.LayerName === layerName); + expect(ourLayer).toBeDefined(); + expect(ourLayer!.LayerArn).toBe(layerArn); + expect(ourLayer!.LatestMatchingVersion?.Version).toBe(2); + }); + + it('should delete layer version 1', async () => { + // DeleteLayerVersion returns nothing on success (204) + await lambda.send( + new DeleteLayerVersionCommand({ LayerName: layerName, VersionNumber: 1 }) + ); + + // Verify it's gone + await expect( + lambda.send(new GetLayerVersionCommand({ LayerName: layerName, VersionNumber: 1 })) + ).rejects.toThrow(); + }); + + it('should list layer versions after deletion', async () => { + const response = await lambda.send( + new ListLayerVersionsCommand({ LayerName: layerName }) + ); + + expect(response.LayerVersions).toHaveLength(1); + expect(response.LayerVersions![0].Version).toBe(2); + }); + + it('should handle delete of non-existent version gracefully', async () => { + // AWS returns 204 even for non-existent versions + await lambda.send( + new DeleteLayerVersionCommand({ LayerName: layerName, VersionNumber: 99 }) + ); + }); +}); + +describe('Lambda Layer Attachment', () => { + let lambda: LambdaClient; + let layerName: string; + let layerVersionArn: string; + let fnName: string; + + beforeAll(async () => { + lambda = makeClient(LambdaClient); + layerName = `attach-layer-${uniqueName()}`; + fnName = `layer-fn-${uniqueName()}`; + + // Publish a layer to attach + const layerContent = Buffer.from('module.exports.dep = () => "shared";'); + const zipBuffer = buildMinimalZip('nodejs/node_modules/dep/index.js', layerContent); + + const layerResp = await lambda.send( + new PublishLayerVersionCommand({ + LayerName: layerName, + Content: { ZipFile: zipBuffer }, + CompatibleRuntimes: ['nodejs20.x'], + }) + ); + layerVersionArn = layerResp.LayerVersionArn!; + }); + + afterAll(async () => { + try { + await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName })); + } catch { /* ignore */ } + try { + await lambda.send(new DeleteLayerVersionCommand({ LayerName: layerName, VersionNumber: 1 })); + } catch { /* ignore */ } + }); + + it('should create function with layer attached', async () => { + const handlerCode = "exports.handler = async () => ({ statusCode: 200 });"; + const zipBuffer = buildMinimalZip('index.js', Buffer.from(handlerCode)); + + const response = await lambda.send( + new CreateFunctionCommand({ + FunctionName: fnName, + Runtime: 'nodejs20.x', + Role: `arn:aws:iam::${ACCOUNT}:role/lambda-role`, + Handler: 'index.handler', + Code: { ZipFile: zipBuffer }, + Layers: [layerVersionArn], + }) + ); + + expect(response.Layers).toHaveLength(1); + expect(response.Layers![0].Arn).toBe(layerVersionArn); + }); + + it('should show layers in function configuration', async () => { + const response = await lambda.send( + new GetFunctionConfigurationCommand({ FunctionName: fnName }) + ); + + expect(response.Layers).toHaveLength(1); + expect(response.Layers![0].Arn).toBe(layerVersionArn); + }); + + it('should update function to remove layers', async () => { + const response = await lambda.send( + new UpdateFunctionConfigurationCommand({ + FunctionName: fnName, + Layers: [], + }) + ); + + // After removing layers, the field should be empty or absent + expect(response.Layers ?? []).toHaveLength(0); + }); + + it('should update function to add layers back', async () => { + const response = await lambda.send( + new UpdateFunctionConfigurationCommand({ + FunctionName: fnName, + Layers: [layerVersionArn], + }) + ); + + expect(response.Layers).toHaveLength(1); + expect(response.Layers![0].Arn).toBe(layerVersionArn); + }); +}); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.java index d13b1326ec..d7609cbec0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerController.java @@ -1,21 +1,34 @@ package io.github.hectorvent.floci.services.lambda; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; +import java.util.List; +import java.util.Map; + /** - * Lambda layer endpoints — use the /2018-10-31 API version prefix. + * Lambda layer endpoints — uses the /2018-10-31 API version prefix. * - * ListLayers: GET /2018-10-31/layers - * ListLayerVersions: GET /2018-10-31/layers/{LayerName}/versions + * PublishLayerVersion: POST /2018-10-31/layers/{LayerName}/versions + * ListLayerVersions: GET /2018-10-31/layers/{LayerName}/versions + * GetLayerVersion: GET /2018-10-31/layers/{LayerName}/versions/{VersionNumber} + * DeleteLayerVersion: DELETE /2018-10-31/layers/{LayerName}/versions/{VersionNumber} + * ListLayers: GET /2018-10-31/layers */ @Path("/2018-10-31") @Produces(MediaType.APPLICATION_JSON) @@ -23,25 +36,134 @@ import jakarta.ws.rs.core.Response; public class LambdaLayerController { private final ObjectMapper objectMapper; + private final LambdaLayerService layerService; + private final RegionResolver regionResolver; @Inject - public LambdaLayerController(ObjectMapper objectMapper) { + public LambdaLayerController(ObjectMapper objectMapper, + LambdaLayerService layerService, + RegionResolver regionResolver) { this.objectMapper = objectMapper; + this.layerService = layerService; + this.regionResolver = regionResolver; } - @GET - @Path("/layers") - public Response listLayers() { - ObjectNode root = objectMapper.createObjectNode(); - root.putArray("Layers"); - return Response.ok(root).build(); + @POST + @Path("/layers/{layerName}/versions") + public Response publishLayerVersion(@PathParam("layerName") String layerName, + @Context HttpHeaders headers, + Map request) { + String region = regionResolver.resolveRegion(headers); + LambdaLayerVersion lv = layerService.publishLayerVersion(region, layerName, request); + return Response.status(201).entity(buildLayerVersionResponse(lv)).build(); } @GET @Path("/layers/{layerName}/versions") - public Response listLayerVersions(@PathParam("layerName") String layerName) { + public Response listLayerVersions(@PathParam("layerName") String layerName, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + List versions = layerService.listLayerVersions(region, layerName); ObjectNode root = objectMapper.createObjectNode(); - root.putArray("LayerVersions"); + ArrayNode arr = root.putArray("LayerVersions"); + for (LambdaLayerVersion lv : versions) { + arr.add(buildLayerVersionSummary(lv)); + } return Response.ok(root).build(); } + + @GET + @Path("/layers/{layerName}/versions/{versionNumber}") + public Response getLayerVersion(@PathParam("layerName") String layerName, + @PathParam("versionNumber") long versionNumber, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + LambdaLayerVersion lv = layerService.getLayerVersion(region, layerName, versionNumber); + return Response.ok(buildLayerVersionResponse(lv)).build(); + } + + @DELETE + @Path("/layers/{layerName}/versions/{versionNumber}") + public Response deleteLayerVersion(@PathParam("layerName") String layerName, + @PathParam("versionNumber") long versionNumber, + @Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + layerService.deleteLayerVersion(region, layerName, versionNumber); + return Response.noContent().build(); + } + + @GET + @Path("/layers") + public Response listLayers(@Context HttpHeaders headers) { + String region = regionResolver.resolveRegion(headers); + List layers = layerService.listLayers(region); + ObjectNode root = objectMapper.createObjectNode(); + ArrayNode arr = root.putArray("Layers"); + for (LambdaLayerVersion lv : layers) { + ObjectNode layerNode = objectMapper.createObjectNode(); + layerNode.put("LayerName", lv.getLayerName()); + layerNode.put("LayerArn", lv.getLayerArn()); + ObjectNode latestVersion = layerNode.putObject("LatestMatchingVersion"); + latestVersion.put("LayerVersionArn", lv.getLayerVersionArn()); + latestVersion.put("Version", lv.getVersion()); + latestVersion.put("Description", lv.getDescription() != null ? lv.getDescription() : ""); + latestVersion.put("CreatedDate", lv.getCreatedDate()); + latestVersion.put("LicenseInfo", lv.getLicenseInfo() != null ? lv.getLicenseInfo() : ""); + if (lv.getCompatibleRuntimes() != null && !lv.getCompatibleRuntimes().isEmpty()) { + ArrayNode runtimes = latestVersion.putArray("CompatibleRuntimes"); + lv.getCompatibleRuntimes().forEach(runtimes::add); + } + if (lv.getCompatibleArchitectures() != null && !lv.getCompatibleArchitectures().isEmpty()) { + ArrayNode archs = latestVersion.putArray("CompatibleArchitectures"); + lv.getCompatibleArchitectures().forEach(archs::add); + } + arr.add(layerNode); + } + return Response.ok(root).build(); + } + + private ObjectNode buildLayerVersionResponse(LambdaLayerVersion lv) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("LayerArn", lv.getLayerArn()); + node.put("LayerVersionArn", lv.getLayerVersionArn()); + node.put("Version", lv.getVersion()); + node.put("Description", lv.getDescription() != null ? lv.getDescription() : ""); + node.put("CreatedDate", lv.getCreatedDate()); + node.put("LicenseInfo", lv.getLicenseInfo() != null ? lv.getLicenseInfo() : ""); + + // Content block + ObjectNode contentNode = node.putObject("Content"); + contentNode.put("CodeSha256", lv.getCodeSha256() != null ? lv.getCodeSha256() : ""); + contentNode.put("CodeSize", lv.getCodeSizeBytes()); + // Location is a presigned URL in real AWS; we provide a placeholder + contentNode.put("Location", ""); + + if (lv.getCompatibleRuntimes() != null && !lv.getCompatibleRuntimes().isEmpty()) { + ArrayNode runtimes = node.putArray("CompatibleRuntimes"); + lv.getCompatibleRuntimes().forEach(runtimes::add); + } + if (lv.getCompatibleArchitectures() != null && !lv.getCompatibleArchitectures().isEmpty()) { + ArrayNode archs = node.putArray("CompatibleArchitectures"); + lv.getCompatibleArchitectures().forEach(archs::add); + } + return node; + } + + private ObjectNode buildLayerVersionSummary(LambdaLayerVersion lv) { + ObjectNode node = objectMapper.createObjectNode(); + node.put("LayerVersionArn", lv.getLayerVersionArn()); + node.put("Version", lv.getVersion()); + node.put("Description", lv.getDescription() != null ? lv.getDescription() : ""); + node.put("CreatedDate", lv.getCreatedDate()); + node.put("LicenseInfo", lv.getLicenseInfo() != null ? lv.getLicenseInfo() : ""); + if (lv.getCompatibleRuntimes() != null && !lv.getCompatibleRuntimes().isEmpty()) { + ArrayNode runtimes = node.putArray("CompatibleRuntimes"); + lv.getCompatibleRuntimes().forEach(runtimes::add); + } + if (lv.getCompatibleArchitectures() != null && !lv.getCompatibleArchitectures().isEmpty()) { + ArrayNode archs = node.putArray("CompatibleArchitectures"); + lv.getCompatibleArchitectures().forEach(archs::add); + } + return node; + } } diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java new file mode 100644 index 0000000000..50be32ad34 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerService.java @@ -0,0 +1,243 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion; +import io.github.hectorvent.floci.services.lambda.zip.ZipExtractor; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.s3.model.S3Object; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +/** + * Business logic for Lambda Layer management. + */ +@ApplicationScoped +public class LambdaLayerService { + + private static final Logger LOG = Logger.getLogger(LambdaLayerService.class); + + private final LambdaLayerStore layerStore; + private final ZipExtractor zipExtractor; + private final EmulatorConfig config; + private final RegionResolver regionResolver; + private final S3Service s3Service; + + @Inject + public LambdaLayerService(LambdaLayerStore layerStore, + ZipExtractor zipExtractor, + EmulatorConfig config, + RegionResolver regionResolver, + S3Service s3Service) { + this.layerStore = layerStore; + this.zipExtractor = zipExtractor; + this.config = config; + this.regionResolver = regionResolver; + this.s3Service = s3Service; + } + + /** + * Publishes a new layer version. Each call with the same layer name creates a new version. + */ + @SuppressWarnings("unchecked") + public LambdaLayerVersion publishLayerVersion(String region, String layerName, Map request) { + if (layerName == null || layerName.isBlank()) { + throw new AwsException("InvalidParameterValueException", "LayerName is required", 400); + } + + Map content = (Map) request.get("Content"); + if (content == null) { + throw new AwsException("InvalidParameterValueException", "Content is required", 400); + } + + String description = (String) request.get("Description"); + String licenseInfo = (String) request.get("LicenseInfo"); + + List compatibleRuntimes = request.get("CompatibleRuntimes") instanceof List + ? (List) request.get("CompatibleRuntimes") : null; + List compatibleArchitectures = request.get("CompatibleArchitectures") instanceof List + ? (List) request.get("CompatibleArchitectures") : null; + + // Resolve the zip content + byte[] zipBytes = resolveLayerContent(content); + + // Determine the next version number + long nextVersion = layerStore.getLatestVersion(region, layerName) + 1; + + // Extract the layer zip to disk + Path layerPath = getLayerCodePath(layerName, nextVersion); + try { + zipExtractor.extractTo(zipBytes, layerPath); + } catch (IOException e) { + throw new AwsException("InvalidParameterValueException", + "Failed to extract layer archive: " + e.getMessage(), 400); + } + + // Compute SHA-256 + String codeSha256 = computeSha256(zipBytes); + + // Build the layer version + String accountId = regionResolver.getAccountId(); + String layerArn = String.format("arn:aws:lambda:%s:%s:layer:%s", region, accountId, layerName); + String layerVersionArn = layerArn + ":" + nextVersion; + + LambdaLayerVersion layerVersion = new LambdaLayerVersion(); + layerVersion.setLayerName(layerName); + layerVersion.setLayerArn(layerArn); + layerVersion.setLayerVersionArn(layerVersionArn); + layerVersion.setVersion(nextVersion); + layerVersion.setDescription(description); + layerVersion.setLicenseInfo(licenseInfo); + layerVersion.setCompatibleRuntimes(compatibleRuntimes != null ? new ArrayList<>(compatibleRuntimes) : null); + layerVersion.setCompatibleArchitectures(compatibleArchitectures != null ? new ArrayList<>(compatibleArchitectures) : null); + layerVersion.setCreatedDate(DateTimeFormatter.ISO_INSTANT.format(Instant.now().atOffset(ZoneOffset.UTC))); + layerVersion.setCodeSizeBytes(zipBytes.length); + layerVersion.setCodeSha256(codeSha256); + layerVersion.setCodeLocalPath(layerPath.toAbsolutePath().normalize().toString()); + + layerStore.save(region, layerVersion); + LOG.infov("Published layer version: {0} v{1} in region {2}", layerName, nextVersion, region); + return layerVersion; + } + + /** + * Returns information about a specific layer version. + */ + public LambdaLayerVersion getLayerVersion(String region, String layerName, long versionNumber) { + return layerStore.get(region, layerName, versionNumber) + .orElseThrow(() -> new AwsException("ResourceNotFoundException", + "Layer version " + versionNumber + " for layer " + layerName + " not found.", 404)); + } + + /** + * Lists all versions of a layer. + */ + public List listLayerVersions(String region, String layerName) { + return layerStore.listVersions(region, layerName); + } + + /** + * Lists all layers in a region (returns the latest version of each). + */ + public List listLayers(String region) { + return layerStore.listLayers(region); + } + + /** + * Deletes a specific layer version. + */ + public void deleteLayerVersion(String region, String layerName, long versionNumber) { + LambdaLayerVersion lv = layerStore.get(region, layerName, versionNumber).orElse(null); + if (lv == null) { + // AWS returns 204 even if the layer version doesn't exist + return; + } + + // Delete the extracted code from disk + if (lv.getCodeLocalPath() != null) { + Path codePath = Path.of(lv.getCodeLocalPath()); + deleteDirectory(codePath); + } + + layerStore.delete(region, layerName, versionNumber); + LOG.infov("Deleted layer version: {0} v{1} in region {2}", layerName, versionNumber, region); + } + + /** + * Resolves a layer version ARN to its local code path. + * Used by the container launcher to copy layer content into /opt. + */ + public LambdaLayerVersion resolveLayerByArn(String layerVersionArn) { + // ARN format: arn:aws:lambda:{region}:{account}:layer:{name}:{version} + String[] parts = layerVersionArn.split(":"); + if (parts.length < 8) { + return null; + } + String region = parts[3]; + String layerName = parts[6]; + long version; + try { + version = Long.parseLong(parts[7]); + } catch (NumberFormatException e) { + return null; + } + return layerStore.get(region, layerName, version).orElse(null); + } + + private byte[] resolveLayerContent(Map content) { + String zipFileBase64 = (String) content.get("ZipFile"); + if (zipFileBase64 != null) { + return Base64.getDecoder().decode(zipFileBase64); + } + + String s3Bucket = (String) content.get("S3Bucket"); + String s3Key = (String) content.get("S3Key"); + if (s3Bucket != null && s3Key != null) { + if (s3Service == null) { + throw new AwsException("ServiceUnavailableException", "S3 service not available", 503); + } + try { + S3Object obj = s3Service.getObject(s3Bucket, s3Key); + return obj.getData(); + } catch (Exception e) { + throw new AwsException("InvalidParameterValueException", + "Unable to fetch layer content from s3://" + s3Bucket + "/" + s3Key + ": " + e.getMessage(), 400); + } + } + + throw new AwsException("InvalidParameterValueException", + "Layer content must include either ZipFile or S3Bucket/S3Key", 400); + } + + private Path getLayerCodePath(String layerName, long version) { + String sanitized = layerName.replaceAll("[^a-zA-Z0-9_\\-.]", "_"); + return Path.of(config.services().lambda().codePath()) + .resolve("layers") + .resolve(sanitized) + .resolve(String.valueOf(version)); + } + + private String computeSha256(byte[] data) { + try { + byte[] digest = MessageDigest.getInstance("SHA-256").digest(data); + return Base64.getEncoder().encodeToString(digest); + } catch (NoSuchAlgorithmException e) { + return ""; + } + } + + private void deleteDirectory(Path dir) { + if (!Files.exists(dir)) { + return; + } + try { + Files.walk(dir) + .sorted(Comparator.reverseOrder()) + .forEach(p -> { + try { + Files.delete(p); + } catch (IOException e) { + LOG.warnv("Failed to delete {0}: {1}", p, e.getMessage()); + } + }); + } catch (IOException e) { + LOG.warnv("Failed to delete layer directory {0}: {1}", dir, e.getMessage()); + } + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerStore.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerStore.java new file mode 100644 index 0000000000..cb38cfd8fe --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaLayerStore.java @@ -0,0 +1,92 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.github.hectorvent.floci.core.storage.StorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion; +import com.fasterxml.jackson.core.type.TypeReference; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Wraps the storage backend for Lambda Layer Versions. + * Keys follow the pattern: layer::{region}::{layerName}::{version} + */ +@ApplicationScoped +public class LambdaLayerStore { + + private final StorageBackend backend; + + @Inject + public LambdaLayerStore(StorageFactory storageFactory) { + this.backend = storageFactory.create("lambda", "lambda-layers.json", + new TypeReference>() {}); + } + + LambdaLayerStore(StorageBackend backend) { + this.backend = backend; + } + + public void save(String region, LambdaLayerVersion layerVersion) { + backend.put(key(region, layerVersion.getLayerName(), layerVersion.getVersion()), layerVersion); + } + + public Optional get(String region, String layerName, long version) { + return backend.get(key(region, layerName, version)); + } + + /** + * Returns all versions of a given layer in a region, sorted by version ascending. + */ + public List listVersions(String region, String layerName) { + String prefix = "layer::" + region + "::" + layerName + "::"; + return backend.scan(k -> k.startsWith(prefix)).stream() + .sorted((a, b) -> Long.compare(a.getVersion(), b.getVersion())) + .toList(); + } + + /** + * Returns the latest version number for a layer, or 0 if no versions exist. + */ + public long getLatestVersion(String region, String layerName) { + return listVersions(region, layerName).stream() + .mapToLong(LambdaLayerVersion::getVersion) + .max() + .orElse(0); + } + + /** + * Returns all distinct layers in a region (latest version of each). + */ + public List listLayers(String region) { + String prefix = "layer::" + region + "::"; + List all = backend.scan(k -> k.startsWith(prefix)); + // Group by layer name and return the latest version of each + return all.stream() + .collect(java.util.stream.Collectors.groupingBy(LambdaLayerVersion::getLayerName)) + .values().stream() + .map(versions -> versions.stream() + .max((a, b) -> Long.compare(a.getVersion(), b.getVersion())) + .orElseThrow()) + .toList(); + } + + public void delete(String region, String layerName, long version) { + backend.delete(key(region, layerName, version)); + } + + /** + * Deletes all versions of a layer. + */ + public void deleteAll(String region, String layerName) { + listVersions(region, layerName).forEach(lv -> + backend.delete(key(region, lv.getLayerName(), lv.getVersion()))); + } + + private static String key(String region, String layerName, long version) { + return "layer::" + region + "::" + layerName + "::" + version; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java index 16c49b2864..104c873ffb 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java @@ -8,8 +8,10 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; import io.github.hectorvent.floci.core.common.docker.ContainerSpec; import io.github.hectorvent.floci.core.common.docker.DockerHostResolver; import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager; +import io.github.hectorvent.floci.services.lambda.LambdaLayerService; import io.github.hectorvent.floci.services.lambda.model.ContainerState; import io.github.hectorvent.floci.services.lambda.model.LambdaFunction; +import io.github.hectorvent.floci.services.lambda.model.LambdaLayerVersion; import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServer; import io.github.hectorvent.floci.services.lambda.runtime.RuntimeApiServerFactory; import com.github.dockerjava.api.DockerClient; @@ -60,6 +62,7 @@ public class ContainerLauncher { private final EmulatorConfig config; private final EcrRegistryManager ecrRegistryManager; private final EmbeddedDnsServer embeddedDnsServer; + private final LambdaLayerService layerService; /** Matches an AWS-shaped ECR image URI: {@code .dkr.ecr..amazonaws.com/[:tag]}. */ private static final java.util.regex.Pattern AWS_ECR_URI = @@ -74,7 +77,8 @@ public class ContainerLauncher { DockerHostResolver dockerHostResolver, EmulatorConfig config, EcrRegistryManager ecrRegistryManager, - EmbeddedDnsServer embeddedDnsServer) { + EmbeddedDnsServer embeddedDnsServer, + LambdaLayerService layerService) { this.containerBuilder = containerBuilder; this.lifecycleManager = lifecycleManager; this.logStreamer = logStreamer; @@ -84,6 +88,7 @@ public class ContainerLauncher { this.config = config; this.ecrRegistryManager = ecrRegistryManager; this.embeddedDnsServer = embeddedDnsServer; + this.layerService = layerService; } /** @@ -262,6 +267,24 @@ public class ContainerLauncher { } } + // 3. Copy layer contents into /opt (layers are merged in order) + if (fn.getLayers() != null && !fn.getLayers().isEmpty()) { + for (String layerArn : fn.getLayers()) { + LambdaLayerVersion layer = layerService.resolveLayerByArn(layerArn); + if (layer != null && layer.getCodeLocalPath() != null) { + Path layerPath = Path.of(layer.getCodeLocalPath()); + if (Files.exists(layerPath)) { + copyDirToContainer(dockerClient, containerId, layerPath, "/opt", fn.getFunctionName()); + LOG.debugv("Copied layer {0} into container {1} at /opt", layerArn, containerId); + } else { + LOG.warnv("Layer code path not found for {0}: {1}", layerArn, layer.getCodeLocalPath()); + } + } else { + LOG.warnv("Could not resolve layer ARN: {0} for function {1}", layerArn, fn.getFunctionName()); + } + } + } + // Now start the container with code in place lifecycleManager.startCreated(containerId, spec); diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaLayerVersion.java b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaLayerVersion.java new file mode 100644 index 0000000000..c288c6de92 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/model/LambdaLayerVersion.java @@ -0,0 +1,66 @@ +package io.github.hectorvent.floci.services.lambda.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.List; + +/** + * Represents a single published version of a Lambda layer. + */ +@RegisterForReflection +@JsonIgnoreProperties(ignoreUnknown = true) +public class LambdaLayerVersion { + + private String layerName; + private String layerArn; + private String layerVersionArn; + private long version; + private String description; + private String licenseInfo; + private List compatibleRuntimes; + private List compatibleArchitectures; + private String createdDate; + private long codeSizeBytes; + private String codeSha256; + private String codeLocalPath; + + public LambdaLayerVersion() { + } + + public String getLayerName() { return layerName; } + public void setLayerName(String layerName) { this.layerName = layerName; } + + public String getLayerArn() { return layerArn; } + public void setLayerArn(String layerArn) { this.layerArn = layerArn; } + + public String getLayerVersionArn() { return layerVersionArn; } + public void setLayerVersionArn(String layerVersionArn) { this.layerVersionArn = layerVersionArn; } + + public long getVersion() { return version; } + public void setVersion(long version) { this.version = version; } + + public String getDescription() { return description; } + public void setDescription(String description) { this.description = description; } + + public String getLicenseInfo() { return licenseInfo; } + public void setLicenseInfo(String licenseInfo) { this.licenseInfo = licenseInfo; } + + public List getCompatibleRuntimes() { return compatibleRuntimes; } + public void setCompatibleRuntimes(List compatibleRuntimes) { this.compatibleRuntimes = compatibleRuntimes; } + + public List getCompatibleArchitectures() { return compatibleArchitectures; } + public void setCompatibleArchitectures(List compatibleArchitectures) { this.compatibleArchitectures = compatibleArchitectures; } + + public String getCreatedDate() { return createdDate; } + public void setCreatedDate(String createdDate) { this.createdDate = createdDate; } + + public long getCodeSizeBytes() { return codeSizeBytes; } + public void setCodeSizeBytes(long codeSizeBytes) { this.codeSizeBytes = codeSizeBytes; } + + public String getCodeSha256() { return codeSha256; } + public void setCodeSha256(String codeSha256) { this.codeSha256 = codeSha256; } + + public String getCodeLocalPath() { return codeLocalPath; } + public void setCodeLocalPath(String codeLocalPath) { this.codeLocalPath = codeLocalPath; } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java index 8ae74c6a30..a35756ca49 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaImageConfigTest.java @@ -242,7 +242,8 @@ class LambdaImageConfigTest { ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer); launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver, - runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, embeddedDnsServer); + runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, embeddedDnsServer, + mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class)); when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer); when(runtimeApiServer.getPort()).thenReturn(9000); diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java new file mode 100644 index 0000000000..7c74dc9777 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaLayerIntegrationTest.java @@ -0,0 +1,346 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.ByteArrayOutputStream; +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.*; + +/** + * Integration tests for Lambda Layer lifecycle: + * PublishLayerVersion, GetLayerVersion, ListLayerVersions, ListLayers, DeleteLayerVersion. + * Also verifies layer attachment on CreateFunction and UpdateFunctionConfiguration. + */ +@QuarkusTest +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class LambdaLayerIntegrationTest { + + private static final String LAYER_NAME = "test-layer"; + private static final String FN_NAME = "layer-test-fn"; + + // ── helpers ─────────────────────────────────────────────────────────────── + + private static String layerZipBase64() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + zos.putNextEntry(new ZipEntry("nodejs/node_modules/my-lib/index.js")); + zos.write("module.exports = { hello: () => 'world' };".getBytes()); + zos.closeEntry(); + } + return Base64.getEncoder().encodeToString(baos.toByteArray()); + } + + private static String functionZipBase64() throws Exception { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + try (ZipOutputStream zos = new ZipOutputStream(baos)) { + zos.putNextEntry(new ZipEntry("index.js")); + zos.write("exports.handler = async () => ({ statusCode: 200 });".getBytes()); + zos.closeEntry(); + } + return Base64.getEncoder().encodeToString(baos.toByteArray()); + } + + // ── PublishLayerVersion ─────────────────────────────────────────────────── + + @Test + @Order(1) + void publishLayerVersion_createsVersion1() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "Content": { "ZipFile": "%s" }, + "CompatibleRuntimes": ["nodejs20.x", "nodejs22.x"], + "CompatibleArchitectures": ["x86_64"], + "Description": "Shared utilities v1", + "LicenseInfo": "MIT" + } + """.formatted(layerZipBase64())) + .when() + .post("/2018-10-31/layers/" + LAYER_NAME + "/versions") + .then() + .statusCode(201) + .body("Version", equalTo(1)) + .body("LayerArn", containsString(":layer:" + LAYER_NAME)) + .body("LayerVersionArn", containsString(":layer:" + LAYER_NAME + ":1")) + .body("Description", equalTo("Shared utilities v1")) + .body("LicenseInfo", equalTo("MIT")) + .body("CompatibleRuntimes", hasItems("nodejs20.x", "nodejs22.x")) + .body("CompatibleArchitectures", hasItem("x86_64")) + .body("Content.CodeSize", greaterThan(0)) + .body("Content.CodeSha256", not(emptyString())) + .body("CreatedDate", not(emptyString())); + } + + @Test + @Order(2) + void publishLayerVersion_createsVersion2() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "Content": { "ZipFile": "%s" }, + "CompatibleRuntimes": ["nodejs22.x"], + "Description": "Shared utilities v2" + } + """.formatted(layerZipBase64())) + .when() + .post("/2018-10-31/layers/" + LAYER_NAME + "/versions") + .then() + .statusCode(201) + .body("Version", equalTo(2)) + .body("LayerVersionArn", containsString(":layer:" + LAYER_NAME + ":2")) + .body("Description", equalTo("Shared utilities v2")); + } + + // ── GetLayerVersion ────────────────────────────────────────────────────── + + @Test + @Order(3) + void getLayerVersion_returnsVersion1() { + given() + .when() + .get("/2018-10-31/layers/" + LAYER_NAME + "/versions/1") + .then() + .statusCode(200) + .body("Version", equalTo(1)) + .body("Description", equalTo("Shared utilities v1")) + .body("LayerArn", containsString(":layer:" + LAYER_NAME)) + .body("LayerVersionArn", containsString(":layer:" + LAYER_NAME + ":1")) + .body("Content.CodeSha256", not(emptyString())); + } + + @Test + @Order(4) + void getLayerVersion_nonExistent_returns404() { + given() + .when() + .get("/2018-10-31/layers/" + LAYER_NAME + "/versions/99") + .then() + .statusCode(404); + } + + @Test + @Order(5) + void getLayerVersion_nonExistentLayer_returns404() { + given() + .when() + .get("/2018-10-31/layers/no-such-layer/versions/1") + .then() + .statusCode(404); + } + + // ── ListLayerVersions ──────────────────────────────────────────────────── + + @Test + @Order(6) + void listLayerVersions_returnsBothVersions() { + given() + .when() + .get("/2018-10-31/layers/" + LAYER_NAME + "/versions") + .then() + .statusCode(200) + .body("LayerVersions", hasSize(2)) + .body("LayerVersions[0].Version", equalTo(1)) + .body("LayerVersions[1].Version", equalTo(2)); + } + + @Test + @Order(7) + void listLayerVersions_nonExistentLayer_returnsEmptyList() { + given() + .when() + .get("/2018-10-31/layers/no-such-layer/versions") + .then() + .statusCode(200) + .body("LayerVersions", empty()); + } + + // ── ListLayers ─────────────────────────────────────────────────────────── + + @Test + @Order(8) + void listLayers_returnsLayerWithLatestVersion() { + given() + .when() + .get("/2018-10-31/layers") + .then() + .statusCode(200) + .body("Layers", hasSize(greaterThanOrEqualTo(1))) + .body("Layers.find { it.LayerName == '" + LAYER_NAME + "' }.LayerArn", + containsString(":layer:" + LAYER_NAME)) + .body("Layers.find { it.LayerName == '" + LAYER_NAME + "' }.LatestMatchingVersion.Version", + equalTo(2)); + } + + // ── Layer attachment on CreateFunction ──────────────────────────────────── + + @Test + @Order(9) + void createFunction_withLayers_storesLayerArns() throws Exception { + given() + .contentType("application/json") + .body(""" + { + "FunctionName": "%s", + "Runtime": "nodejs20.x", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Handler": "index.handler", + "Code": { "ZipFile": "%s" }, + "Layers": ["arn:aws:lambda:us-east-1:000000000000:layer:%s:1"] + } + """.formatted(FN_NAME, functionZipBase64(), LAYER_NAME)) + .when() + .post("/2015-03-31/functions") + .then() + .statusCode(201) + .body("FunctionName", equalTo(FN_NAME)) + .body("Layers", hasSize(1)) + .body("Layers[0].Arn", containsString(":layer:" + LAYER_NAME + ":1")); + } + + @Test + @Order(10) + void getFunction_showsLayers() { + given() + .when() + .get("/2015-03-31/functions/" + FN_NAME) + .then() + .statusCode(200) + .body("Configuration.Layers", hasSize(1)) + .body("Configuration.Layers[0].Arn", containsString(":layer:" + LAYER_NAME + ":1")); + } + + // ── Layer attachment on UpdateFunctionConfiguration ─────────────────────── + + @Test + @Order(11) + void updateFunctionConfiguration_updatesLayers() { + given() + .contentType("application/json") + .body(""" + { + "Layers": [ + "arn:aws:lambda:us-east-1:000000000000:layer:%s:1", + "arn:aws:lambda:us-east-1:000000000000:layer:%s:2" + ] + } + """.formatted(LAYER_NAME, LAYER_NAME)) + .when() + .put("/2015-03-31/functions/" + FN_NAME + "/configuration") + .then() + .statusCode(200) + .body("Layers", hasSize(2)); + } + + @Test + @Order(12) + void updateFunctionConfiguration_removesAllLayers() { + given() + .contentType("application/json") + .body(""" + { + "Layers": [] + } + """) + .when() + .put("/2015-03-31/functions/" + FN_NAME + "/configuration") + .then() + .statusCode(200) + .body("Layers", anyOf(nullValue(), empty())); + } + + // ── DeleteLayerVersion ─────────────────────────────────────────────────── + + @Test + @Order(13) + void deleteLayerVersion_removesVersion1() { + given() + .when() + .delete("/2018-10-31/layers/" + LAYER_NAME + "/versions/1") + .then() + .statusCode(204); + } + + @Test + @Order(14) + void listLayerVersions_afterDelete_showsOnlyVersion2() { + given() + .when() + .get("/2018-10-31/layers/" + LAYER_NAME + "/versions") + .then() + .statusCode(200) + .body("LayerVersions", hasSize(1)) + .body("LayerVersions[0].Version", equalTo(2)); + } + + @Test + @Order(15) + void deleteLayerVersion_nonExistent_returns204() { + // AWS returns 204 even for non-existent versions + given() + .when() + .delete("/2018-10-31/layers/" + LAYER_NAME + "/versions/99") + .then() + .statusCode(204); + } + + // ── PublishLayerVersion validation ──────────────────────────────────────── + + @Test + @Order(16) + void publishLayerVersion_missingContent_returns400() { + given() + .contentType("application/json") + .body(""" + { + "Description": "No content" + } + """) + .when() + .post("/2018-10-31/layers/" + LAYER_NAME + "/versions") + .then() + .statusCode(400); + } + + // ── cleanup ────────────────────────────────────────────────────────────── + + @Test + @Order(20) + void cleanup_deleteFunction() { + given() + .when() + .delete("/2015-03-31/functions/" + FN_NAME) + .then() + .statusCode(204); + } + + @Test + @Order(21) + void cleanup_deleteRemainingLayerVersion() { + given() + .when() + .delete("/2018-10-31/layers/" + LAYER_NAME + "/versions/2") + .then() + .statusCode(204); + } + + @Test + @Order(22) + void listLayers_afterCleanup_noTestLayer() { + given() + .when() + .get("/2018-10-31/layers") + .then() + .statusCode(200); + // Layer should no longer appear (all versions deleted) + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java index b1c63effc6..b55e170521 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java @@ -76,7 +76,8 @@ class ContainerLauncherTest { ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer); launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver, - runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, embeddedDnsServer); + runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager, embeddedDnsServer, + mock(io.github.hectorvent.floci.services.lambda.LambdaLayerService.class)); when(runtimeApiServerFactory.create()).thenReturn(runtimeApiServer); when(runtimeApiServer.getPort()).thenReturn(9000);