feat(lakeformation): lake formation (#2427)

* feat(lakeformation): implement Lake Formation emulator

* chore(docs): register LakeFormationJsonHandler in deferred_handlers

* fix(lakeformation): resolve code review comments

* fix(lakeformation): ensure wildcard exclusions generate distinct keys

* fix(lakeformation): include tableCatalogId in DataCellsFilter keys

* fix(lakeformation): include LF-tag values in permission identity key and add integration tests

* fix(lakeformation): configure Jackson for PascalCase and fix JSON-1.1 handler

* fix(lakeformation): escape tag values in permission key to prevent collision

* fix(lakeformation): include embedded CatalogId in permission key and fix tag value encoding collision

* fix(lakeformation): include embedded CatalogId in permission key and fix tag value encoding collision

* feat(lakeformation): migrate from JSON 1.1 dispatcher to REST JSON

- Remove LakeFormationJsonHandler and its routing in AwsJson11Controller
- Create standard JAX-RS LakeFormationController mapped to specific actions
- Update ResolvedServiceCatalog to correctly route Lake Formation requests via restProxyClasses
- Implement regional data isolation via keys prefixing region in MemoryLakeFormationStorage
- Add modeled AlreadyExistsException and EntityNotFoundException handling in LakeFormationService
- Update LakeFormationIntegrationTest to send standards-compliant HTTP POST calls to mapped endpoints

* fix(lakeformation): revoke grant options when base permission is revoked

When a permission exists in both permissions and permissionsWithGrantOption and a revoke names it only in permissions, the grant option is now properly revoked as well to prevent dangling grant options and inconsistent permission states returned to clients.

* fix(lakeformation): correct LF tag casing to match AWS wire protocol

The AWS Lake Formation API uses LFTags, LFTag, LFTagPolicy, and LFTagExpression on the wire. The Jackson PascalCase naming strategy incorrectly converted internal lfTags fields to LfTags, causing silent mapping failures (e.g. AddLFTagsToResourceRequest lost its tags, and TBAC Resource.LFTag lost its resource identity entirely).

Added explicit @JsonProperty annotations to ensure strict compliance with AWS specifications.

* fix(lakeformation): apply filters when listing resources and permissions

The list-resources and list-permissions endpoints were completely ignoring the provided filters and returning the entire in-memory storage, which violates AWS behavior and breaks Terraform synchronization (since it sees permissions of other principals).

Updated MemoryLakeFormationStorage to natively apply:
- listResources: EQUALS, NOT_EQUALS, and BEGINS_WITH for RESOURCE_ARN FilterConditions
- listPermissions: Principal identification checks and exact Resource matching

* fix(lakeformation): resolve multiple minor conformance issues

- Add @JsonInclude(NON_NULL) to all Lake Formation model classes to omit empty JSON fields from wire responses
- Validate that PermissionsWithGrantOption is a subset of Permissions in GrantPermissions
- Validate that ResourceArn starts with 'arn:' in RegisterResource
- Create AwsThrowableMapper to map generic service NPEs to standard AWS 500 InternalFailure responses
- Update index.md documentation to reflect Lake Formation's REST JSON protocol instead of JSON 1.1

* test(lakeformation): cover missing API operations and TBAC grant

Added explicit coverage for the remaining 8 Lake Formation operations to ensure all endpoints execute against the mock storage cleanly:
- RegisterResource, DescribeResource, ListResources, DeregisterResource (Resource lifecycle)
- ListLFTags, DeleteLFTag (Tag lifecycle extension)
- AddLFTagsToResource, RemoveLFTagsFromResource (Tag assignment)

Also added a dedicated TBAC round-trip test (grantAndListPermissionsTBAC) to assert that grants scoped to LFTag resources serialize correctly and are successfully retrievable via ListPermissions.

* fix(lakeformation): enforce AWS-compatible FilterCondition operators and logic

- MemoryLakeFormationStorage now correctly implements AWS's EQ and NE operator strings instead of EQUALS and NOT_EQUALS (which bots and SDKs never send).
- Unrecognized operators now throw an InvalidInputException instead of silently matching everything.
- LakeFormationService now correctly ANDs all filters in the FilterConditionList by passing the entire list to storage rather than arbitrarily dropping all but the first.
- Fixed a Quarkus JAX-RS deployment conflict where Resource Explorer 2 and Lake Formation both mapped to POST /ListResources. The conflict was resolved by rewriting Resource Explorer 2's ambiguous path at the pre-matching filter layer, allowing both services to co-exist securely.

* fix(lakeformation): enforce required inputs on GrantPermissions and handle malformed records

- Added explicit validation to GrantPermissions and RevokePermissions to ensure Principal, Resource, and Permissions are present, throwing an InvalidInputException if missing.
- Null-guarded principal and resource dereferencing in MemoryLakeFormationStorage's listPermissions filter. This prevents a malformed grant record from triggering a NullPointerException and causing a 500 InternalFailure for all subsequent list operations.

* chore(lakeformation): pin ListResources filter in tests and document intentional omissions

- Updated LakeFormationIntegrationTest.resourceLifecycle to register a second resource, strictly asserting that ListResources with an EQ filter correctly isolates and returns only the requested resource.
- Added code comments to MemoryLakeFormationStorage documenting the deliberate omission of pagination (MaxResults, NextToken) and specific optional list filters (ResourceType, IncludeRelated), clarifying the design choice for future maintainers.
- Reverted the repo-wide AwsThrowableMapper addition as it falls outside the scope of the Lake Formation protocol fixes and warrants its own dedicated review.

* chore(lakeformation): Reverted the repo-wide AwsThrowableMapper

- Reverted the repo-wide AwsThrowableMapper addition as it falls outside the scope of the Lake Formation protocol fixes and warrants its own dedicated review.

---------

Signed-off-by: NAMAN JAIN <naman.049259@tmu.ac.in>
This commit is contained in:
NAMAN JAIN authored and GitHub committed 2026-08-26 10:29:31 -04:00
1 parent e4b101d5da
commit ac6cb06af4
71 files changed
+3406 -3

No files matched your search

@@ -0,0 +1,360 @@
package io.github.hectorvent.floci.services.lakeformation;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.TestMethodOrder;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
@QuarkusTest
@TestMethodOrder(MethodOrderer.MethodName.class)
class LakeFormationIntegrationTest {
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static final String CONTENT_TYPE = "application/json";
private static final String AUTH_HEADER = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20201022/us-east-1/lakeformation/aws4_request, SignedHeaders=host;x-amz-date, Signature=dummy";
@Test
void putAndGetDataLakeSettings() {
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"DataLakeSettings\":{\"DataLakeAdmins\":[{\"DataLakePrincipalIdentifier\":\"arn:aws:iam::111122223333:user/admin\"}]}}")
.when()
.post("/PutDataLakeSettings")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/GetDataLakeSettings")
.then()
.statusCode(200)
.body("DataLakeSettings.DataLakeAdmins[0].DataLakePrincipalIdentifier", equalTo("arn:aws:iam::111122223333:user/admin"));
}
@Test
void createAndGetLFTag() {
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"department\",\"TagValues\":[\"sales\",\"engineering\"]}")
.when()
.post("/CreateLFTag")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"department\"}")
.when()
.post("/GetLFTag")
.then()
.statusCode(200)
.body("TagKey", equalTo("department"))
.body("TagValues", containsInAnyOrder("sales", "engineering"));
}
@Test
void updateLFTag() {
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"department2\",\"TagValues\":[\"sales\"]}")
.when()
.post("/CreateLFTag")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"department2\",\"TagValuesToAdd\":[\"marketing\"],\"TagValuesToDelete\":[\"sales\"]}")
.when()
.post("/UpdateLFTag")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"department2\"}")
.when()
.post("/GetLFTag")
.then()
.statusCode(200)
.body("TagKey", equalTo("department2"))
.body("TagValues", contains("marketing"));
}
@Test
void grantAndListPermissions() {
String grantBody = "{"
+ "\"Principal\":{\"DataLakePrincipalIdentifier\":\"arn:aws:iam::111122223333:role/my-role\"},"
+ "\"Resource\":{\"Table\":{\"DatabaseName\":\"default\",\"Name\":\"my-table\"}},"
+ "\"Permissions\":[\"SELECT\",\"INSERT\"]"
+ "}";
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body(grantBody)
.when()
.post("/GrantPermissions")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/ListPermissions")
.then()
.statusCode(200)
.body("PrincipalResourcePermissions[0].Principal.DataLakePrincipalIdentifier", equalTo("arn:aws:iam::111122223333:role/my-role"))
.body("PrincipalResourcePermissions[0].Resource.Table.DatabaseName", equalTo("default"))
.body("PrincipalResourcePermissions[0].Resource.Table.Name", equalTo("my-table"))
.body("PrincipalResourcePermissions[0].Permissions", containsInAnyOrder("SELECT", "INSERT"));
}
@Test
void revokePermissions() {
String grantBody = "{"
+ "\"Principal\":{\"DataLakePrincipalIdentifier\":\"arn:aws:iam::111122223333:role/my-role\"},"
+ "\"Resource\":{\"Table\":{\"DatabaseName\":\"default\",\"Name\":\"my-table\"}},"
+ "\"Permissions\":[\"SELECT\",\"INSERT\"]"
+ "}";
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body(grantBody)
.when()
.post("/GrantPermissions")
.then()
.statusCode(200);
String revokeBody = "{"
+ "\"Principal\":{\"DataLakePrincipalIdentifier\":\"arn:aws:iam::111122223333:role/my-role\"},"
+ "\"Resource\":{\"Table\":{\"DatabaseName\":\"default\",\"Name\":\"my-table\"}},"
+ "\"Permissions\":[\"INSERT\"]"
+ "}";
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body(revokeBody)
.when()
.post("/RevokePermissions")
.then()
.statusCode(200);
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/ListPermissions")
.then()
.statusCode(200)
.body("PrincipalResourcePermissions[0].Permissions", contains("SELECT"));
}
@Test
void grantAndListPermissionsTBAC() {
String grantBody = "{"
+ "\"Principal\":{\"DataLakePrincipalIdentifier\":\"arn:aws:iam::111122223333:role/tbac\"},"
+ "\"Resource\":{\"LFTag\":{\"CatalogId\":\"111122223333\",\"TagKey\":\"env\",\"TagValues\":[\"dev\"]}},"
+ "\"Permissions\":[\"ASSOCIATE\"]"
+ "}";
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body(grantBody)
.when()
.post("/GrantPermissions")
.then()
.statusCode(200);
String listBody = "{"
+ "\"Principal\":{\"DataLakePrincipalIdentifier\":\"arn:aws:iam::111122223333:role/tbac\"}"
+ "}";
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body(listBody)
.when()
.post("/ListPermissions")
.then()
.statusCode(200)
.body("PrincipalResourcePermissions[0].Resource.LFTag.TagKey", equalTo("env"))
.body("PrincipalResourcePermissions[0].Resource.LFTag.TagValues", contains("dev"))
.body("PrincipalResourcePermissions[0].Permissions", contains("ASSOCIATE"));
}
@Test
void resourceLifecycle() {
String arn = "arn:aws:s3:::my-lake-bucket";
String arn2 = "arn:aws:s3:::my-other-lake-bucket";
// Register first
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\":\"" + arn + "\",\"RoleArn\":\"arn:aws:iam::111122223333:role/s3-role\",\"UseServiceLinkedRole\":true}")
.when()
.post("/RegisterResource")
.then()
.statusCode(200);
// Register second
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\":\"" + arn2 + "\",\"RoleArn\":\"arn:aws:iam::111122223333:role/s3-role\",\"UseServiceLinkedRole\":true}")
.when()
.post("/RegisterResource")
.then()
.statusCode(200);
// Describe first
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\":\"" + arn + "\"}")
.when()
.post("/DescribeResource")
.then()
.statusCode(200)
.body("ResourceInfo.ResourceArn", equalTo(arn));
// List with filter (should only return the first resource)
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"FilterConditionList\":[{\"Field\":\"RESOURCE_ARN\",\"ComparisonOperator\":\"EQ\",\"StringValueList\":[\"" + arn + "\"]}]}")
.when()
.post("/ListResources")
.then()
.statusCode(200)
.body("ResourceInfoList", hasSize(1))
.body("ResourceInfoList[0].ResourceArn", equalTo(arn));
// Deregister
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\":\"" + arn + "\"}")
.when()
.post("/DeregisterResource")
.then()
.statusCode(200);
// Describe should fail now
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"ResourceArn\":\"" + arn + "\"}")
.when()
.post("/DescribeResource")
.then()
.statusCode(400)
.body("__type", equalTo("EntityNotFoundException"));
}
@Test
void listAndDeleteLFTag() {
// Create tag
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"project\",\"TagValues\":[\"apollo\"]}")
.when()
.post("/CreateLFTag")
.then()
.statusCode(200);
// List
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{}")
.when()
.post("/ListLFTags")
.then()
.statusCode(200)
.body("LFTags.TagKey", hasItem("project"));
// Delete
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"project\"}")
.when()
.post("/DeleteLFTag")
.then()
.statusCode(200);
// Get should fail
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"project\"}")
.when()
.post("/GetLFTag")
.then()
.statusCode(400)
.body("__type", equalTo("EntityNotFoundException"));
}
@Test
void addAndRemoveLFTagsFromResource() {
String arn = "arn:aws:s3:::my-tagged-bucket";
// Create tag
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"TagKey\":\"classification\",\"TagValues\":[\"confidential\"]}")
.when()
.post("/CreateLFTag")
.then()
.statusCode(200);
// Add to resource
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"Resource\":{\"DataLocation\":{\"ResourceArn\":\"" + arn + "\"}},\"LFTags\":[{\"TagKey\":\"classification\",\"TagValues\":[\"confidential\"]}]}")
.when()
.post("/AddLFTagsToResource")
.then()
.statusCode(200);
// Remove from resource
given()
.contentType(CONTENT_TYPE)
.header("Authorization", AUTH_HEADER)
.body("{\"Resource\":{\"DataLocation\":{\"ResourceArn\":\"" + arn + "\"}},\"LFTags\":[{\"TagKey\":\"classification\",\"TagValues\":[\"confidential\"]}]}")
.when()
.post("/RemoveLFTagsFromResource")
.then()
.statusCode(200);
}
}
@@ -0,0 +1,146 @@
package io.github.hectorvent.floci.services.lakeformation;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.lakeformation.model.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class LakeFormationServiceTest {
@Mock
private LakeFormationStorage storage;
@Mock
private RegionResolver regionResolver;
private LakeFormationService service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
when(regionResolver.getAccountId()).thenReturn("123456789012");
service = new LakeFormationService(storage, regionResolver);
}
@Test
void testPutDataLakeSettings() {
PutDataLakeSettingsRequest req = new PutDataLakeSettingsRequest();
req.setCatalogId("custom-catalog");
DataLakeSettings settings = new DataLakeSettings();
req.setDataLakeSettings(settings);
PutDataLakeSettingsResponse res = service.putDataLakeSettings("us-east-1", req);
assertNotNull(res);
verify(storage).putDataLakeSettings("us-east-1", "custom-catalog", settings);
}
@Test
void testRegisterResource() {
RegisterResourceRequest req = new RegisterResourceRequest();
req.setResourceArn("arn:aws:s3:::my-bucket");
req.setRoleArn("arn:aws:iam::123:role/MyRole");
req.setUseServiceLinkedRole(true);
when(storage.describeResource(anyString(), anyString())).thenReturn(Optional.empty());
RegisterResourceResponse res = service.registerResource("us-east-1", req);
assertNotNull(res);
verify(storage).registerResource("us-east-1", "arn:aws:s3:::my-bucket", "arn:aws:iam::123:role/MyRole", true, null);
}
@Test
void testRegisterResourceAlreadyExists() {
RegisterResourceRequest req = new RegisterResourceRequest();
req.setResourceArn("arn:aws:s3:::my-bucket");
when(storage.describeResource("us-east-1", "arn:aws:s3:::my-bucket")).thenReturn(Optional.of(new ResourceInfo()));
AwsException ex = assertThrows(AwsException.class, () -> service.registerResource("us-east-1", req));
assertEquals("AlreadyExistsException", ex.getErrorCode());
}
@Test
void testRegisterResourceMissingArn() {
RegisterResourceRequest req = new RegisterResourceRequest();
AwsException ex = assertThrows(AwsException.class, () -> service.registerResource("us-east-1", req));
assertEquals("InvalidInputException", ex.getErrorCode());
}
@Test
void testDescribeResource() {
DescribeResourceRequest req = new DescribeResourceRequest();
req.setResourceArn("arn:aws:s3:::my-bucket");
ResourceInfo info = new ResourceInfo();
info.setResourceArn("arn:aws:s3:::my-bucket");
when(storage.describeResource("us-east-1", "arn:aws:s3:::my-bucket")).thenReturn(Optional.of(info));
DescribeResourceResponse res = service.describeResource("us-east-1", req);
assertNotNull(res.getResourceInfo());
assertEquals("arn:aws:s3:::my-bucket", res.getResourceInfo().getResourceArn());
}
@Test
void testDescribeResourceNotFound() {
DescribeResourceRequest req = new DescribeResourceRequest();
req.setResourceArn("arn:aws:s3:::my-bucket");
when(storage.describeResource(anyString(), anyString())).thenReturn(Optional.empty());
AwsException ex = assertThrows(AwsException.class, () -> service.describeResource("us-east-1", req));
assertEquals("EntityNotFoundException", ex.getErrorCode());
}
@Test
void testCreateLFTag() {
CreateLFTagRequest req = new CreateLFTagRequest();
req.setTagKey("my-tag");
req.setTagValues(List.of("val1", "val2"));
when(storage.getLFTag(anyString(), anyString(), anyString())).thenReturn(Optional.empty());
CreateLFTagResponse res = service.createLFTag("us-east-1", req);
assertNotNull(res);
verify(storage).createLFTag("us-east-1", "123456789012", "my-tag", List.of("val1", "val2"));
}
@Test
void testCreateLFTagAlreadyExists() {
CreateLFTagRequest req = new CreateLFTagRequest();
req.setTagKey("my-tag");
req.setTagValues(List.of("val1"));
when(storage.getLFTag("us-east-1", "123456789012", "my-tag")).thenReturn(Optional.of(new LFTag()));
AwsException ex = assertThrows(AwsException.class, () -> service.createLFTag("us-east-1", req));
assertEquals("AlreadyExistsException", ex.getErrorCode());
}
@Test
void testGetLFTag() {
GetLFTagRequest req = new GetLFTagRequest();
req.setTagKey("my-tag");
LFTag tag = new LFTag();
tag.setTagKey("my-tag");
tag.setTagValues(List.of("val1"));
when(storage.getLFTag("us-east-1", "123456789012", "my-tag")).thenReturn(Optional.of(tag));
GetLFTagResponse res = service.getLFTag("us-east-1", req);
assertEquals("123456789012", res.getCatalogId());
assertEquals("my-tag", res.getTagKey());
assertEquals(List.of("val1"), res.getTagValues());
}
}