Light, fluffy, and always free - The AWS Local Emulator alternative
feat(codegurureviewer): repository association lifecycle with tagging (#2741)
lex000b46d804c04b
diff --git a/docs/services/codegurureviewer.md b/docs/services/codegurureviewer.mdnew file mode 100644index 0000000000..d7a452cb90--- /dev/null+++ b/docs/services/codegurureviewer.md@@ -0,0 +1,42 @@+# CodeGuru Reviewer++**Protocol:** REST JSON++**Endpoint:** `http://localhost:4566`++Floci implements the CodeGuru Reviewer repository-association lifecycle for local SDK,+CLI, and Terraform workflows. Associations are isolated by region and use the configured+Floci storage mode.++## Supported Actions++<!-- floci:actions:start -->+| Action | Description |+| --- | --- |+| `AssociateRepository` | Associates a CodeCommit, Bitbucket, GitHub Enterprise Server, or S3 repository (`POST /associations`) |+| `DescribeRepositoryAssociation` | Returns the association, its state, and its tags (`GET /associations/{associationArn}`) |+| `DisassociateRepository` | Removes the association (`DELETE /associations/{associationArn}`) |+| `ListRepositoryAssociations` | Lists association summaries with filters and pagination (`GET /associations`) |+| `ListTagsForResource` | Lists association tags (`GET /tags/{resourceArn}`) |+| `TagResource` | Adds tags to an association (`POST /tags/{resourceArn}`) |+| `UntagResource` | Removes tag keys from an association (`DELETE /tags/{resourceArn}`) |+<!-- floci:actions:end -->++`ListRepositoryAssociations` accepts the documented filters (`ProviderType`,+`State`, `Name`, `Owner`) plus `MaxResults` and `NextToken` pagination.++An association reaches the terminal `Associated` state as soon as `AssociateRepository`+returns, so a provider waiter polling `DescribeRepositoryAssociation` completes on its+first read instead of spinning through an `Associating` state the emulator would never+leave. The `Repository` union is validated the way AWS validates it: exactly one of+`CodeCommit`, `Bitbucket`, `GitHubEnterpriseServer`, or `S3Bucket` must be set, third-party+providers require `Owner` and `ConnectionArn`, and `CUSTOMER_MANAGED_CMK` encryption+requires a `KMSKeyId`. Associating the same repository twice reports `ConflictException`.++Code reviews and recommendations are not implemented.++## Configuration++| Variable | Default | Description |+|---|---|---|+| `FLOCI_SERVICES_CODEGURUREVIEWER_ENABLED` | `true` | Enable or disable CodeGuru Reviewer |diff --git a/docs/services/index.md b/docs/services/index.mdindex 9ae88ab7b8..8d30e1b8c4 100644--- a/docs/services/index.md+++ b/docs/services/index.md@@ -95,6 +95,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac| [Managed Prometheus (AMP)](managed-prometheus.md) | `/workspaces/*`, `/tags/*` | REST JSON | 8 || [AWS Backup](backup.md) | `/backup-vaults/*`, `/backup/plans/*`, `/backup-jobs/*`, `/supported-resource-types` | REST JSON | 20 || [AWS FIS](fis.md) | `/experimentTemplates/*`, `/experiments/*`, `/actions/*`, `/targetResourceTypes/*`, `/safetyLevers/*`, `/tags/*` | REST JSON | 26 |+| [CodeGuru Reviewer](codegurureviewer.md) | `/associations`, `/associations/{associationArn}`, `/tags/*` | REST JSON | 7 || [CloudFront](cloudfront.md) | `/2020-05-31/distribution/*`, `/2020-05-31/cache-policy/*`, `/2020-05-31/function/*` | REST XML | 50 || [Route53](route53.md) | `/2013-04-01/hostedzone/*`, `/2013-04-01/healthcheck/*`, `/2013-04-01/change/*` | REST XML | 17 || [Route 53 Resolver](route53resolver.md) | `POST /` + `X-Amz-Target: Route53Resolver.*` | JSON 1.1 | 18 |diff --git a/mkdocs.yml b/mkdocs.ymlindex a7e0f6617f..9de06047e0 100644--- a/mkdocs.yml+++ b/mkdocs.yml@@ -137,6 +137,7 @@ nav:- CodeBuild: services/codebuild.md- AWS Batch: services/batch.md- CodeDeploy: services/codedeploy.md+ - CodeGuru Reviewer: services/codegurureviewer.md- CodePipeline: services/codepipeline.md- Service Quotas: services/servicequotas.md- AWS RAM: services/ram.mddiff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 475cd414bf..fe11bc4e34 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -702,6 +702,7 @@ public interface EmulatorConfig {LakeFormationServiceConfig lakeformation();EfsServiceConfig efs();+ CodeGuruReviewerServiceConfig codegurureviewer();}interface ConnectServiceConfig {@@ -719,6 +720,11 @@ public interface EmulatorConfig {boolean enabled();}+ interface CodeGuruReviewerServiceConfig {+ @WithDefault("true")+ boolean enabled();+ }+interface IotServiceConfig {@WithDefault("true")boolean enabled();diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.javaindex 811fe02512..5b96a52572 100644--- a/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java+++ b/src/main/java/io/github/hectorvent/floci/core/common/ResolvedServiceCatalog.java@@ -571,7 +571,13 @@ public class ResolvedServiceCatalog {storageMode(config.storage().services().efs().mode(), config.storage().mode()),config.storage().services().efs().flushIntervalMs(), null, ServiceProtocol.REST_JSON,protocols(ServiceProtocol.REST_JSON),- Set.of(), Set.of("elasticfilesystem"), Set.of(), Set.of(EfsController.class))+ Set.of(), Set.of("elasticfilesystem"), Set.of(), Set.of(EfsController.class)),+ descriptor("codeguru-reviewer", "codegurureviewer",+ config.services().codegurureviewer().enabled(), true,+ "codegurureviewer", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,+ protocols(ServiceProtocol.REST_JSON),+ Set.of(), Set.of("codeguru-reviewer"), Set.of(),+ Set.of(io.github.hectorvent.floci.services.codegurureviewer.CodeGuruReviewerController.class))));}diff --git a/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerController.java b/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerController.javanew file mode 100644index 0000000000..6ab4c50d7c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerController.java@@ -0,0 +1,203 @@+package io.github.hectorvent.floci.services.codegurureviewer;++import com.fasterxml.jackson.databind.JsonNode;+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.AwsException;+import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.services.codegurureviewer.model.RepositoryAssociation;+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.QueryParam;+import jakarta.ws.rs.WebApplicationException;+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.time.Instant;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++/**+ * Amazon CodeGuru Reviewer REST-JSON controller.+ *+ * <p>Tagging goes through the shared {@code /tags/{resourceArn}} path, which+ * {@link CodeGuruReviewerService} serves as a {@code TagHandler}.+ *+ * <p>Only the operations declared below are served; anything else falls through to the+ * emulator's not-found handling rather than a stub success.+ */+@Path("/")+@Produces(MediaType.APPLICATION_JSON)+@Consumes(MediaType.APPLICATION_JSON)+public class CodeGuruReviewerController {++ private final CodeGuruReviewerService codeGuruReviewerService;+ private final RegionResolver regionResolver;+ private final ObjectMapper objectMapper;++ @Inject+ public CodeGuruReviewerController(CodeGuruReviewerService codeGuruReviewerService,+ RegionResolver regionResolver, ObjectMapper objectMapper) {+ this.codeGuruReviewerService = codeGuruReviewerService;+ this.regionResolver = regionResolver;+ this.objectMapper = objectMapper;+ }++ @POST+ @Path("/associations")+ public Response associateRepository(@Context HttpHeaders headers, String body) {+ String region = regionResolver.resolveRegion(headers);+ JsonNode request = readTree(body);+ RepositoryAssociation association = codeGuruReviewerService.associateRepository(+ request.get("Repository"), request.get("KMSKeyDetails"),+ parseTags(request.get("Tags")), region);+ return Response.ok(associationResponse(association)).build();+ }++ @GET+ @Path("/associations/{associationArn}")+ public Response describeRepositoryAssociation(@PathParam("associationArn") String associationArn,+ @Context HttpHeaders headers) {+ String region = regionResolver.resolveRegion(headers);+ return Response.ok(associationResponse(+ codeGuruReviewerService.describeRepositoryAssociation(associationArn, region))).build();+ }++ @DELETE+ @Path("/associations/{associationArn}")+ public Response disassociateRepository(@PathParam("associationArn") String associationArn,+ @Context HttpHeaders headers) {+ String region = regionResolver.resolveRegion(headers);+ return Response.ok(associationResponse(+ codeGuruReviewerService.disassociateRepository(associationArn, region))).build();+ }++ /**+ * The filter query keys are singular ({@code ProviderType=...&State=...}) because that is+ * the wire mapping the API reference documents for the plural request fields+ * ({@code ProviderTypes}, {@code States}, ...): the SDK serializes each list member as a+ * repeated singular query parameter.+ */+ @GET+ @Path("/associations")+ public Response listRepositoryAssociations(@QueryParam("ProviderType") List<String> providerTypes,+ @QueryParam("State") List<String> states,+ @QueryParam("Name") List<String> names,+ @QueryParam("Owner") List<String> owners,+ @QueryParam("MaxResults") String maxResults,+ @QueryParam("NextToken") String nextToken,+ @Context HttpHeaders headers) {+ String region = regionResolver.resolveRegion(headers);+ PaginatedResult<RepositoryAssociation> page = codeGuruReviewerService.listRepositoryAssociations(+ providerTypes, states, names, owners, parseMaxResults(maxResults), nextToken, region);+ ObjectNode response = objectMapper.createObjectNode();+ ArrayNode summaries = response.putArray("RepositoryAssociationSummaries");+ for (RepositoryAssociation association : page.items()) {+ ObjectNode summary = summaries.addObject();+ summary.put("AssociationArn", association.getAssociationArn());+ if (association.getConnectionArn() != null) {+ summary.put("ConnectionArn", association.getConnectionArn());+ }+ summary.put("LastUpdatedTimeStamp", epochSeconds(association.getLastUpdatedTimeStamp()));+ summary.put("AssociationId", association.getAssociationId());+ summary.put("Name", association.getName());+ summary.put("Owner", association.getOwner());+ summary.put("ProviderType", association.getProviderType());+ summary.put("State", association.getState());+ }+ if (page.nextToken() != null) {+ response.put("NextToken", page.nextToken());+ }+ return Response.ok(response).build();+ }++ private ObjectNode associationResponse(RepositoryAssociation association) {+ ObjectNode response = objectMapper.createObjectNode();+ response.set("RepositoryAssociation", associationNode(association));+ response.set("Tags", objectMapper.valueToTree(+ association.getTags() != null ? association.getTags() : Map.of()));+ return response;+ }++ private ObjectNode associationNode(RepositoryAssociation association) {+ ObjectNode node = objectMapper.createObjectNode();+ node.put("AssociationId", association.getAssociationId());+ node.put("AssociationArn", association.getAssociationArn());+ if (association.getConnectionArn() != null) {+ node.put("ConnectionArn", association.getConnectionArn());+ }+ node.put("Name", association.getName());+ node.put("Owner", association.getOwner());+ node.put("ProviderType", association.getProviderType());+ node.put("State", association.getState());+ node.put("StateReason", association.getStateReason());+ node.put("CreatedTimeStamp", epochSeconds(association.getCreatedTimeStamp()));+ node.put("LastUpdatedTimeStamp", epochSeconds(association.getLastUpdatedTimeStamp()));++ ObjectNode kmsKeyDetails = node.putObject("KMSKeyDetails");+ kmsKeyDetails.put("EncryptionOption", association.getEncryptionOption());+ if (association.getKmsKeyId() != null) {+ kmsKeyDetails.put("KMSKeyId", association.getKmsKeyId());+ }++ if (association.getS3BucketName() != null) {+ ObjectNode s3Details = node.putObject("S3RepositoryDetails");+ s3Details.put("BucketName", association.getS3BucketName());+ if (association.getSourceCodeArtifactsObjectKey() != null) {+ ObjectNode codeArtifacts = s3Details.putObject("CodeArtifacts");+ codeArtifacts.put("SourceCodeArtifactsObjectKey", association.getSourceCodeArtifactsObjectKey());+ if (association.getBuildArtifactsObjectKey() != null) {+ codeArtifacts.put("BuildArtifactsObjectKey", association.getBuildArtifactsObjectKey());+ }+ }+ }+ return node;+ }++ private long epochSeconds(Instant instant) {+ return instant != null ? instant.getEpochSecond() : 0L;+ }++ // Bound as String so a malformed value reaches this method: a JAX-RS Integer binding+ // fails during parameter conversion and surfaces as 404, where AWS models 400.+ private Integer parseMaxResults(String maxResults) {+ if (maxResults == null || maxResults.isBlank()) {+ return null;+ }+ try {+ return Integer.valueOf(maxResults);+ } catch (NumberFormatException e) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + maxResults+ + "' at 'maxResults' failed to satisfy constraint: Member must be an integer.", 400);+ }+ }++ private JsonNode readTree(String body) {+ try {+ return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);+ } catch (Exception e) {+ throw new WebApplicationException(JsonErrorResponseUtils.createSerializationErrorResponse());+ }+ }++ private Map<String, String> parseTags(JsonNode tagsNode) {+ Map<String, String> tags = new LinkedHashMap<>();+ if (tagsNode != null && tagsNode.isObject()) {+ tagsNode.fields().forEachRemaining(entry -> tags.put(entry.getKey(), entry.getValue().asText()));+ }+ return tags;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerService.java b/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerService.javanew file mode 100644index 0000000000..fa10d1d1b9--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerService.java@@ -0,0 +1,312 @@+package io.github.hectorvent.floci.services.codegurureviewer;++import com.fasterxml.jackson.core.type.TypeReference;+import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.core.common.PaginatedResult;+import io.github.hectorvent.floci.core.common.Pagination;+import io.github.hectorvent.floci.core.common.RegionResolver;+import io.github.hectorvent.floci.core.common.TagHandler;+import io.github.hectorvent.floci.core.storage.StorageBackend;+import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.codegurureviewer.model.RepositoryAssociation;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.inject.Inject;+import org.jboss.logging.Logger;++import java.time.Instant;+import java.util.Comparator;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.UUID;+import java.util.regex.Pattern;++/**+ * Amazon CodeGuru Reviewer repository associations.+ *+ * <p>An association reaches the terminal {@code Associated} state as soon as+ * {@code AssociateRepository} returns, so the provider waiter that polls+ * {@code DescribeRepositoryAssociation} completes on its first attempt instead of spinning+ * through an {@code Associating} state the emulator would never leave.+ */+@ApplicationScoped+public class CodeGuruReviewerService implements TagHandler {++ private static final Logger LOG = Logger.getLogger(CodeGuruReviewerService.class);++ private static final Pattern NAME = Pattern.compile("\\S[\\w.-]*");+ private static final Pattern OWNER = Pattern.compile("\\S(.*\\S)?");+ private static final Set<String> ENCRYPTION_OPTIONS = Set.of("AWS_OWNED_CMK", "CUSTOMER_MANAGED_CMK");+ private static final String ASSOCIATED = "Associated";+ private static final String DISASSOCIATED = "Disassociated";+ private static final String ARN_RESOURCE_PREFIX = "association:";++ private final StorageBackend<String, RepositoryAssociation> associations;+ private final RegionResolver regionResolver;++ @Inject+ public CodeGuruReviewerService(StorageFactory storageFactory, RegionResolver regionResolver) {+ this.associations = storageFactory.create("codegurureviewer", "codegurureviewer-associations.json",+ new TypeReference<Map<String, RepositoryAssociation>>() {});+ this.regionResolver = regionResolver;+ }++ // ──────────────────────── Repository associations ────────────────────────++ /**+ * {@code Repository} is a union: exactly one of {@code CodeCommit}, {@code Bitbucket},+ * {@code GitHubEnterpriseServer} or {@code S3Bucket} may be set, and the association's+ * {@code Name}, {@code Owner} and {@code ProviderType} follow from whichever it is.+ */+ public RepositoryAssociation associateRepository(JsonNode repository, JsonNode kmsKeyDetails,+ Map<String, String> tags, String region) {+ if (repository == null || !repository.isObject()) {+ throw new AwsException("ValidationException", "Repository is required.", 400);+ }++ RepositoryAssociation association = new RepositoryAssociation();+ String accountId = regionResolver.getAccountId();+ int members = 0;++ JsonNode codeCommit = repository.get("CodeCommit");+ if (codeCommit != null && codeCommit.isObject()) {+ members++;+ association.setProviderType("CodeCommit");+ association.setName(requireName(codeCommit, "Repository.CodeCommit.Name"));+ association.setOwner(accountId);+ }+ JsonNode bitbucket = repository.get("Bitbucket");+ if (bitbucket != null && bitbucket.isObject()) {+ members++;+ applyThirdParty(association, bitbucket, "Bitbucket");+ }+ JsonNode gitHubEnterprise = repository.get("GitHubEnterpriseServer");+ if (gitHubEnterprise != null && gitHubEnterprise.isObject()) {+ members++;+ applyThirdParty(association, gitHubEnterprise, "GitHubEnterpriseServer");+ }+ JsonNode s3Bucket = repository.get("S3Bucket");+ if (s3Bucket != null && s3Bucket.isObject()) {+ members++;+ association.setProviderType("S3Bucket");+ association.setName(requireName(s3Bucket, "Repository.S3Bucket.Name"));+ association.setOwner(accountId);+ String bucketName = text(s3Bucket, "BucketName");+ if (bucketName == null || bucketName.isBlank()) {+ throw new AwsException("ValidationException", "Repository.S3Bucket.BucketName is required.", 400);+ }+ association.setS3BucketName(bucketName);+ }++ if (members != 1) {+ throw new AwsException("ValidationException",+ "Repository must set exactly one of CodeCommit, Bitbucket, GitHubEnterpriseServer, S3Bucket.",+ 400);+ }+ if (findByRepository(association.getProviderType(), association.getOwner(), association.getName(), region)+ != null) {+ throw new AwsException("ConflictException",+ "Repository " + association.getName() + " is already associated.", 409);+ }++ applyKmsKeyDetails(association, kmsKeyDetails);++ String associationId = UUID.randomUUID().toString();+ Instant now = Instant.now();+ association.setAssociationId(associationId);+ association.setAssociationArn(regionResolver.buildArn("codeguru-reviewer", region,+ ARN_RESOURCE_PREFIX + associationId));+ association.setState(ASSOCIATED);+ association.setStateReason("Pull Request Notification configuration successful");+ association.setCreatedTimeStamp(now);+ association.setLastUpdatedTimeStamp(now);+ association.setTags(tags != null ? new LinkedHashMap<>(tags) : new LinkedHashMap<>());++ associations.put(storageKey(region, associationId), association);+ LOG.infov("Associated CodeGuru Reviewer repository: {0} ({1})",+ association.getName(), association.getProviderType());+ return association;+ }++ public RepositoryAssociation describeRepositoryAssociation(String associationArn, String region) {+ return associations.get(lookupKey(associationArn, region))+ .orElseThrow(() -> associationNotFound(associationArn));+ }++ public RepositoryAssociation disassociateRepository(String associationArn, String region) {+ RepositoryAssociation association = describeRepositoryAssociation(associationArn, region);+ associations.delete(storageKey(region, association.getAssociationId()));+ association.setState(DISASSOCIATED);+ association.setLastUpdatedTimeStamp(Instant.now());+ LOG.infov("Disassociated CodeGuru Reviewer repository: {0}", association.getName());+ return association;+ }++ public PaginatedResult<RepositoryAssociation> listRepositoryAssociations(+ List<String> providerTypes, List<String> states, List<String> names, List<String> owners,+ Integer maxResults, String nextToken, String region) {+ String regionPrefix = region + "::";+ List<RepositoryAssociation> matching = associations.scan(key -> key.startsWith(regionPrefix)).stream()+ .filter(association -> matches(providerTypes, association.getProviderType()))+ .filter(association -> matches(states, association.getState()))+ .filter(association -> matches(names, association.getName()))+ .filter(association -> matches(owners, association.getOwner()))+ .sorted(Comparator.comparing(RepositoryAssociation::getName)+ .thenComparing(RepositoryAssociation::getAssociationId))+ .toList();+ return Pagination.paginate(matching, RepositoryAssociation::getAssociationId,+ maxResults, nextToken, 100, "ValidationException");+ }++ // ──────────────────────────── Tags ────────────────────────────++ @Override+ public String serviceKey() {+ return "codeguru-reviewer";+ }++ @Override+ public String tagsBodyKey() {+ return "Tags";+ }++ @Override+ public Map<String, String> listTags(String region, String arn) {+ Map<String, String> tags = forTagging(arn, region).getTags();+ return tags != null ? tags : Map.of();+ }++ @Override+ public void tagResource(String region, String arn, Map<String, String> tags) {+ RepositoryAssociation association = forTagging(arn, region);+ if (association.getTags() == null) {+ association.setTags(new HashMap<>());+ }+ association.getTags().putAll(tags);+ associations.put(storageKey(region, association.getAssociationId()), association);+ }++ @Override+ public void untagResource(String region, String arn, List<String> tagKeys) {+ RepositoryAssociation association = forTagging(arn, region);+ if (association.getTags() != null && tagKeys != null) {+ tagKeys.forEach(association.getTags()::remove);+ }+ associations.put(storageKey(region, association.getAssociationId()), association);+ }++ /**+ * The tag operations declare {@code ResourceNotFoundException} where the association+ * operations declare {@code NotFoundException}, so the lookup is repeated here with the+ * error code the tag path's model actually names.+ */+ private RepositoryAssociation forTagging(String arn, String region) {+ return associations.get(lookupKey(arn, region))+ .orElseThrow(() -> new AwsException("ResourceNotFoundException",+ "Repository association " + arn + " does not exist.", 404));+ }++ // ──────────────────────────── Helpers ────────────────────────────++ private void applyThirdParty(RepositoryAssociation association, JsonNode repository, String providerType) {+ association.setProviderType(providerType);+ association.setName(requireName(repository, "Repository." + providerType + ".Name"));++ String owner = text(repository, "Owner");+ if (owner == null || !OWNER.matcher(owner).matches() || owner.length() > 100) {+ throw new AwsException("ValidationException",+ "Repository." + providerType + ".Owner is required and must be 1-100 characters.", 400);+ }+ association.setOwner(owner);++ String connectionArn = text(repository, "ConnectionArn");+ if (connectionArn == null || connectionArn.isBlank()) {+ throw new AwsException("ValidationException",+ "Repository." + providerType + ".ConnectionArn is required.", 400);+ }+ association.setConnectionArn(connectionArn);+ }++ private void applyKmsKeyDetails(RepositoryAssociation association, JsonNode kmsKeyDetails) {+ String encryptionOption = "AWS_OWNED_CMK";+ String kmsKeyId = null;+ if (kmsKeyDetails != null && kmsKeyDetails.isObject()) {+ String requested = text(kmsKeyDetails, "EncryptionOption");+ if (requested != null) {+ if (!ENCRYPTION_OPTIONS.contains(requested)) {+ throw new AwsException("ValidationException",+ "KMSKeyDetails.EncryptionOption must be one of AWS_OWNED_CMK, CUSTOMER_MANAGED_CMK.",+ 400);+ }+ encryptionOption = requested;+ }+ kmsKeyId = text(kmsKeyDetails, "KMSKeyId");+ }+ if ("CUSTOMER_MANAGED_CMK".equals(encryptionOption) && (kmsKeyId == null || kmsKeyId.isBlank())) {+ throw new AwsException("ValidationException",+ "KMSKeyDetails.KMSKeyId is required when EncryptionOption is CUSTOMER_MANAGED_CMK.", 400);+ }+ association.setEncryptionOption(encryptionOption);+ association.setKmsKeyId(kmsKeyId);+ }++ private RepositoryAssociation findByRepository(String providerType, String owner, String name, String region) {+ String regionPrefix = region + "::";+ return associations.scan(key -> key.startsWith(regionPrefix)).stream()+ .filter(association -> providerType.equals(association.getProviderType())+ && owner.equals(association.getOwner())+ && name.equals(association.getName()))+ .findFirst()+ .orElse(null);+ }++ private String lookupKey(String associationArn, String region) {+ AwsArnUtils.Arn arn;+ try {+ arn = AwsArnUtils.parse(associationArn);+ } catch (IllegalArgumentException e) {+ throw new AwsException("ValidationException",+ "AssociationArn is not a valid CodeGuru Reviewer association ARN: " + associationArn, 400);+ }+ if (!"codeguru-reviewer".equals(arn.service()) || !arn.resource().startsWith(ARN_RESOURCE_PREFIX)) {+ throw new AwsException("ValidationException",+ "AssociationArn is not a valid CodeGuru Reviewer association ARN: " + associationArn, 400);+ }+ String arnRegion = arn.region().isEmpty() ? region : arn.region();+ return storageKey(arnRegion, arn.resource().substring(ARN_RESOURCE_PREFIX.length()));+ }++ private String requireName(JsonNode repository, String field) {+ String name = text(repository, "Name");+ if (name == null || !NAME.matcher(name).matches() || name.length() > 100) {+ throw new AwsException("ValidationException",+ field + " is required and must be 1-100 characters matching ^\\S[\\w.-]*$.", 400);+ }+ return name;+ }++ private boolean matches(List<String> filter, String value) {+ return filter == null || filter.isEmpty() || filter.contains(value);+ }++ private String text(JsonNode node, String field) {+ JsonNode value = node.get(field);+ if (value == null || value.isNull()) {+ return null;+ }+ return value.asText();+ }++ private AwsException associationNotFound(String associationArn) {+ return new AwsException("NotFoundException",+ "Repository association " + associationArn + " does not exist.", 404);+ }++ private String storageKey(String region, String associationId) {+ return region + "::" + associationId;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/model/RepositoryAssociation.java b/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/model/RepositoryAssociation.javanew file mode 100644index 0000000000..d4c00950dd--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/codegurureviewer/model/RepositoryAssociation.java@@ -0,0 +1,157 @@+package io.github.hectorvent.floci.services.codegurureviewer.model;++import io.quarkus.runtime.annotations.RegisterForReflection;++import java.time.Instant;+import java.util.LinkedHashMap;+import java.util.Map;++/** An association between CodeGuru Reviewer and a source repository. */+@RegisterForReflection+public class RepositoryAssociation {++ private String associationId;+ private String associationArn;+ private String connectionArn;+ private String name;+ private String owner;+ private String providerType;+ private String state;+ private String stateReason;+ private Instant createdTimeStamp;+ private Instant lastUpdatedTimeStamp;+ private String kmsKeyId;+ private String encryptionOption;+ private String s3BucketName;+ private String sourceCodeArtifactsObjectKey;+ private String buildArtifactsObjectKey;+ private Map<String, String> tags = new LinkedHashMap<>();++ public String getAssociationId() {+ return associationId;+ }++ public void setAssociationId(String associationId) {+ this.associationId = associationId;+ }++ public String getAssociationArn() {+ return associationArn;+ }++ public void setAssociationArn(String associationArn) {+ this.associationArn = associationArn;+ }++ public String getConnectionArn() {+ return connectionArn;+ }++ public void setConnectionArn(String connectionArn) {+ this.connectionArn = connectionArn;+ }++ public String getName() {+ return name;+ }++ public void setName(String name) {+ this.name = name;+ }++ public String getOwner() {+ return owner;+ }++ public void setOwner(String owner) {+ this.owner = owner;+ }++ public String getProviderType() {+ return providerType;+ }++ public void setProviderType(String providerType) {+ this.providerType = providerType;+ }++ public String getState() {+ return state;+ }++ public void setState(String state) {+ this.state = state;+ }++ public String getStateReason() {+ return stateReason;+ }++ public void setStateReason(String stateReason) {+ this.stateReason = stateReason;+ }++ public Instant getCreatedTimeStamp() {+ return createdTimeStamp;+ }++ public void setCreatedTimeStamp(Instant createdTimeStamp) {+ this.createdTimeStamp = createdTimeStamp;+ }++ public Instant getLastUpdatedTimeStamp() {+ return lastUpdatedTimeStamp;+ }++ public void setLastUpdatedTimeStamp(Instant lastUpdatedTimeStamp) {+ this.lastUpdatedTimeStamp = lastUpdatedTimeStamp;+ }++ public String getKmsKeyId() {+ return kmsKeyId;+ }++ public void setKmsKeyId(String kmsKeyId) {+ this.kmsKeyId = kmsKeyId;+ }++ public String getEncryptionOption() {+ return encryptionOption;+ }++ public void setEncryptionOption(String encryptionOption) {+ this.encryptionOption = encryptionOption;+ }++ public String getS3BucketName() {+ return s3BucketName;+ }++ public void setS3BucketName(String s3BucketName) {+ this.s3BucketName = s3BucketName;+ }++ public String getSourceCodeArtifactsObjectKey() {+ return sourceCodeArtifactsObjectKey;+ }++ public void setSourceCodeArtifactsObjectKey(String sourceCodeArtifactsObjectKey) {+ this.sourceCodeArtifactsObjectKey = sourceCodeArtifactsObjectKey;+ }++ public String getBuildArtifactsObjectKey() {+ return buildArtifactsObjectKey;+ }++ public void setBuildArtifactsObjectKey(String buildArtifactsObjectKey) {+ this.buildArtifactsObjectKey = buildArtifactsObjectKey;+ }++ public Map<String, String> getTags() {+ return tags;+ }++ public void setTags(Map<String, String> tags) {+ this.tags = tags;+ }+}diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex b2fb33b1bb..51c9dab365 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -605,3 +605,5 @@ floci:enabled: trueram:enabled: true+ codegurureviewer:+ enabled: truediff --git a/src/test/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerIntegrationTest.javanew file mode 100644index 0000000000..33ae464b13--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerIntegrationTest.java@@ -0,0 +1,368 @@+package io.github.hectorvent.floci.services.codegurureviewer;++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 static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.emptyIterable;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.matchesPattern;+import static org.hamcrest.Matchers.not;+import static org.hamcrest.Matchers.notNullValue;++@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class CodeGuruReviewerIntegrationTest {++ private static final String CONNECTION_ARN =+ "arn:aws:codestar-connections:us-east-1:000000000000:connection/11111111-2222-3333-4444-555555555555";++ private static String codeCommitAssociationArn;+ private static String bitbucketAssociationArn;+ private static String s3AssociationArn;++ @Test+ @Order(1)+ void associateCodeCommitRepository() {+ codeCommitAssociationArn = given()+ .contentType("application/json")+ .body("""+ {"Repository": {"CodeCommit": {"Name": "floci-service"}},+ "Tags": {"team": "reviewers"}}+ """)+ .when()+ .post("/associations")+ .then()+ .statusCode(200)+ .body("RepositoryAssociation.AssociationId", notNullValue())+ .body("RepositoryAssociation.AssociationArn",+ matchesPattern("^arn:aws:codeguru-reviewer:us-east-1:000000000000:association:"+ + "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$"))+ .body("RepositoryAssociation.Name", equalTo("floci-service"))+ .body("RepositoryAssociation.Owner", equalTo("000000000000"))+ .body("RepositoryAssociation.ProviderType", equalTo("CodeCommit"))+ .body("RepositoryAssociation.State", equalTo("Associated"))+ .body("RepositoryAssociation.StateReason", notNullValue())+ .body("RepositoryAssociation.CreatedTimeStamp", notNullValue())+ .body("RepositoryAssociation.LastUpdatedTimeStamp", notNullValue())+ .body("RepositoryAssociation.KMSKeyDetails.EncryptionOption", equalTo("AWS_OWNED_CMK"))+ .body("Tags.team", equalTo("reviewers"))+ .extract().path("RepositoryAssociation.AssociationArn");+ }++ @Test+ @Order(2)+ void describeIsAssociatedOnFirstRead() {+ given()+ .when()+ .get("/associations/" + codeCommitAssociationArn)+ .then()+ .statusCode(200)+ .body("RepositoryAssociation.AssociationArn", equalTo(codeCommitAssociationArn))+ .body("RepositoryAssociation.State", equalTo("Associated"))+ .body("RepositoryAssociation.ProviderType", equalTo("CodeCommit"))+ .body("Tags.team", equalTo("reviewers"));+ }++ @Test+ @Order(3)+ void describeMissingAssociationReturnsNotFound() {+ given()+ .when()+ .get("/associations/arn:aws:codeguru-reviewer:us-east-1:000000000000:association:"+ + "00000000-0000-0000-0000-000000000000")+ .then()+ .statusCode(404)+ .body("__type", equalTo("NotFoundException"));+ }++ @Test+ @Order(4)+ void associatingTheSameRepositoryTwiceConflicts() {+ given()+ .contentType("application/json")+ .body("{\"Repository\": {\"CodeCommit\": {\"Name\": \"floci-service\"}}}")+ .when()+ .post("/associations")+ .then()+ .statusCode(409)+ .body("__type", equalTo("ConflictException"));+ }++ @Test+ @Order(5)+ void associateRejectsRepositoryWithoutExactlyOneMember() {+ given()+ .contentType("application/json")+ .body("{\"Repository\": {}}")+ .when()+ .post("/associations")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));++ given()+ .contentType("application/json")+ .body("""+ {"Repository": {"CodeCommit": {"Name": "a"},+ "S3Bucket": {"Name": "b", "BucketName": "codeguru-floci"}}}+ """)+ .when()+ .post("/associations")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(6)+ void associateBitbucketRepositoryDerivesOwnerAndProviderType() {+ bitbucketAssociationArn = given()+ .contentType("application/json")+ .body("""+ {"Repository": {"Bitbucket": {"Name": "floci-web", "Owner": "floci-team",+ "ConnectionArn": "%s"}}}+ """.formatted(CONNECTION_ARN))+ .when()+ .post("/associations")+ .then()+ .statusCode(200)+ .body("RepositoryAssociation.Name", equalTo("floci-web"))+ .body("RepositoryAssociation.Owner", equalTo("floci-team"))+ .body("RepositoryAssociation.ProviderType", equalTo("Bitbucket"))+ .body("RepositoryAssociation.ConnectionArn", equalTo(CONNECTION_ARN))+ .body("RepositoryAssociation.State", equalTo("Associated"))+ .extract().path("RepositoryAssociation.AssociationArn");+ }++ @Test+ @Order(7)+ void bitbucketRepositoryRequiresConnectionArn() {+ given()+ .contentType("application/json")+ .body("{\"Repository\": {\"Bitbucket\": {\"Name\": \"floci-api\", \"Owner\": \"floci-team\"}}}")+ .when()+ .post("/associations")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(8)+ void associateS3RepositoryCarriesBucketDetails() {+ s3AssociationArn = given()+ .contentType("application/json")+ .body("""+ {"Repository": {"S3Bucket": {"Name": "floci-batch", "BucketName": "codeguru-reviewer-floci"}},+ "KMSKeyDetails": {"EncryptionOption": "CUSTOMER_MANAGED_CMK",+ "KMSKeyId": "11111111-2222-3333-4444-555555555555"}}+ """)+ .when()+ .post("/associations")+ .then()+ .statusCode(200)+ .body("RepositoryAssociation.Name", equalTo("floci-batch"))+ .body("RepositoryAssociation.ProviderType", equalTo("S3Bucket"))+ .body("RepositoryAssociation.Owner", equalTo("000000000000"))+ .body("RepositoryAssociation.S3RepositoryDetails.BucketName", equalTo("codeguru-reviewer-floci"))+ .body("RepositoryAssociation.KMSKeyDetails.EncryptionOption", equalTo("CUSTOMER_MANAGED_CMK"))+ .body("RepositoryAssociation.KMSKeyDetails.KMSKeyId", equalTo("11111111-2222-3333-4444-555555555555"))+ .extract().path("RepositoryAssociation.AssociationArn");+ }++ @Test+ @Order(9)+ void customerManagedKeyRequiresKeyId() {+ given()+ .contentType("application/json")+ .body("""+ {"Repository": {"CodeCommit": {"Name": "floci-keyless"}},+ "KMSKeyDetails": {"EncryptionOption": "CUSTOMER_MANAGED_CMK"}}+ """)+ .when()+ .post("/associations")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(10)+ void listRepositoryAssociations() {+ given()+ .when()+ .get("/associations")+ .then()+ .statusCode(200)+ .body("RepositoryAssociationSummaries.Name",+ hasItem("floci-service"))+ .body("RepositoryAssociationSummaries.Name", hasItem("floci-web"))+ .body("RepositoryAssociationSummaries.State", hasItem("Associated"));++ given()+ .when()+ .get("/associations?ProviderType=Bitbucket")+ .then()+ .statusCode(200)+ .body("RepositoryAssociationSummaries.size()", equalTo(1))+ .body("RepositoryAssociationSummaries[0].Name", equalTo("floci-web"))+ .body("RepositoryAssociationSummaries[0].AssociationArn", equalTo(bitbucketAssociationArn))+ .body("RepositoryAssociationSummaries[0].ConnectionArn", equalTo(CONNECTION_ARN));++ given()+ .when()+ .get("/associations?Name=nothing-here")+ .then()+ .statusCode(200)+ .body("RepositoryAssociationSummaries", emptyIterable());+ }++ @Test+ @Order(11)+ void listRepositoryAssociationsPaginates() {+ String firstPageArn =+ given()+ .when()+ .get("/associations?MaxResults=1")+ .then()+ .statusCode(200)+ .body("RepositoryAssociationSummaries.size()", equalTo(1))+ .body("NextToken", notNullValue())+ .extract()+ .path("RepositoryAssociationSummaries[0].AssociationArn");++ String nextToken =+ given()+ .when()+ .get("/associations?MaxResults=1")+ .then()+ .extract()+ .path("NextToken");++ given()+ .when()+ .get("/associations?MaxResults=1&NextToken=" + nextToken)+ .then()+ .statusCode(200)+ .body("RepositoryAssociationSummaries.size()", equalTo(1))+ .body("RepositoryAssociationSummaries[0].AssociationArn", not(equalTo(firstPageArn)));++ given()+ .when()+ .get("/associations?MaxResults=0")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));++ given()+ .when()+ .get("/associations?MaxResults=abc")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"));+ }++ @Test+ @Order(12)+ void tagRoundTripOverTheSharedTagsPath() {+ given()+ .when()+ .get("/tags/" + codeCommitAssociationArn)+ .then()+ .statusCode(200)+ .body("Tags.team", equalTo("reviewers"));++ given()+ .contentType("application/json")+ .body("{\"Tags\": {\"env\": \"test\"}}")+ .when()+ .post("/tags/" + codeCommitAssociationArn)+ .then()+ .statusCode(204);++ given()+ .when()+ .get("/tags/" + codeCommitAssociationArn)+ .then()+ .statusCode(200)+ .body("Tags.team", equalTo("reviewers"))+ .body("Tags.env", equalTo("test"));++ given()+ .when()+ .delete("/tags/" + codeCommitAssociationArn + "?tagKeys=env")+ .then()+ .statusCode(204);++ given()+ .when()+ .get("/tags/" + codeCommitAssociationArn)+ .then()+ .statusCode(200)+ .body("Tags.team", equalTo("reviewers"))+ .body("Tags.env", equalTo(null));++ given()+ .when()+ .get("/associations/" + codeCommitAssociationArn)+ .then()+ .statusCode(200)+ .body("Tags.team", equalTo("reviewers"));+ }++ @Test+ @Order(13)+ void tagsForUnknownAssociationReturnResourceNotFound() {+ given()+ .when()+ .get("/tags/arn:aws:codeguru-reviewer:us-east-1:000000000000:association:"+ + "00000000-0000-0000-0000-000000000000")+ .then()+ .statusCode(404)+ .body("__type", equalTo("ResourceNotFoundException"));+ }++ @Test+ @Order(14)+ void disassociateRepository() {+ given()+ .when()+ .delete("/associations/" + s3AssociationArn)+ .then()+ .statusCode(200)+ .body("RepositoryAssociation.AssociationArn", equalTo(s3AssociationArn))+ .body("RepositoryAssociation.State", equalTo("Disassociated"));++ given()+ .when()+ .get("/associations/" + s3AssociationArn)+ .then()+ .statusCode(404)+ .body("__type", equalTo("NotFoundException"));++ given()+ .when()+ .get("/associations?Name=floci-batch")+ .then()+ .statusCode(200)+ .body("RepositoryAssociationSummaries", emptyIterable());+ }++ @Test+ @Order(15)+ void describeRejectsAnArnFromAnotherService() {+ given()+ .when()+ .get("/associations/arn:aws:s3:::not-an-association")+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", containsString("association ARN"));+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex ff78af4dcf..fe0fbb1e0e 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -388,3 +388,5 @@ floci:enabled: trueram:enabled: true+ codegurureviewer:+ enabled: truediff --git a/tools/docs/service_matrix.yaml b/tools/docs/service_matrix.yamlindex b9120b003e..a97ccf5934 100644--- a/tools/docs/service_matrix.yaml+++ b/tools/docs/service_matrix.yaml@@ -28,6 +28,7 @@ aliases:logs: cloudwatch # CloudWatch Logs facet, at cloudwatch.mdmonitoring: cloudwatch # CloudWatch Metrics facet, at cloudwatch.md#metricssecretsmanager: secrets-manager+ codeguru-reviewer: codegurureviewer # SigV4 signing name is hyphenated; the doc slug is notservicecatalog: service-catalogcognito-idp: cognito # Cognito's SigV4 signing namestates: step-functions # Step Functions' SigV4 signing namediff --git a/tools/docs/services.yaml b/tools/docs/services.yamlindex 50b38802f5..1aa55e67a8 100644--- a/tools/docs/services.yaml+++ b/tools/docs/services.yaml@@ -34,6 +34,19 @@ services:doc: docs/services/cloudtrail.mdsources:- { path: src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailJsonHandler.java, mode: switch }+ - service: codegurureviewer+ doc: docs/services/codegurureviewer.md+ sources:+ - { path: src/main/java/io/github/hectorvent/floci/services/codegurureviewer/CodeGuruReviewerController.java, mode: rest }+ - { path: src/main/java/io/github/hectorvent/floci/core/common/SharedTagsController.java, mode: rest }+ rename_actions:+ ListTags: ListTagsForResource+ TagResourcePost: TagResource+ exclude_actions:+ - ListTagsByQuery+ - TagResourceByBody+ - TagResourcePut+ - UntagResourceByQuery- service: comprehenddoc: docs/services/comprehend.mdsources: