diff --git a/docs/services/lakeformation.md b/docs/services/lakeformation.md index df35db646e..6355337ee7 100644 --- a/docs/services/lakeformation.md +++ b/docs/services/lakeformation.md @@ -18,6 +18,7 @@ The `lakeformation` service allows you to manage data lake settings, resources, ### Resource Registration * `RegisterResource` +* `UpdateResource` * `DeregisterResource` * `ListResources` * `DescribeResource` diff --git a/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationController.java b/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationController.java index 2ac46c979d..fd27037fc0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationController.java +++ b/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationController.java @@ -78,6 +78,12 @@ public class LakeFormationController { return handleResponse(service.registerResource(regionResolver.resolveRegion(headers), mapper.treeToValue(parse(body), RegisterResourceRequest.class))); } + @POST + @Path("/UpdateResource") + public Response updateResource(@Context HttpHeaders headers, String body) throws Exception { + return handleResponse(service.updateResource(regionResolver.resolveRegion(headers), mapper.treeToValue(parse(body), UpdateResourceRequest.class))); + } + @POST @Path("/DeregisterResource") public Response deregisterResource(@Context HttpHeaders headers, String body) throws Exception { diff --git a/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationService.java b/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationService.java index bf28887938..c1f74192e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationService.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.lakeformation; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.services.lakeformation.model.*; import jakarta.enterprise.context.ApplicationScoped; @@ -55,6 +56,56 @@ public class LakeFormationService { return new RegisterResourceResponse(); } + public UpdateResourceResponse updateResource(String region, UpdateResourceRequest request) { + validateResourceArn(request.getResourceArn()); + validateRoleArn(request.getRoleArn()); + + storage.updateResource( + region, + request.getResourceArn(), + request.getRoleArn(), + request.getExpectedResourceOwnerAccount(), + request.getHybridAccessEnabled(), + request.getWithFederation() + ); + return new UpdateResourceResponse(); + } + + private static void validateResourceArn(String resourceArn) { + if (resourceArn == null) { + throw new AwsException("InvalidInputException", "ResourceArn is required", 400); + } + try { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(resourceArn); + if (parsed.partition().isBlank() || parsed.service().isBlank() || parsed.resource().isBlank() + || resourceArn.chars().anyMatch(Character::isWhitespace)) { + throw new IllegalArgumentException("Invalid resource ARN"); + } + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidInputException", "ResourceArn must be a valid ARN", 400); + } + } + + private static void validateRoleArn(String roleArn) { + if (roleArn == null) { + throw new AwsException("InvalidInputException", "RoleArn is required", 400); + } + try { + AwsArnUtils.Arn parsed = AwsArnUtils.parse(roleArn); + if (parsed.partition().isBlank() + || !"iam".equals(parsed.service()) + || !parsed.region().isEmpty() + || parsed.accountId().isBlank() + || !parsed.resource().startsWith("role/") + || parsed.resource().length() == "role/".length() + || roleArn.chars().anyMatch(Character::isWhitespace)) { + throw new IllegalArgumentException("Invalid IAM role ARN"); + } + } catch (IllegalArgumentException e) { + throw new AwsException("InvalidInputException", "RoleArn must be a valid IAM role ARN", 400); + } + } + public DeregisterResourceResponse deregisterResource(String region, DeregisterResourceRequest request) { if (request.getResourceArn() == null) { throw new AwsException("InvalidInputException", "ResourceArn is required", 400); diff --git a/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationStorage.java b/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationStorage.java index b42d88ad44..983fd508c1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationStorage.java +++ b/src/main/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationStorage.java @@ -10,6 +10,8 @@ public interface LakeFormationStorage { Optional getDataLakeSettings(String region, String catalogId); void registerResource(String region, String resourceArn, String roleArn, boolean useServiceLinkedRole, Boolean withFederation); + void updateResource(String region, String resourceArn, String roleArn, String expectedResourceOwnerAccount, + Boolean hybridAccessEnabled, Boolean withFederation); void deregisterResource(String region, String resourceArn); List listResources(String region, List filterConditions, Integer maxResults, String nextToken); Optional describeResource(String region, String resourceArn); diff --git a/src/main/java/io/github/hectorvent/floci/services/lakeformation/MemoryLakeFormationStorage.java b/src/main/java/io/github/hectorvent/floci/services/lakeformation/MemoryLakeFormationStorage.java index a633927ffc..cb3283afb6 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lakeformation/MemoryLakeFormationStorage.java +++ b/src/main/java/io/github/hectorvent/floci/services/lakeformation/MemoryLakeFormationStorage.java @@ -42,7 +42,7 @@ public class MemoryLakeFormationStorage implements LakeFormationStorage { } @Override - public void registerResource(String region, String resourceArn, String roleArn, boolean useServiceLinkedRole, Boolean withFederation) { + public synchronized void registerResource(String region, String resourceArn, String roleArn, boolean useServiceLinkedRole, Boolean withFederation) { ResourceInfo info = new ResourceInfo(); info.setResourceArn(resourceArn); info.setRoleArn(roleArn); @@ -52,7 +52,44 @@ public class MemoryLakeFormationStorage implements LakeFormationStorage { } @Override - public void deregisterResource(String region, String resourceArn) { + public synchronized void updateResource(String region, String resourceArn, String roleArn, String expectedResourceOwnerAccount, + Boolean hybridAccessEnabled, Boolean withFederation) { + String resourceKey = region + ":" + resourceArn; + ResourceInfo existing = resourcesStorage.get(resourceKey) + .orElseThrow(() -> new io.github.hectorvent.floci.core.common.AwsException( + "EntityNotFoundException", "Resource not found", 400)); + // Work on a defensive copy so concurrent readers (DescribeResource, ListResources) + // never observe a partially-mutated ResourceInfo: they see either the old complete + // state or the new complete state, never a mix of field values. + ResourceInfo updated = copyOf(existing); + updated.setRoleArn(roleArn); + if (expectedResourceOwnerAccount != null) { + updated.setExpectedResourceOwnerAccount(expectedResourceOwnerAccount); + } + if (hybridAccessEnabled != null) { + updated.setHybridAccessEnabled(hybridAccessEnabled); + } + if (withFederation != null) { + updated.setWithFederation(withFederation); + } + resourcesStorage.put(resourceKey, updated); + } + + private static ResourceInfo copyOf(ResourceInfo source) { + ResourceInfo copy = new ResourceInfo(); + copy.setExpectedResourceOwnerAccount(source.getExpectedResourceOwnerAccount()); + copy.setHybridAccessEnabled(source.getHybridAccessEnabled()); + copy.setLastModified(source.getLastModified()); + copy.setResourceArn(source.getResourceArn()); + copy.setRoleArn(source.getRoleArn()); + copy.setVerificationStatus(source.getVerificationStatus()); + copy.setWithFederation(source.getWithFederation()); + copy.setWithPrivilegedAccess(source.getWithPrivilegedAccess()); + return copy; + } + + @Override + public synchronized void deregisterResource(String region, String resourceArn) { resourcesStorage.delete(region + ":" + resourceArn); } diff --git a/src/main/java/io/github/hectorvent/floci/services/lakeformation/model/UpdateResourceRequest.java b/src/main/java/io/github/hectorvent/floci/services/lakeformation/model/UpdateResourceRequest.java new file mode 100644 index 0000000000..780c736911 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lakeformation/model/UpdateResourceRequest.java @@ -0,0 +1,58 @@ +package io.github.hectorvent.floci.services.lakeformation.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateResourceRequest { + + private String expectedResourceOwnerAccount; + private Boolean hybridAccessEnabled; + private String resourceArn; + private String roleArn; + private Boolean withFederation; + + public String getExpectedResourceOwnerAccount() { + return expectedResourceOwnerAccount; + } + + public void setExpectedResourceOwnerAccount(String expectedResourceOwnerAccount) { + this.expectedResourceOwnerAccount = expectedResourceOwnerAccount; + } + + public Boolean getHybridAccessEnabled() { + return hybridAccessEnabled; + } + + public void setHybridAccessEnabled(Boolean hybridAccessEnabled) { + this.hybridAccessEnabled = hybridAccessEnabled; + } + + public String getResourceArn() { + return resourceArn; + } + + public void setResourceArn(String resourceArn) { + this.resourceArn = resourceArn; + } + + public String getRoleArn() { + return roleArn; + } + + public void setRoleArn(String roleArn) { + this.roleArn = roleArn; + } + + public Boolean getWithFederation() { + return withFederation; + } + + public void setWithFederation(Boolean withFederation) { + this.withFederation = withFederation; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/lakeformation/model/UpdateResourceResponse.java b/src/main/java/io/github/hectorvent/floci/services/lakeformation/model/UpdateResourceResponse.java new file mode 100644 index 0000000000..7586f97d09 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/lakeformation/model/UpdateResourceResponse.java @@ -0,0 +1,12 @@ +package io.github.hectorvent.floci.services.lakeformation.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.PropertyNamingStrategies; +import com.fasterxml.jackson.databind.annotation.JsonNaming; +import io.quarkus.runtime.annotations.RegisterForReflection; + +@RegisterForReflection +@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class) +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateResourceResponse { +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationIntegrationTest.java index d3e9c76e11..a4925bd908 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationIntegrationTest.java @@ -279,6 +279,63 @@ class LakeFormationIntegrationTest { .body("__type", equalTo("EntityNotFoundException")); } + @Test + void updateResourcePreservesOmittedValuesAndIsRegionScoped() { + String arn = "arn:aws:s3:::update-resource-bucket"; + String initialRole = "arn:aws:iam::111122223333:role/initial"; + String updatedRole = "arn:aws:iam::111122223333:role/updated"; + String secondRegionHeader = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20201022/us-west-2/lakeformation/aws4_request, SignedHeaders=host;x-amz-date, Signature=dummy"; + + given() + .contentType(CONTENT_TYPE) + .header("Authorization", AUTH_HEADER) + .body("{\"ResourceArn\":\"" + arn + "\",\"RoleArn\":\"" + initialRole + "\",\"WithFederation\":true}") + .when() + .post("/RegisterResource") + .then() + .statusCode(200); + + given() + .contentType(CONTENT_TYPE) + .header("Authorization", secondRegionHeader) + .body("{\"ResourceArn\":\"" + arn + "\",\"RoleArn\":\"" + initialRole + "\",\"WithFederation\":false}") + .when() + .post("/RegisterResource") + .then() + .statusCode(200); + + given() + .contentType(CONTENT_TYPE) + .header("Authorization", AUTH_HEADER) + .body("{\"ResourceArn\":\"" + arn + "\",\"RoleArn\":\"" + updatedRole + "\"}") + .when() + .post("/UpdateResource") + .then() + .statusCode(200); + + given() + .contentType(CONTENT_TYPE) + .header("Authorization", AUTH_HEADER) + .body("{\"ResourceArn\":\"" + arn + "\"}") + .when() + .post("/DescribeResource") + .then() + .statusCode(200) + .body("ResourceInfo.RoleArn", equalTo(updatedRole)) + .body("ResourceInfo.WithFederation", equalTo(true)); + + given() + .contentType(CONTENT_TYPE) + .header("Authorization", secondRegionHeader) + .body("{\"ResourceArn\":\"" + arn + "\"}") + .when() + .post("/DescribeResource") + .then() + .statusCode(200) + .body("ResourceInfo.RoleArn", equalTo(initialRole)) + .body("ResourceInfo.WithFederation", equalTo(false)); + } + @Test void listAndDeleteLFTag() { // Create tag diff --git a/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationResourceRaceTest.java b/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationResourceRaceTest.java new file mode 100644 index 0000000000..b8b4966e6c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationResourceRaceTest.java @@ -0,0 +1,168 @@ +package io.github.hectorvent.floci.services.lakeformation; + +import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; +import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.lakeformation.model.ResourceInfo; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +/** + * A register racing an update for the same resource must not be silently reverted. + * + *

The update is a read-modify-write under the storage monitor: read the record, mutate it, + * write it back. A register landing between the read and the write would be overwritten by that + * write, losing the fresh registration, so the register takes the same monitor the update and + * deregister already hold. + */ +class LakeFormationResourceRaceTest { + + private static final String REGION = "us-east-1"; + private static final String RESOURCE_ARN = "arn:aws:s3:::race-bucket"; + private static final String REGISTER_ROLE = "arn:aws:iam::000000000000:role/RegisterRole"; + private static final String UPDATE_ROLE = "arn:aws:iam::000000000000:role/UpdateRole"; + + private MemoryLakeFormationStorage newStorage() { + StorageFactory storageFactory = Mockito.mock(StorageFactory.class); + when(storageFactory.create(anyString(), anyString(), any())) + .thenReturn(AccountAwareStorageBackend.inMemory("000000000000")); + return new MemoryLakeFormationStorage(storageFactory); + } + + @Test + void aRegisterRacingAnUpdateIsNeverReverted() throws Exception { + for (int attempt = 0; attempt < 50; attempt++) { + MemoryLakeFormationStorage storage = newStorage(); + + CountDownLatch start = new CountDownLatch(1); + AtomicReference unexpected = new AtomicReference<>(); + + Thread registerer = new Thread(() -> { + await(start); + try { + storage.registerResource(REGION, RESOURCE_ARN, REGISTER_ROLE, false, null); + } catch (Throwable t) { + unexpected.set(t); + } + }); + Thread updater = new Thread(() -> { + await(start); + try { + storage.updateResource(REGION, RESOURCE_ARN, UPDATE_ROLE, null, null, null); + } catch (io.github.hectorvent.floci.core.common.AwsException expected) { + if (!"EntityNotFoundException".equals(expected.getErrorCode())) { + unexpected.set(expected); + } + } catch (Throwable t) { + unexpected.set(t); + } + }); + + registerer.start(); + updater.start(); + start.countDown(); + registerer.join(TimeUnit.SECONDS.toMillis(10)); + updater.join(TimeUnit.SECONDS.toMillis(10)); + assertFalse(registerer.isAlive() || updater.isAlive(), "a thread never finished"); + assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get()); + + // The register always lands, so the resource is there. The role names the last writer: + // the register, or the update if it ran after. Anything else means a stale write + // reverted the registration. + Optional stored = storage.describeResource(REGION, RESOURCE_ARN); + assertTrue(stored.isPresent(), "the registration was lost (attempt " + attempt + ")"); + assertTrue(Set.of(REGISTER_ROLE, UPDATE_ROLE).contains(stored.get().getRoleArn()), + "unexpected role " + stored.get().getRoleArn() + " (attempt " + attempt + ")"); + } + } + + @Test + void aConcurrentDescribeNeverObservesAPartialUpdate() throws Exception { + String initialRole = "arn:aws:iam::000000000000:role/Initial"; + String updatedRole = "arn:aws:iam::000000000000:role/Updated"; + + for (int attempt = 0; attempt < 50; attempt++) { + MemoryLakeFormationStorage storage = newStorage(); + storage.registerResource(REGION, RESOURCE_ARN, initialRole, false, true); + + final int attemptNo = attempt; + CountDownLatch start = new CountDownLatch(1); + AtomicReference unexpected = new AtomicReference<>(); + AtomicInteger observations = new AtomicInteger(0); + + Thread updater = new Thread(() -> { + await(start); + try { + storage.updateResource(REGION, RESOURCE_ARN, updatedRole, null, null, false); + } catch (Throwable t) { + unexpected.set(t); + } + }); + + Thread reader = new Thread(() -> { + await(start); + try { + for (int i = 0; i < 200; i++) { + Optional info = storage.describeResource(REGION, RESOURCE_ARN); + if (info.isPresent()) { + ResourceInfo r = info.get(); + // Every observation must be a fully consistent snapshot: + // either (initialRole, federation=true) or (updatedRole, federation=false). + // A mixed state (e.g. updatedRole with federation=true) means the + // reader observed a partially-mutated object. + boolean isInitialState = updatedRole.equals(r.getRoleArn()) == false + && Boolean.TRUE.equals(r.getWithFederation()); + boolean isUpdatedState = updatedRole.equals(r.getRoleArn()) + && Boolean.FALSE.equals(r.getWithFederation()); + assertTrue(isInitialState || isUpdatedState, + "partial update observed: role=" + r.getRoleArn() + + ", withFederation=" + r.getWithFederation() + + " (attempt " + attemptNo + ")"); + observations.incrementAndGet(); + } + } + } catch (Throwable t) { + unexpected.set(t); + } + }); + + updater.start(); + reader.start(); + start.countDown(); + updater.join(TimeUnit.SECONDS.toMillis(10)); + reader.join(TimeUnit.SECONDS.toMillis(10)); + assertFalse(updater.isAlive() || reader.isAlive(), "a thread never finished"); + assertNull(unexpected.get(), () -> "unexpected failure: " + unexpected.get()); + assertTrue(observations.get() > 0, "reader never observed the resource"); + + // After the update completes, the final state must be fully consistent. + Optional stored = storage.describeResource(REGION, RESOURCE_ARN); + assertTrue(stored.isPresent()); + assertEquals(updatedRole, stored.get().getRoleArn()); + assertEquals(false, stored.get().getWithFederation()); + } + } + + private static void await(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationServiceTest.java index 93f2ffb112..1036fdbe4a 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lakeformation/LakeFormationServiceTest.java @@ -79,6 +79,58 @@ class LakeFormationServiceTest { assertEquals("InvalidInputException", ex.getErrorCode()); } + @Test + void testUpdateResource() { + UpdateResourceRequest req = new UpdateResourceRequest(); + req.setResourceArn("arn:aws:s3:::my-bucket"); + req.setRoleArn("arn:aws-us-gov:iam::123:role/UpdatedRole"); + req.setHybridAccessEnabled(true); + + UpdateResourceResponse res = service.updateResource("us-east-1", req); + + assertNotNull(res); + verify(storage).updateResource( + "us-east-1", "arn:aws:s3:::my-bucket", "arn:aws-us-gov:iam::123:role/UpdatedRole", null, true, null); + } + + @Test + void testUpdateResourceNotFound() { + UpdateResourceRequest req = new UpdateResourceRequest(); + req.setResourceArn("arn:aws:s3:::my-bucket"); + req.setRoleArn("arn:aws:iam::123:role/UpdatedRole"); + doThrow(new AwsException("EntityNotFoundException", "Resource not found", 400)) + .when(storage).updateResource(anyString(), anyString(), anyString(), any(), any(), any()); + + AwsException ex = assertThrows(AwsException.class, () -> service.updateResource("us-east-1", req)); + + assertEquals("EntityNotFoundException", ex.getErrorCode()); + verify(storage).updateResource(anyString(), anyString(), anyString(), any(), any(), any()); + } + + @Test + void testUpdateResourceRejectsInvalidRequiredArn() { + UpdateResourceRequest req = new UpdateResourceRequest(); + req.setResourceArn("not-an-arn"); + req.setRoleArn("not-an-arn"); + + AwsException ex = assertThrows(AwsException.class, () -> service.updateResource("us-east-1", req)); + + assertEquals("InvalidInputException", ex.getErrorCode()); + verifyNoInteractions(storage); + } + + @Test + void testUpdateResourceRejectsMalformedResourceArn() { + UpdateResourceRequest req = new UpdateResourceRequest(); + req.setResourceArn("arn:aws:s3"); + req.setRoleArn("arn:aws:iam::123:role/UpdatedRole"); + + AwsException ex = assertThrows(AwsException.class, () -> service.updateResource("us-east-1", req)); + + assertEquals("InvalidInputException", ex.getErrorCode()); + verifyNoInteractions(storage); + } + @Test void testDescribeResource() { DescribeResourceRequest req = new DescribeResourceRequest();