Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#14887] test(client): Verify Domain SDKs end to end (#14888)

Jerry Shao6be32b5cb10b
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/DomainAuthorizationIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/DomainAuthorizationIT.java
new file mode 100644
index 0000000000..2739783da5
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/DomainAuthorizationIT.java
@@ -0,0 +1,502 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.client.integration.test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.Privilege;
+import org.apache.gravitino.authorization.Privileges;
+import org.apache.gravitino.authorization.SecurableObject;
+import org.apache.gravitino.authorization.SecurableObjects;
+import org.apache.gravitino.client.GravitinoAdminClient;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainChange;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.domain.DomainMemberFilter;
+import org.apache.gravitino.domain.DomainRelation;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
+import org.apache.gravitino.exceptions.ForbiddenException;
+import org.apache.gravitino.exceptions.NoSuchDomainException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.gravitino.tag.TagValue;
+import org.junit.jupiter.api.Test;
+
+/** SDK tests with simple authentication, real owners, role grants, denies and Casbin. */
+public class DomainAuthorizationIT extends DomainIT {
+ /** {@inheritDoc} */
+ @Override
+ protected boolean authorizationEnabled() {
+ return true;
+ }
+
+ @Test
+ void testVisibilityInheritedPermissionsAndDenyPrecedence() {
+ Domain parent =
+ metalake.createDomain("Parent/auth. scope", null, null, TagValue.noValue("parent"), true);
+ Domain child =
+ parent.createSubdomain("Child/auth. scope", null, null, TagValue.noValue("child"), true);
+ for (String user : List.of("reader", "manager", "outsider", "owner", "lake_manager")) {
+ metalake.addUser(user);
+ }
+
+ // Grant only parent scopes so the child must inherit its permissions.
+ grant("reader", List.of(scope(parent.name(), Privileges.UseDomain.allow())));
+ grant("manager", List.of(scope(parent.name(), Privileges.ManageDomain.allow())));
+ try (GravitinoAdminClient readerClient = userClient("reader");
+ GravitinoAdminClient managerClient = userClient("manager");
+ GravitinoAdminClient outsiderClient = userClient("outsider");
+ GravitinoAdminClient ownerClient = userClient("owner");
+ GravitinoAdminClient inheritedClient = userClient("lake_manager")) {
+ GravitinoMetalake reader = readerClient.loadMetalake(metalake.name());
+ GravitinoMetalake manager = managerClient.loadMetalake(metalake.name());
+ GravitinoMetalake outsider = outsiderClient.loadMetalake(metalake.name());
+
+ // Drafts are hidden from readers but visible to inherited managers.
+ assertEquals(0, reader.listDomains().length);
+ assertThrows(NoSuchDomainException.class, () -> reader.getDomain(parent.name()));
+ assertEquals(child.name(), manager.getDomain(child.name()).name());
+
+ // Publication changes visibility independently for the parent and child.
+ manager.getDomain(parent.name()).publish();
+ assertEquals(Set.of(parent.name()), Set.of(reader.listDomains()));
+ assertThrows(NoSuchDomainException.class, () -> reader.getDomain(child.name()));
+ manager.getDomain(child.name()).publish();
+ assertEquals(Set.of(parent.name(), child.name()), Set.of(reader.listDomains()));
+ assertEquals(0, outsider.listDomains().length);
+ assertThrows(ForbiddenException.class, () -> outsider.getDomain(parent.name()));
+ assertThrows(ForbiddenException.class, () -> reader.getDomain(parent.name()).unpublish());
+
+ // A child deny takes precedence over an allow inherited from the parent.
+ grant("reader", List.of(scope(child.name(), Privileges.UseDomain.deny())));
+ assertEquals(Set.of(parent.name()), Set.of(reader.listDomains()));
+ assertThrows(ForbiddenException.class, () -> reader.getDomain(child.name()));
+
+ // Owners bypass denies; metalake grants also apply throughout the domain hierarchy.
+ metalake.setOwner(
+ MetadataObjects.of(null, parent.name(), MetadataObject.Type.DOMAIN),
+ "owner",
+ Owner.Type.USER);
+ grant(
+ "owner",
+ List.of(
+ scope(child.name(), Privileges.UseDomain.deny(), Privileges.ManageDomain.deny())));
+ GravitinoMetalake owner = ownerClient.loadMetalake(metalake.name());
+ assertEquals(child.name(), owner.getDomain(child.name()).name());
+ assertEquals(Domain.Status.DRAFT, owner.getDomain(child.name()).unpublish().status());
+ grant(
+ "lake_manager",
+ List.of(
+ SecurableObjects.ofMetalake(
+ metalake.name(), List.of(Privileges.ManageDomain.allow()))));
+ assertEquals(
+ child.name(),
+ inheritedClient.loadMetalake(metalake.name()).getDomain(child.name()).name());
+ }
+ }
+
+ @Test
+ void testBackingTagOwnershipAndCreationPermissions() {
+ metalake.addUser("creator");
+ grant(
+ "creator",
+ List.of(
+ SecurableObjects.ofMetalake(
+ metalake.name(), List.of(Privileges.ManageDomain.allow()))));
+ try (GravitinoAdminClient creatorClient = userClient("creator")) {
+ GravitinoMetalake creator = creatorClient.loadMetalake(metalake.name());
+ assertThrows(
+ ForbiddenException.class,
+ () -> creator.createDomain("denied", null, null, TagValue.noValue("new tag"), true));
+
+ // Creating a backing tag needs CREATE_TAG in addition to domain management.
+ grant(
+ "creator",
+ List.of(
+ SecurableObjects.ofMetalake(metalake.name(), List.of(Privileges.CreateTag.allow()))));
+ Domain created =
+ creator.createDomain("created", null, null, TagValue.noValue("owned tag"), true);
+
+ // Domain management does not grant ownership of an unrelated tag.
+ metalake.createTag("foreign tag", null, Collections.emptyMap());
+ assertThrows(
+ ForbiddenException.class,
+ () -> created.updateBackingTag(TagValue.noValue("foreign tag")));
+ assertThrows(
+ ForbiddenException.class,
+ () ->
+ creator.createDomain("foreign", null, null, TagValue.noValue("foreign tag"), false));
+
+ metalake.setOwner(
+ MetadataObjects.of(null, "foreign tag", MetadataObject.Type.TAG),
+ "creator",
+ Owner.Type.USER);
+ Domain bound =
+ creator.createDomain("bound", null, null, TagValue.noValue("foreign tag"), false);
+ assertEquals(TagValue.noValue("foreign tag"), bound.backingTag().orElseThrow());
+ assertTrue(bound.updateBackingTag(null).backingTag().isEmpty());
+ created.updateBackingTag(TagValue.noValue("foreign tag"));
+ assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ creator.createDomain("conflict", null, null, TagValue.noValue("foreign tag"), false));
+ }
+ }
+
+ @Test
+ void testMemberAccessWithoutTagPrivilegesAndHiddenSubdomains() {
+ Catalog catalog = createRelationalCatalog();
+ Column[] columns = {Column.of("id", Types.LongType.get())};
+ Table table =
+ catalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of("schema", "orders"), columns, "", Collections.emptyMap());
+ catalog
+ .asTableCatalog()
+ .createTable(NameIdentifier.of("schema", "hidden"), columns, "", Collections.emptyMap());
+ Domain parent =
+ metalake.createDomain("access parent", null, null, TagValue.noValue("parent tag"), true);
+ Domain child =
+ parent.createSubdomain("access child", null, null, TagValue.noValue("child tag"), true);
+ parent.publish();
+ catalog
+ .asSchemas()
+ .loadSchema("schema")
+ .supportsTags()
+ .associateTags(new String[] {"parent tag"}, new String[0]);
+ table.supportsTags().associateTags(new String[] {"child tag"}, new String[0]);
+
+ // Give access to one leaf object without granting any tag privileges.
+ metalake.addUser("object_reader");
+ SecurableObject catalogScope =
+ SecurableObjects.ofCatalog("ice", List.of(Privileges.UseCatalog.allow()));
+ SecurableObject schemaScope =
+ SecurableObjects.ofSchema(
+ SecurableObjects.ofCatalog("ice", Collections.emptyList()),
+ "schema",
+ List.of(Privileges.UseSchema.allow()));
+ SecurableObject tableScope =
+ SecurableObjects.ofTable(schemaScope, "orders", List.of(Privileges.SelectTable.allow()));
+ grant(
+ "object_reader",
+ List.of(
+ scope(parent.name(), Privileges.UseDomain.allow()),
+ catalogScope,
+ schemaScope,
+ tableScope));
+ try (GravitinoAdminClient readerClient = userClient("object_reader")) {
+ GravitinoMetalake reader = readerClient.loadMetalake(metalake.name());
+ DomainMember[] visible =
+ reader.getDomain(parent.name()).listMembers(DomainMemberFilter.builder().build());
+ assertEquals(1, visible.length);
+ assertEquals("ice.schema.orders", visible[0].object().fullName());
+ assertEquals(DomainRelation.Type.INHERITED, visible[0].relations()[0].type());
+ assertEquals(1, visible[0].relations().length);
+ assertEquals("ice.schema", visible[0].relations()[0].source().orElseThrow().fullName());
+ assertEquals(0, reader.getDomain(parent.name()).listSubdomains().length);
+ assertEquals(0, reader.getDomain(parent.name()).listSubdomainsInfo().length);
+ assertEquals(1, reader.listDomainsInfo().length);
+ assertEquals(
+ 0,
+ reader
+ .getDomain(parent.name())
+ .listMembers(DomainMemberFilter.builder().withDomains(child.name()).build())
+ .length);
+
+ // The draft child must not contribute a roll-up relation before publication.
+ child.publish();
+ visible = reader.getDomain(parent.name()).listMembers(DomainMemberFilter.builder().build());
+ assertEquals(
+ Set.of(DomainRelation.Type.INHERITED, DomainRelation.Type.VIA_SUBDOMAIN),
+ Arrays.stream(visible[0].relations())
+ .map(DomainRelation::type)
+ .collect(Collectors.toSet()));
+ Table readerTable =
+ reader
+ .loadCatalog("ice")
+ .asTableCatalog()
+ .loadTable(NameIdentifier.of("schema", "orders"));
+ assertEquals(
+ Set.of(parent.name(), child.name()), Set.of(readerTable.supportsDomains().listDomains()));
+
+ // A visible object's hidden child relation must disappear without hiding parent membership.
+ grant("object_reader", List.of(scope(child.name(), Privileges.UseDomain.deny())));
+ DomainMember[] parentOnly =
+ reader.getDomain(parent.name()).listMembers(DomainMemberFilter.builder().build());
+ assertEquals(1, parentOnly.length);
+ assertEquals(1, parentOnly[0].relations().length);
+ assertEquals(DomainRelation.Type.INHERITED, parentOnly[0].relations()[0].type());
+ assertEquals(Set.of(parent.name()), Set.of(readerTable.supportsDomains().listDomains()));
+ assertEquals(1, readerTable.supportsDomains().listDomainsInfo()[0].relations().length);
+
+ // A table deny removes the member and blocks reverse lookup even with USE_DOMAIN.
+ grant(
+ "object_reader",
+ List.of(
+ SecurableObjects.ofTable(
+ schemaScope, "orders", List.of(Privileges.SelectTable.deny()))));
+ assertEquals(
+ 0,
+ reader.getDomain(parent.name()).listMembers(DomainMemberFilter.builder().build()).length);
+ assertThrows(ForbiddenException.class, () -> readerTable.supportsDomains().listDomains());
+ }
+ }
+
+ @Test
+ void testMoveReevaluatesParentGrantsAndMetalakeOwnership() {
+ Domain first =
+ metalake.createDomain("first", null, null, TagValue.noValue("first tag"), true).publish();
+ Domain second =
+ metalake.createDomain("second", null, null, TagValue.noValue("second tag"), true).publish();
+ Domain child =
+ first
+ .createSubdomain("moving/child. name", null, null, TagValue.noValue("moving tag"), true)
+ .publish();
+ metalake.addUser("moving_manager");
+ metalake.addUser("lake_owner");
+ grant("moving_manager", List.of(scope(first.name(), Privileges.ManageDomain.allow())));
+ try (GravitinoAdminClient managerClient = userClient("moving_manager");
+ GravitinoAdminClient ownerClient = userClient("lake_owner")) {
+ GravitinoMetalake manager = managerClient.loadMetalake(metalake.name());
+ Domain snapshot = manager.getDomain(child.name());
+ assertThrows(ForbiddenException.class, () -> snapshot.attachToParent(second.name()));
+
+ // A stale snapshot must use current parent grants, rather than its loaded parent.
+ child.attachToParent(second.name());
+ assertThrows(ForbiddenException.class, snapshot::unpublish);
+
+ grant("moving_manager", List.of(scope(second.name(), Privileges.ManageDomain.allow())));
+ assertEquals(Domain.Status.DRAFT, snapshot.unpublish().status());
+ assertEquals(first.name(), snapshot.parent().orElseThrow());
+
+ grant("moving_manager", List.of(scope(child.name(), Privileges.ManageDomain.deny())));
+ assertThrows(NoSuchDomainException.class, () -> manager.getDomain(child.name()));
+ grant(
+ "lake_owner",
+ List.of(
+ scope(child.name(), Privileges.ManageDomain.deny(), Privileges.UseDomain.deny())));
+
+ // Restore ownership on failure too, so teardown can still remove the metalake.
+ MetadataObject root = MetadataObjects.of(null, metalake.name(), MetadataObject.Type.METALAKE);
+ metalake.setOwner(root, "lake_owner", Owner.Type.USER);
+ GravitinoMetalake owner = ownerClient.loadMetalake(metalake.name());
+ try {
+ assertEquals(child.name(), owner.getDomain(child.name()).name());
+ } finally {
+ owner.setOwner(root, "anonymous", Owner.Type.USER);
+ }
+ }
+ }
+
+ @Test
+ void testWriteEndpointsRejectReadersAndExplicitManagementDenies() {
+ Domain parent =
+ metalake
+ .createDomain("matrix-parent", null, null, TagValue.noValue("matrix-parent-tag"), true)
+ .publish();
+ Domain child =
+ parent
+ .createSubdomain("matrix-child", null, null, TagValue.noValue("matrix-child-tag"), true)
+ .publish();
+ Domain target =
+ metalake
+ .createDomain("matrix-target", null, null, TagValue.noValue("matrix-target-tag"), true)
+ .publish();
+
+ Domain creationParent =
+ metalake
+ .createDomain(
+ "creation-parent", null, null, TagValue.noValue("creation-parent-tag"), true)
+ .publish();
+
+ for (String user : List.of("matrix_reader", "matrix_denied")) {
+ metalake.addUser(user);
+ grant(
+ user,
+ List.of(
+ SecurableObjects.ofMetalake(
+ metalake.name(),
+ List.of(Privileges.UseDomain.allow(), Privileges.CreateTag.allow()))));
+ if (user.equals("matrix_denied")) {
+ grant(
+ user,
+ List.of(
+ SecurableObjects.ofMetalake(
+ metalake.name(), List.of(Privileges.ManageDomain.allow())),
+ scope(child.name(), Privileges.ManageDomain.deny()),
+ scope(creationParent.name(), Privileges.ManageDomain.deny())));
+ }
+
+ try (GravitinoAdminClient userClient = userClient(user)) {
+ GravitinoMetalake reader = userClient.loadMetalake(metalake.name());
+ Domain snapshot = reader.getDomain(child.name());
+ // USE_DOMAIN keeps reads available even when management is explicitly denied.
+ assertEquals(child.name(), snapshot.name());
+ assertEquals(0, snapshot.listMembers(DomainMemberFilter.builder().build()).length);
+ assertEquals(0, snapshot.listSubdomains().length);
+ assertEquals(0, snapshot.listSubdomainsInfo().length);
+ assertThrows(
+ ForbiddenException.class,
+ () -> reader.alterDomain(child.name(), DomainChange.updateComment("denied")),
+ user);
+ assertThrows(ForbiddenException.class, () -> reader.deleteDomain(child.name()), user);
+ assertThrows(ForbiddenException.class, snapshot::publish, user);
+ assertThrows(ForbiddenException.class, snapshot::unpublish, user);
+ assertThrows(ForbiddenException.class, () -> snapshot.attachToParent(target.name()), user);
+ assertThrows(ForbiddenException.class, snapshot::detachFromParent, user);
+ assertThrows(ForbiddenException.class, () -> snapshot.updateBackingTag(null), user);
+ assertThrows(
+ ForbiddenException.class,
+ () ->
+ reader
+ .getDomain(creationParent.name())
+ .createSubdomain(
+ "denied-subdomain", null, null, TagValue.noValue("denied-tag"), true),
+ user);
+ if (user.equals("matrix_reader")) {
+ assertThrows(
+ ForbiddenException.class,
+ () ->
+ reader.createDomain(
+ "denied-domain", null, null, TagValue.noValue("denied-create-tag"), true));
+ }
+ }
+
+ // Every rejected write leaves the original state intact, with cache enabled.
+ Domain unchanged = metalake.getDomain(child.name());
+ assertEquals(Domain.Status.PUBLISHED, unchanged.status());
+ assertEquals(parent.name(), unchanged.parent().orElseThrow());
+ assertEquals(child.backingTag(), unchanged.backingTag());
+ assertEquals(child.comment(), unchanged.comment());
+ assertEquals(Set.of(child.name()), Set.of(parent.listSubdomains()));
+ assertEquals(0, creationParent.listSubdomains().length);
+ for (String name : List.of("denied-subdomain", "denied-domain")) {
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain(name));
+ }
+ for (String name : List.of("denied-tag", "denied-create-tag")) {
+ assertThrows(NoSuchTagException.class, () -> metalake.getTag(name));
+ }
+ }
+ }
+
+ @Test
+ void testNonOwnerManagerCanUseWriteEndpoints() {
+ Domain parent =
+ metalake
+ .createDomain(
+ "allowed-parent", null, null, TagValue.noValue("allowed-parent-tag"), true)
+ .publish();
+ Domain target =
+ metalake
+ .createDomain(
+ "allowed-target", null, null, TagValue.noValue("allowed-target-tag"), true)
+ .publish();
+ Domain child =
+ parent
+ .createSubdomain(
+ "allowed-child", null, null, TagValue.noValue("allowed-child-tag"), true)
+ .publish();
+ Domain creationParent =
+ metalake
+ .createDomain(
+ "allowed-creation-parent",
+ null,
+ null,
+ TagValue.noValue("allowed-creation-parent-tag"),
+ true)
+ .publish();
+ metalake.addUser("allowed_manager");
+ grant(
+ "allowed_manager",
+ List.of(
+ SecurableObjects.ofMetalake(
+ metalake.name(),
+ List.of(Privileges.ManageDomain.allow(), Privileges.CreateTag.allow()))));
+
+ // The domain stays owned by the admin; only the replacement tag belongs to the manager.
+ metalake.createTag("manager-binding-tag", null, Collections.emptyMap());
+ metalake.setOwner(
+ MetadataObjects.of(null, "manager-binding-tag", MetadataObject.Type.TAG),
+ "allowed_manager",
+ Owner.Type.USER);
+ try (GravitinoAdminClient managerClient = userClient("allowed_manager")) {
+ GravitinoMetalake manager = managerClient.loadMetalake(metalake.name());
+ Domain managed = manager.getDomain(child.name());
+ assertEquals(
+ "managed",
+ manager.alterDomain(child.name(), DomainChange.updateComment("managed")).comment());
+ assertEquals(Domain.Status.DRAFT, managed.unpublish().status());
+ assertEquals(Domain.Status.PUBLISHED, managed.publish().status());
+ assertEquals(target.name(), managed.attachToParent(target.name()).parent().orElseThrow());
+ assertTrue(managed.detachFromParent().parent().isEmpty());
+ assertEquals(
+ TagValue.noValue("manager-binding-tag"),
+ managed
+ .updateBackingTag(TagValue.noValue("manager-binding-tag"))
+ .backingTag()
+ .orElseThrow());
+ assertTrue(managed.updateBackingTag(null).backingTag().isEmpty());
+
+ // Legal creation requests also succeed when both management and tag creation are allowed.
+ Domain created =
+ manager.createDomain(
+ "denied-domain", null, null, TagValue.noValue("denied-create-tag"), true);
+ Domain subdomain =
+ manager
+ .getDomain(creationParent.name())
+ .createSubdomain(
+ "denied-subdomain", null, null, TagValue.noValue("denied-tag"), true);
+ assertEquals(creationParent.name(), subdomain.parent().orElseThrow());
+ assertEquals(created.name(), manager.getDomain(created.name()).name());
+ assertTrue(manager.deleteDomain(child.name()));
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain(child.name()));
+ }
+ }
+
+ private GravitinoAdminClient userClient(String user) {
+ return GravitinoAdminClient.builder(serverUri).withSimpleAuth(user).build();
+ }
+
+ private void grant(String user, List<SecurableObject> objects) {
+ String role = "role_" + UUID.randomUUID().toString().replace("-", "");
+ metalake.createRole(role, Collections.emptyMap(), objects);
+ metalake.grantRolesToUser(List.of(role), user);
+ }
+
+ private static SecurableObject scope(String name, Privilege... privileges) {
+ return SecurableObjects.parse(name, MetadataObject.Type.DOMAIN, List.of(privileges));
+ }
+}
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/DomainIT.java b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/DomainIT.java
new file mode 100644
index 0000000000..ae84b998f8
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/integration/test/DomainIT.java
@@ -0,0 +1,1025 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.client.integration.test;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpServer;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.gravitino.Catalog;
+import org.apache.gravitino.Configs;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.client.GravitinoAdminClient;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.domain.Domain;
+import org.apache.gravitino.domain.DomainChange;
+import org.apache.gravitino.domain.DomainMember;
+import org.apache.gravitino.domain.DomainMemberFilter;
+import org.apache.gravitino.domain.DomainRelation;
+import org.apache.gravitino.exceptions.BackingTagAlreadyBoundException;
+import org.apache.gravitino.exceptions.DomainAlreadyExistsException;
+import org.apache.gravitino.exceptions.NoSuchDomainException;
+import org.apache.gravitino.exceptions.NoSuchTagException;
+import org.apache.gravitino.exceptions.NonEmptyDomainException;
+import org.apache.gravitino.exceptions.TagAlreadyExistsException;
+import org.apache.gravitino.file.Fileset;
+import org.apache.gravitino.integration.test.util.BaseIT;
+import org.apache.gravitino.model.Model;
+import org.apache.gravitino.rel.Column;
+import org.apache.gravitino.rel.SQLRepresentation;
+import org.apache.gravitino.rel.Table;
+import org.apache.gravitino.rel.View;
+import org.apache.gravitino.rel.types.Types;
+import org.apache.gravitino.semantic.Dataset;
+import org.apache.gravitino.semantic.SemanticModel;
+import org.apache.gravitino.semantic.SemanticModelDefinition;
+import org.apache.gravitino.tag.TagChange;
+import org.apache.gravitino.tag.TagValue;
+import org.apache.gravitino.tag.TagValueConstraint;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/**
+ * Real-server Domain SDK tests using the metadata backend selected by {@code jdbcBackend}.
+ *
+ * <p>Backend provisioning and server lifecycle follow {@link BaseIT}, including MySQL and
+ * PostgreSQL.
+ */
+public class DomainIT extends BaseIT {
+ private String metalakeName;
+ /** The test metalake, owned by the explicitly authenticated service admin. */
+ protected GravitinoMetalake metalake;
+
+ @TempDir Path directory;
+
+ /** {@inheritDoc} */
+ @Override
+ @BeforeAll
+ public void startIntegrationTest() throws Exception {
+ customConfigs.put(
+ Configs.ENABLE_AUTHORIZATION.getKey(), String.valueOf(authorizationEnabled()));
+ customConfigs.put(Configs.SERVICE_ADMINS.getKey(), "anonymous");
+ customConfigs.put(Configs.AUTHENTICATORS.getKey(), "simple");
+ // BaseIT also uses this bind host in client URIs; a wildcard address is not a client target.
+ // Loopback keeps the test server local and makes readiness probes reachable on macOS.
+ customConfigs.put("gravitino.server.webserver.host", "127.0.0.1");
+
+ super.startIntegrationTest();
+
+ // Use the configured service admin rather than the developer's operating-system username.
+ client.close();
+ client = GravitinoAdminClient.builder(serverUri).withSimpleAuth("anonymous").build();
+ }
+
+ /** {@inheritDoc} */
+ @Override
+ @AfterAll
+ public void stopIntegrationTest() throws IOException, InterruptedException {
+ String storage =
+ serverConfig == null ? null : serverConfig.get(Configs.ENTITY_RELATIONAL_JDBC_BACKEND_PATH);
+ boolean embedded = "embedded".equals(testMode);
+ super.stopIntegrationTest();
+
+ // BaseIT owns external database containers; only the embedded H2 store leaves local files.
+ if (embedded && "h2".equalsIgnoreCase(getJDBCBackend()) && storage != null) {
+ for (String suffix : List.of(".mv.db", ".trace.db", ".lock.db", "")) {
+ Files.deleteIfExists(Path.of(storage + suffix));
+ }
+ }
+ }
+
+ /** Whether this suite enables the real Casbin authorizer. */
+ protected boolean authorizationEnabled() {
+ return false;
+ }
+
+ /**
+ * Creates an isolated Iceberg JDBC catalog and schema, using local H2 and files.
+ *
+ * @return The catalog, containing an empty schema named schema.
+ */
+ protected Catalog createRelationalCatalog() {
+ // This is the Iceberg catalog database, independent of Gravitino's jdbcBackend entity store.
+ Catalog catalog =
+ metalake.createCatalog(
+ "ice",
+ Catalog.Type.RELATIONAL,
+ "lakehouse-iceberg",
+ "",
+ Map.of(
+ "catalog-backend",
+ "jdbc",
+ "warehouse",
+ directory.resolve("warehouse").toString(),
+ "uri",
+ "jdbc:h2:mem:" + metalake.name() + ";DB_CLOSE_DELAY=-1;MODE=MYSQL",
+ "jdbc-driver",
+ "org.h2.Driver",
+ "jdbc-initialize",
+ "true"));
+ catalog.asSchemas().createSchema("schema", "", Collections.emptyMap());
+ return catalog;
+ }
+
+ @BeforeEach
+ void createMetalake() {
+ metalakeName = "domain_it_" + UUID.randomUUID().toString().replace("-", "");
+ metalake = client.createMetalake(metalakeName, "", Collections.emptyMap());
+ }
+
+ @AfterEach
+ void dropMetalake() {
+ client.dropMetalake(metalakeName, true);
+ }
+
+ @Test
+ void testDomainLifecycleAndEncodedNames() {
+ // Exercise names that must survive path and query encoding without becoming hierarchy.
+ String name = "Finance/US. East,?&+%";
+ Domain draft = create(name);
+ assertEquals(name, metalake.getDomain(name).name());
+ assertEquals(Set.of(name), Set.of(metalake.listDomains()));
+ assertEquals(name, metalake.listDomainsInfo()[0].name());
+ assertEquals(Domain.Status.DRAFT, draft.status());
+
+ // Mutations return a fresh snapshot and leave previously loaded state unchanged.
+ Domain published = draft.publish();
+ assertEquals(Domain.Status.PUBLISHED, published.status());
+ assertEquals(Domain.Status.DRAFT, draft.status());
+ assertEquals(Domain.Status.DRAFT, published.unpublish().status());
+
+ Map<String, String> properties = new HashMap<>();
+ properties.put("key", "value");
+ Domain changed =
+ metalake.alterDomain(
+ name, DomainChange.updateComment("new"), DomainChange.setProperty("key", "value"));
+ assertEquals("new", changed.comment());
+ assertEquals(properties, changed.properties());
+ assertNull(draft.comment());
+ assertTrue(draft.properties().isEmpty());
+
+ // Renaming a domain preserves its backing tag but invalidates the old name until reused.
+ changed =
+ metalake.alterDomain(
+ name, DomainChange.removeProperty("key"), DomainChange.rename("Renamed/US. East,?&+%"));
+ assertTrue(changed.properties().isEmpty());
+ assertEquals(
+ TagValue.noValue(name.replace(".", "_") + " tag"), changed.backingTag().orElseThrow());
+ assertNull(metalake.alterDomain(changed.name(), DomainChange.updateComment(null)).comment());
+ assertEquals("new", changed.comment());
+ assertThrows(NoSuchDomainException.class, draft::publish);
+
+ // An old snapshot addresses the replacement domain by name, not the original entity ID.
+ Domain replacement =
+ metalake.createDomain(name, null, null, TagValue.noValue("replacement tag"), true);
+ assertEquals(Domain.Status.PUBLISHED, draft.publish().status());
+ assertEquals(Domain.Status.DRAFT, replacement.status());
+
+ assertTrue(metalake.deleteDomain(name));
+ assertFalse(metalake.deleteDomain(name));
+ assertTrue(metalake.deleteDomain(changed.name()));
+ }
+
+ @Test
+ void testHierarchyAndBackingTagChanges() {
+ Domain parent = create("Parent/with. spaces");
+ Domain other = create("Other/parent. name");
+ Domain child =
+ parent.createSubdomain("Tax,EU/child", null, null, TagValue.noValue("child tag"), true);
+ assertEquals(parent.name(), child.parent().orElseThrow());
+ assertArrayEquals(new String[] {child.name()}, parent.listSubdomains());
+ assertEquals(child.name(), parent.listSubdomainsInfo()[0].name());
+
+ // Published children constrain both parent deletion and visibility changes.
+ assertThrows(NonEmptyDomainException.class, () -> metalake.deleteDomain(parent.name()));
+ assertThrows(IllegalArgumentException.class, child::publish);
+ parent.publish();
+ Domain publishedChild = child.publish();
+ assertThrows(IllegalArgumentException.class, parent::unpublish);
+ assertThrows(IllegalArgumentException.class, () -> publishedChild.attachToParent(other.name()));
+
+ // Move and detach operate on current server state even when invoked on an older snapshot.
+ other.publish();
+ Domain moved = publishedChild.attachToParent(other.name());
+ assertEquals(other.name(), moved.parent().orElseThrow());
+ assertEquals(parent.name(), child.parent().orElseThrow());
+ assertEquals(0, parent.listSubdomains().length);
+ assertEquals(child.name(), other.listSubdomains()[0]);
+ assertTrue(child.detachFromParent().parent().isEmpty());
+ assertTrue(metalake.getDomain(child.name()).parent().isEmpty());
+ assertEquals(parent.name(), child.parent().orElseThrow());
+
+ // Removing a binding does not delete the tag or mutate the original snapshot.
+ metalake.createTag("new backing", null, Collections.emptyMap());
+ assertEquals(
+ TagValue.noValue("new backing"),
+ child.updateBackingTag(TagValue.noValue("new backing")).backingTag().orElseThrow());
+ assertTrue(child.updateBackingTag(null).backingTag().isEmpty());
+ assertEquals(TagValue.noValue("child tag"), child.backingTag().orElseThrow());
+ assertNotNull(metalake.getTag("child tag"));
+ assertTrue(metalake.deleteDomain(parent.name()));
+ }
+
+ @Test
+ void testErrorsAndEmptyMemberFilters() {
+ Domain domain = create("errors");
+ assertThrows(
+ DomainAlreadyExistsException.class,
+ () -> metalake.createDomain(domain.name(), null, null, TagValue.noValue("another"), true));
+ assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ metalake.createDomain(
+ "conflict", null, null, domain.backingTag().orElseThrow(), false));
+ assertEquals(
+ 0,
+ domain.listMembers(
+ DomainMemberFilter.builder()
+ .withTypes(MetadataObject.Type.TABLE, MetadataObject.Type.VIEW)
+ .withDomains("Tax,EU", "Trading/US. East&?+%")
+ .withNameContains("x /?&+%,")
+ .build())
+ .length);
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain("missing"));
+ }
+
+ @Test
+ void testMembershipAcrossLocalCatalogs() {
+ Catalog catalog = createRelationalCatalog();
+ Column[] columns = {Column.of("id", Types.LongType.get())};
+ Table table =
+ catalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of("schema", "orders"), columns, "", Collections.emptyMap());
+ Table hidden =
+ catalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of("schema", "hidden"), columns, "", Collections.emptyMap());
+ View view =
+ catalog
+ .asViewCatalog()
+ .createView(
+ NameIdentifier.of("schema", "orders_view"),
+ "",
+ columns,
+ new SQLRepresentation[] {
+ SQLRepresentation.builder()
+ .withDialect("spark")
+ .withSql("SELECT id FROM ice.schema.orders")
+ .build()
+ },
+ null,
+ null,
+ Collections.emptyMap());
+ SemanticModel semantic =
+ catalog
+ .asSemanticModelCatalog()
+ .createSemanticModel(
+ NameIdentifier.of("schema", "business"),
+ "",
+ SemanticModelDefinition.builder()
+ .withDatasets(
+ new Dataset[] {
+ Dataset.builder()
+ .withName("orders")
+ .withSource(NameIdentifier.of("ice", "schema", "orders"))
+ .build()
+ })
+ .build(),
+ Collections.emptyMap());
+
+ // Add the remaining locally supported leaf types from independent catalogs.
+ Catalog files =
+ metalake.createCatalog(
+ "files",
+ Catalog.Type.FILESET,
+ "hadoop",
+ "",
+ Map.of("location", directory.resolve("files").toString()));
+ files.asSchemas().createSchema("schema", "", Collections.emptyMap());
+ Fileset fileset =
+ files
+ .asFilesetCatalog()
+ .createFileset(
+ NameIdentifier.of("schema", "data"),
+ "",
+ Fileset.Type.EXTERNAL,
+ directory.resolve("external").toString(),
+ Collections.emptyMap());
+
+ Catalog models =
+ metalake.createCatalog("models", Catalog.Type.MODEL, "model", "", Collections.emptyMap());
+ models.asSchemas().createSchema("schema", "", Collections.emptyMap());
+ Model model =
+ models
+ .asModelCatalog()
+ .registerModel(NameIdentifier.of("schema", "model"), "", Collections.emptyMap());
+
+ // The schema supplies Finance membership; the nearest table assignment overrides it for Risk.
+ metalake.createTag(
+ "department",
+ null,
+ Collections.emptyMap(),
+ TagValueConstraint.ofAllowedValues("finance", "risk"));
+ Domain finance =
+ metalake.createDomain(
+ "Finance/US. East,?&+%", null, null, TagValue.of("department", "finance"), false);
+ Domain risk =
+ metalake.createDomain("Risk,EU", null, null, TagValue.of("department", "risk"), false);
+ Domain child =
+ finance.createSubdomain(
+ "Trading,US/with. spaces?&+%", null, null, TagValue.noValue("trading"), true);
+ catalog
+ .asSchemas()
+ .loadSchema("schema")
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("department", "finance")}, new TagValue[0]);
+ table.supportsTags().associateTags(new String[] {"trading"}, new String[0]);
+ hidden
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("department", "risk")}, new TagValue[0]);
+ fileset
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("department", "finance")}, new TagValue[0]);
+ model
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("department", "finance")}, new TagValue[0]);
+
+ // An object can be inherited from Finance and reached through Trading at the same time.
+ Map<String, DomainMember> members =
+ Arrays.stream(finance.listMembers(DomainMemberFilter.builder().build()))
+ .collect(Collectors.toMap(member -> member.object().fullName(), member -> member));
+ assertEquals(
+ Set.of(
+ "ice.schema.orders",
+ "ice.schema.orders_view",
+ "ice.schema.business",
+ "files.schema.data",
+ "models.schema.model"),
+ members.keySet());
+ assertEquals(
+ Set.of(DomainRelation.Type.INHERITED, DomainRelation.Type.VIA_SUBDOMAIN),
+ Arrays.stream(members.get("ice.schema.orders").relations())
+ .map(DomainRelation::type)
+ .collect(Collectors.toSet()));
+ assertEquals(
+ DomainRelation.Type.DIRECT, members.get("files.schema.data").relations()[0].type());
+ assertEquals(
+ "ice.schema.hidden",
+ risk.listMembers(DomainMemberFilter.builder().build())[0].object().fullName());
+
+ // Verify the reverse lookup exposed by every supported leaf resource.
+ assertTrue(Set.of(table.supportsDomains().listDomains()).contains(finance.name()));
+ assertEquals(finance.name(), view.supportsDomains().listDomainsInfo()[0].name());
+ assertEquals(finance.name(), semantic.supportsDomains().listDomainsInfo()[0].name());
+ assertEquals(finance.name(), fileset.supportsDomains().listDomainsInfo()[0].name());
+ assertEquals(finance.name(), model.supportsDomains().listDomainsInfo()[0].name());
+
+ // Commas belong to scope names; repeated scopes select their union without duplicating members.
+ assertEquals(
+ 1,
+ finance.listMembers(
+ DomainMemberFilter.builder().withDomains(child.name(), "unknown,scope").build())
+ .length);
+ assertEquals(
+ 5,
+ finance.listMembers(
+ DomainMemberFilter.builder().withDomains(finance.name(), child.name()).build())
+ .length);
+ assertEquals(
+ 2,
+ finance.listMembers(
+ DomainMemberFilter.builder()
+ .withTypes(MetadataObject.Type.VIEW, MetadataObject.Type.MODEL)
+ .build())
+ .length);
+ assertEquals(
+ 2,
+ finance.listMembers(DomainMemberFilter.builder().withNameContains("ORDERS").build())
+ .length);
+ assertEquals(
+ 0,
+ finance.listMembers(DomainMemberFilter.builder().withNameContains("/ ?&+%,").build())
+ .length);
+
+ // Membership roll-ups follow hierarchy changes without retagging the leaf object.
+ Domain other = create("new parent");
+ child.attachToParent(other.name());
+ assertTrue(Set.of(table.supportsDomains().listDomains()).contains(other.name()));
+ metalake.alterDomain(child.name(), DomainChange.rename("renamed/child"));
+ assertTrue(Set.of(table.supportsDomains().listDomains()).contains("renamed/child"));
+ metalake.deleteDomain("renamed/child");
+ assertFalse(Set.of(table.supportsDomains().listDomains()).contains(other.name()));
+ assertNotNull(metalake.getTag("trading"));
+ finance.updateBackingTag(null);
+ assertEquals(0, table.supportsDomains().listDomains().length);
+ }
+
+ @Test
+ void testEncodedNamesThroughPreservingProxy() throws Exception {
+ // Preserve the raw URI so this proxy does not decode %2F before forwarding to Jetty.
+ HttpServer proxy = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+ HttpClient upstream = HttpClient.newHttpClient();
+ proxy.createContext("/", exchange -> forward(exchange, upstream));
+ proxy.start();
+ String uri = "http://127.0.0.1:" + proxy.getAddress().getPort();
+ try (GravitinoAdminClient proxyClient =
+ GravitinoAdminClient.builder(uri).withSimpleAuth("anonymous").build()) {
+ GravitinoMetalake proxied = proxyClient.loadMetalake(metalake.name());
+ String name = "Proxy/US. East,?&+%";
+ Domain domain = proxied.createDomain(name, null, null, TagValue.noValue("proxy tag"), true);
+ assertEquals(name, proxied.getDomain(name).name());
+ assertEquals(Domain.Status.PUBLISHED, domain.publish().status());
+ Catalog catalog = createRelationalCatalog();
+ Table table = createTable(catalog);
+ Table other =
+ catalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of("schema", "other"),
+ new Column[] {Column.of("id", Types.LongType.get())},
+ "",
+ Collections.emptyMap());
+ Domain first =
+ domain.createSubdomain("scope,one", null, null, TagValue.noValue("proxy-first"), true);
+ Domain second =
+ domain.createSubdomain(
+ "scope/two?&+%", null, null, TagValue.noValue("proxy-second"), true);
+ table.supportsTags().associateTags(new String[] {"proxy-first"}, new String[0]);
+ other.supportsTags().associateTags(new String[] {"proxy-second"}, new String[0]);
+
+ // A dropped or incorrectly split scope parameter changes these nonempty results.
+ DomainMember[] selected =
+ domain.listMembers(
+ DomainMemberFilter.builder()
+ .withDomains(first.name(), "unknown,scope")
+ .withNameContains("ORDERS")
+ .build());
+ assertEquals(1, selected.length);
+ assertEquals("ice.schema.orders", selected[0].object().fullName());
+ assertArrayEquals(
+ new DomainRelation[] {DomainRelation.viaSubdomain(first.name())},
+ selected[0].relations());
+ assertEquals(
+ 2,
+ domain.listMembers(
+ DomainMemberFilter.builder().withDomains(first.name(), second.name()).build())
+ .length);
+ assertEquals(
+ "ice.schema.other",
+ domain
+ .listMembers(DomainMemberFilter.builder().withDomains(second.name()).build())[0]
+ .object()
+ .fullName());
+ assertEquals(
+ 0,
+ domain.listMembers(DomainMemberFilter.builder().withDomains("unknown,scope").build())
+ .length);
+ assertEquals(
+ 0,
+ domain.listMembers(
+ DomainMemberFilter.builder()
+ .withDomains(first.name())
+ .withNameContains("other")
+ .build())
+ .length);
+ assertTrue(proxied.deleteDomain(first.name()));
+ assertTrue(proxied.deleteDomain(second.name()));
+ assertTrue(proxied.deleteDomain(name));
+ } finally {
+ proxy.stop(0);
+ }
+ }
+
+ @Test
+ void testNearestTagAssignmentAndValueMatching() {
+ Catalog catalog = createRelationalCatalog();
+ Table table = createTable(catalog);
+ metalake.createTag(
+ "department",
+ null,
+ Collections.emptyMap(),
+ TagValueConstraint.ofAllowedValues("finance", "risk", "Finance"));
+ Domain finance =
+ metalake.createDomain("Finance", null, null, TagValue.of("department", "finance"), false);
+ Domain risk =
+ metalake.createDomain("Risk", null, null, TagValue.of("department", "risk"), false);
+ Domain caseSensitive =
+ metalake.createDomain(
+ "Capitalized", null, null, TagValue.of("department", "Finance"), false);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> finance.updateBackingTag(TagValue.of("department", "unknown")));
+ assertEquals(
+ TagValue.of("department", "finance"),
+ metalake.getDomain(finance.name()).backingTag().orElseThrow());
+
+ // A catalog assignment is inherited until a nearer schema assignment masks the same tag.
+ catalog
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("department", "finance")}, new TagValue[0]);
+ assertTableRelations(
+ finance,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice", MetadataObject.Type.CATALOG)));
+ assertTableRelations(caseSensitive, table);
+ catalog
+ .asSchemas()
+ .loadSchema("schema")
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("department", "risk")}, new TagValue[0]);
+ assertTableRelations(finance, table);
+ assertTableRelations(
+ risk,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice.schema", MetadataObject.Type.SCHEMA)));
+
+ // Multiple direct values match independently and case-sensitively; lower assignments stay
+ // masked.
+ table
+ .supportsTags()
+ .associateTags(
+ new TagValue[] {
+ TagValue.of("department", "finance"), TagValue.of("department", "Finance")
+ },
+ new TagValue[0]);
+ assertTableRelations(finance, table, DomainRelation.direct());
+ assertTableRelations(caseSensitive, table, DomainRelation.direct());
+ assertTableRelations(risk, table);
+ table
+ .supportsTags()
+ .associateTags(new TagValue[0], new TagValue[] {TagValue.of("department", "finance")});
+ assertTableRelations(finance, table);
+ assertTableRelations(caseSensitive, table, DomainRelation.direct());
+ assertTableRelations(risk, table);
+
+ // Removing the nearest assignment reveals schema, then catalog, then no membership.
+ table
+ .supportsTags()
+ .associateTags(new TagValue[0], new TagValue[] {TagValue.of("department", "Finance")});
+ assertTableRelations(
+ risk,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice.schema", MetadataObject.Type.SCHEMA)));
+ catalog
+ .asSchemas()
+ .loadSchema("schema")
+ .supportsTags()
+ .associateTags(new TagValue[0], new TagValue[] {TagValue.of("department", "risk")});
+ assertTableRelations(
+ finance,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice", MetadataObject.Type.CATALOG)));
+ catalog
+ .supportsTags()
+ .associateTags(new TagValue[0], new TagValue[] {TagValue.of("department", "finance")});
+ assertTableRelations(finance, table);
+ assertTableRelations(risk, table);
+ assertTableRelations(caseSensitive, table);
+
+ // A valueless backing binding matches both valued and valueless effective assignments.
+ metalake.createTag("any-value", null, Collections.emptyMap());
+ Domain any = metalake.createDomain("Any", null, null, TagValue.noValue("any-value"), false);
+ table
+ .supportsTags()
+ .associateTags(new TagValue[] {TagValue.of("any-value", "arbitrary")}, new TagValue[0]);
+ assertTableRelations(any, table, DomainRelation.direct());
+ table
+ .supportsTags()
+ .associateTags(
+ new TagValue[] {TagValue.noValue("any-value")},
+ new TagValue[] {TagValue.of("any-value", "arbitrary")});
+ assertTableRelations(any, table, DomainRelation.direct());
+ assertThrows(
+ BackingTagAlreadyBoundException.class,
+ () ->
+ metalake.createDomain(
+ "Mixed", null, null, TagValue.of("any-value", "arbitrary"), false));
+ }
+
+ @Test
+ void testMultipleSubdomainRelationsAndBackingTagIdentity() {
+ Catalog catalog = createRelationalCatalog();
+ Table table = createTable(catalog);
+ Domain parent = create("Parent");
+ Domain first =
+ parent.createSubdomain("First/child.A", null, null, TagValue.noValue("first-tag"), true);
+ Domain second =
+ parent.createSubdomain("Second,child.B", null, null, TagValue.noValue("second-tag"), true);
+ catalog.supportsTags().associateTags(new String[] {"first-tag"}, new String[0]);
+ catalog
+ .asSchemas()
+ .loadSchema("schema")
+ .supportsTags()
+ .associateTags(new String[] {"second-tag"}, new String[0]);
+ table
+ .supportsTags()
+ .associateTags(new String[] {parent.backingTag().orElseThrow().name()}, new String[0]);
+
+ // The member appears once but retains direct membership and both independent roll-up paths.
+ assertTableRelations(
+ parent,
+ table,
+ DomainRelation.direct(),
+ DomainRelation.viaSubdomain(first.name()),
+ DomainRelation.viaSubdomain(second.name()));
+ assertTableRelations(
+ first,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice", MetadataObject.Type.CATALOG)));
+ assertTableRelations(
+ second,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice.schema", MetadataObject.Type.SCHEMA)));
+ DomainMember[] selected =
+ parent.listMembers(
+ DomainMemberFilter.builder()
+ .withDomains(first.name(), second.name())
+ .withTypes(MetadataObject.Type.TABLE)
+ .withNameContains("ORDERS")
+ .build());
+ assertEquals(1, selected.length);
+ assertEquals(3, selected[0].relations().length);
+ assertEquals(
+ 0,
+ parent.listMembers(
+ DomainMemberFilter.builder()
+ .withDomains(first.name())
+ .withTypes(MetadataObject.Type.VIEW)
+ .build())
+ .length);
+
+ // Child scopes do not include their siblings; detaching changes only the parent's roll-up.
+ assertEquals(
+ 0,
+ first.listMembers(DomainMemberFilter.builder().withDomains(second.name()).build()).length);
+ table
+ .supportsTags()
+ .associateTags(new String[0], new String[] {parent.backingTag().orElseThrow().name()});
+ assertTableRelations(
+ parent,
+ table,
+ DomainRelation.viaSubdomain(first.name()),
+ DomainRelation.viaSubdomain(second.name()));
+ second.detachFromParent();
+ assertTableRelations(parent, table, DomainRelation.viaSubdomain(first.name()));
+ first = metalake.alterDomain(first.name(), DomainChange.rename("Renamed/child.A"));
+ assertTableRelations(parent, table, DomainRelation.viaSubdomain(first.name()));
+ parent = metalake.alterDomain(parent.name(), DomainChange.rename("Renamed/parent.P"));
+ assertEquals(parent.name(), metalake.getDomain(first.name()).parent().orElseThrow());
+ assertTableRelations(parent, table, DomainRelation.viaSubdomain(first.name()));
+
+ // Renaming a tag preserves its identity; deleting and recreating its name must not rebind it.
+ metalake.alterTag("first-tag", TagChange.rename("renamed-first-tag"));
+ assertEquals(
+ "renamed-first-tag", metalake.getDomain(first.name()).backingTag().orElseThrow().name());
+ assertTableRelations(parent, table, DomainRelation.viaSubdomain(first.name()));
+ metalake.deleteTag("renamed-first-tag");
+ assertTrue(metalake.getDomain(first.name()).backingTag().isEmpty());
+ assertTableRelations(parent, table);
+ metalake.createTag("renamed-first-tag", null, Collections.emptyMap());
+ catalog.supportsTags().associateTags(new String[] {"renamed-first-tag"}, new String[0]);
+ assertTableRelations(first, table);
+ assertTableRelations(parent, table);
+ first.updateBackingTag(TagValue.noValue("renamed-first-tag"));
+ assertTableRelations(
+ first,
+ table,
+ DomainRelation.inherited(MetadataObjects.parse("ice", MetadataObject.Type.CATALOG)));
+ assertTableRelations(parent, table, DomainRelation.viaSubdomain(first.name()));
+ first.updateBackingTag(null);
+ assertTableRelations(parent, table);
+ }
+
+ @Test
+ void testInvalidHierarchyAtomicCreationAndIdempotence() {
+ Domain parent = create("Parent");
+ Domain other = create("Other");
+ Domain child = parent.createSubdomain("Child", null, null, TagValue.noValue("child-tag"), true);
+
+ metalake.createTag(
+ "existing-valued-tag",
+ null,
+ Collections.emptyMap(),
+ TagValueConstraint.ofAllowedValues("finance"));
+ Domain bound =
+ parent.createSubdomain(
+ "Bound",
+ "existing tag",
+ Map.of("key", "value"),
+ TagValue.of("existing-valued-tag", "finance"),
+ false);
+ assertEquals(parent.name(), bound.parent().orElseThrow());
+ assertEquals(TagValue.of("existing-valued-tag", "finance"), bound.backingTag().orElseThrow());
+ assertEquals(Map.of("key", "value"), bound.properties());
+ assertThrows(
+ DomainAlreadyExistsException.class,
+ () -> metalake.alterDomain(other.name(), DomainChange.rename(parent.name())));
+ assertEquals(other.name(), metalake.getDomain(other.name()).name());
+
+ // Hierarchy validation must leave neither a new domain nor its requested backing tag behind.
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ child.createSubdomain(
+ "Grandchild", null, null, TagValue.noValue("grandchild-tag"), true));
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain("Grandchild"));
+ assertThrows(NoSuchTagException.class, () -> metalake.getTag("grandchild-tag"));
+ assertThrows(
+ DomainAlreadyExistsException.class,
+ () ->
+ metalake.createDomain(parent.name(), null, null, TagValue.noValue("unused-tag"), true));
+ assertThrows(NoSuchTagException.class, () -> metalake.getTag("unused-tag"));
+ assertThrows(IllegalArgumentException.class, () -> child.attachToParent(child.name()));
+ assertThrows(IllegalArgumentException.class, () -> other.attachToParent(child.name()));
+ assertThrows(IllegalArgumentException.class, () -> parent.attachToParent(other.name()));
+ assertEquals(parent.name(), child.attachToParent(parent.name()).parent().orElseThrow());
+ assertEquals(
+ child.backingTag(), child.updateBackingTag(child.backingTag().orElseThrow()).backingTag());
+
+ // Repeating visibility and detach operations is safe and does not mutate an older snapshot.
+ assertEquals(Domain.Status.PUBLISHED, parent.publish().publish().status());
+ assertEquals(Domain.Status.PUBLISHED, child.publish().publish().status());
+ assertEquals(Domain.Status.DRAFT, child.unpublish().unpublish().status());
+ assertEquals(Domain.Status.DRAFT, parent.unpublish().unpublish().status());
+ assertTrue(parent.detachFromParent().parent().isEmpty());
+ assertTrue(child.detachFromParent().detachFromParent().parent().isEmpty());
+ assertEquals(parent.name(), child.parent().orElseThrow());
+ assertNotNull(child.auditInfo().creator());
+ assertNotNull(child.auditInfo().createTime());
+ }
+
+ @Test
+ void testMissingDomainEndpointsAndInvalidBindingsLeaveNoChanges() {
+ Domain removed = create("removed");
+ metalake.deleteDomain(removed.name());
+ assertThrows(
+ NoSuchDomainException.class,
+ () -> metalake.alterDomain(removed.name(), DomainChange.updateComment("missing")));
+ assertThrows(NoSuchDomainException.class, removed::publish);
+ assertThrows(NoSuchDomainException.class, removed::unpublish);
+ assertThrows(NoSuchDomainException.class, removed::detachFromParent);
+ assertThrows(NoSuchDomainException.class, () -> removed.attachToParent("missing-parent"));
+ assertThrows(NoSuchDomainException.class, () -> removed.updateBackingTag(null));
+ assertThrows(NoSuchDomainException.class, removed::listSubdomains);
+ assertThrows(NoSuchDomainException.class, removed::listSubdomainsInfo);
+ assertThrows(
+ NoSuchDomainException.class,
+ () -> removed.listMembers(DomainMemberFilter.builder().build()));
+ assertThrows(
+ NoSuchDomainException.class,
+ () -> removed.createSubdomain("orphan", null, null, TagValue.noValue("orphan-tag"), true));
+ assertThrows(NoSuchTagException.class, () -> metalake.getTag("orphan-tag"));
+ assertFalse(metalake.deleteDomain(removed.name()));
+
+ Domain domain = create("binding-errors");
+ assertThrows(NoSuchDomainException.class, () -> domain.attachToParent("missing-parent"));
+ assertTrue(metalake.getDomain(domain.name()).parent().isEmpty());
+ assertThrows(
+ NoSuchTagException.class, () -> domain.updateBackingTag(TagValue.noValue("absent-tag")));
+ assertEquals(domain.backingTag(), metalake.getDomain(domain.name()).backingTag());
+
+ // Failed creation must neither adopt an existing tag nor create a partial domain.
+ assertThrows(
+ NoSuchTagException.class,
+ () ->
+ metalake.createDomain(
+ "missing-binding", null, null, TagValue.noValue("absent-tag"), false));
+ assertThrows(
+ TagAlreadyExistsException.class,
+ () ->
+ metalake.createDomain(
+ "existing-binding", null, null, domain.backingTag().orElseThrow(), true));
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ metalake.createDomain(
+ "valued-new-tag", null, null, TagValue.of("invalid-new-tag", "value"), true));
+ for (String name : List.of("missing-binding", "existing-binding", "valued-new-tag", "orphan")) {
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain(name));
+ }
+ assertThrows(NoSuchTagException.class, () -> metalake.getTag("invalid-new-tag"));
+ assertNotNull(metalake.getTag(domain.backingTag().orElseThrow().name()));
+ }
+
+ @Test
+ void testUnicodeNamesAndBackingTagValueLengthBoundaries() {
+ Table table = createTable(createRelationalCatalog());
+ String[] values = {"x".repeat(256), "😀".repeat(128)};
+ for (int index = 0; index < values.length; index++) {
+ String tagName = "unicode-boundary-" + index;
+ metalake.createTag(tagName, null, Collections.emptyMap());
+ String name = "财务/😀,区域" + index;
+ TagValue binding = TagValue.of(tagName, values[index]);
+ Domain domain =
+ metalake.createDomain(
+ name, "Unicode comment 中文😀", Map.of("region", "亚洲😀"), binding, false);
+ assertEquals(name, metalake.getDomain(name).name());
+ assertEquals(binding, metalake.getDomain(name).backingTag().orElseThrow());
+ assertEquals("亚洲😀", metalake.getDomain(name).properties().get("region"));
+
+ // Boundary values must survive JSON, storage and effective-tag membership resolution.
+ table.supportsTags().associateTags(new TagValue[] {binding}, new TagValue[0]);
+ assertTableRelations(domain, table, DomainRelation.direct());
+ String renamed = "税务/😀,地区" + index;
+ Domain changed = metalake.alterDomain(name, DomainChange.rename(renamed));
+ assertEquals(renamed, metalake.getDomain(renamed).name());
+ assertEquals(binding, changed.backingTag().orElseThrow());
+ assertTableRelations(changed, table, DomainRelation.direct());
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain(name));
+
+ // Both ASCII and supplementary characters use the same 256 UTF-16-unit limit.
+ String invalid = values[index] + "x";
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> changed.updateBackingTag(TagValue.of(tagName, invalid)));
+ assertEquals(binding, metalake.getDomain(renamed).backingTag().orElseThrow());
+ String rejectedName = "rejected-boundary-" + index;
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ metalake.createDomain(
+ rejectedName, null, null, TagValue.of(tagName, invalid), false));
+ assertThrows(NoSuchDomainException.class, () -> metalake.getDomain(rejectedName));
+ assertTableRelations(changed, table, DomainRelation.direct());
+ }
+ }
+
+ @Test
+ void testRealResponseValueEqualityAndSnapshotProtection() {
+ Table table = createTable(createRelationalCatalog());
+ Domain created =
+ metalake.createDomain(
+ "value-contract",
+ "original",
+ Map.of("key", "value"),
+ TagValue.noValue("value-contract-tag"),
+ true);
+ Domain loaded = metalake.getDomain(created.name());
+ Domain listed = metalake.listDomainsInfo()[0];
+ assertEquals(created, loaded);
+ assertEquals(loaded, listed);
+ assertEquals(created.hashCode(), loaded.hashCode());
+ assertTrue(Set.of(created).contains(listed));
+ assertThrows(
+ UnsupportedOperationException.class, () -> loaded.properties().put("key", "changed"));
+ assertEquals(Map.of("key", "value"), loaded.properties());
+
+ table.supportsTags().associateTags(new String[] {"value-contract-tag"}, new String[0]);
+ DomainMemberFilter filter =
+ DomainMemberFilter.builder().withTypes(MetadataObject.Type.TABLE).build();
+ DomainMember member = loaded.listMembers(filter)[0];
+ DomainMember reloaded = loaded.listMembers(filter)[0];
+ MetadataObject object = MetadataObjects.parse("ice.schema.orders", MetadataObject.Type.TABLE);
+ assertEquals(member, reloaded);
+ assertEquals(member.hashCode(), reloaded.hashCode());
+ assertTrue(Set.of(member).contains(reloaded));
+ assertEquals(object, member.object());
+ assertEquals(object.hashCode(), member.object().hashCode());
+ assertEquals("ice.schema", member.object().parent());
+
+ // Returned arrays cannot change the member or the domain snapshot used as a set key.
+ int memberHash = member.hashCode();
+ member.relations()[0] = null;
+ assertArrayEquals(new DomainRelation[] {DomainRelation.direct()}, member.relations());
+ assertEquals(memberHash, member.hashCode());
+ Domain reverse = table.supportsDomains().listDomainsInfo()[0];
+ Domain reverseReloaded = table.supportsDomains().listDomainsInfo()[0];
+ assertEquals(reverse, reverseReloaded);
+ int reverseHash = reverse.hashCode();
+ reverse.relations()[0] = null;
+ assertArrayEquals(new DomainRelation[] {DomainRelation.direct()}, reverse.relations());
+ assertEquals(reverseHash, reverse.hashCode());
+ assertTrue(Set.of(reverse).contains(reverseReloaded));
+
+ Domain changed =
+ metalake.alterDomain(
+ loaded.name(),
+ DomainChange.updateComment("changed"),
+ DomainChange.setProperty("key", "changed"));
+ assertFalse(loaded.equals(changed));
+ assertEquals("original", loaded.comment());
+ assertEquals(Map.of("key", "value"), loaded.properties());
+ assertEquals(created, loaded);
+ }
+
+ private Table createTable(Catalog catalog) {
+ return catalog
+ .asTableCatalog()
+ .createTable(
+ NameIdentifier.of("schema", "orders"),
+ new Column[] {Column.of("id", Types.LongType.get())},
+ "",
+ Collections.emptyMap());
+ }
+
+ private void assertTableRelations(Domain domain, Table table, DomainRelation... expected) {
+ DomainMember[] members =
+ domain.listMembers(
+ DomainMemberFilter.builder()
+ .withTypes(MetadataObject.Type.TABLE)
+ .withNameContains("ice.schema.orders")
+ .build());
+ Domain[] reverse =
+ Arrays.stream(table.supportsDomains().listDomainsInfo())
+ .filter(candidate -> candidate.name().equals(domain.name()))
+ .toArray(Domain[]::new);
+ if (expected.length == 0) {
+ assertEquals(0, members.length);
+ assertEquals(0, reverse.length);
+ return;
+ }
+ assertEquals(1, members.length);
+ assertEquals("ice.schema.orders", members[0].object().fullName());
+ assertEquals(MetadataObject.Type.TABLE, members[0].object().type());
+ assertEquals(expected.length, members[0].relations().length);
+ assertEquals(Set.of(expected), Set.of(members[0].relations()));
+ assertEquals(1, reverse.length);
+ assertEquals(expected.length, reverse[0].relations().length);
+ assertEquals(Set.of(expected), Set.of(reverse[0].relations()));
+ assertEquals(0, domain.relations().length);
+ }
+
+ private Domain create(String name) {
+ return metalake.createDomain(
+ name, null, null, TagValue.noValue(name.replace(".", "_") + " tag"), true);
+ }
+
+ private void forward(HttpExchange exchange, HttpClient upstream) throws IOException {
+ try {
+ // Forward the encoded path and repeated query parameters unchanged.
+ HttpRequest.Builder request =
+ HttpRequest.newBuilder(URI.create(serverUri + exchange.getRequestURI().toASCIIString()));
+ for (String header : List.of("Authorization", "Content-Type", "Accept")) {
+ String value = exchange.getRequestHeaders().getFirst(header);
+ if (value != null) {
+ request.header(header, value);
+ }
+ }
+ request.method(
+ exchange.getRequestMethod(),
+ HttpRequest.BodyPublishers.ofByteArray(exchange.getRequestBody().readAllBytes()));
+
+ HttpResponse<byte[]> response =
+ upstream.send(request.build(), HttpResponse.BodyHandlers.ofByteArray());
+ response
+ .headers()
+ .firstValue("Content-Type")
+ .ifPresent(value -> exchange.getResponseHeaders().set("Content-Type", value));
+ exchange.sendResponseHeaders(response.statusCode(), response.body().length);
+ exchange.getResponseBody().write(response.body());
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ exchange.sendResponseHeaders(502, -1);
+ } finally {
+ exchange.close();
+ }
+ }
+}
diff --git a/clients/client-python/gravitino/api/authorization/privileges.py b/clients/client-python/gravitino/api/authorization/privileges.py
index 66990e343b..65ad468665 100644
--- a/clients/client-python/gravitino/api/authorization/privileges.py
+++ b/clients/client-python/gravitino/api/authorization/privileges.py
@@ -225,6 +225,12 @@ class Privilege(ABC):
MODIFY_SEMANTIC_MODEL = (0, 1 << 41)
"""The privilege to rename a Semantic Model or alter its definition and metadata."""
+ MANAGE_DOMAIN = (0, 1 << 42)
+ """The privilege to manage domains, including drafts."""
+
+ USE_DOMAIN = (0, 1 << 43)
+ """The privilege to discover published domains and their accessible members."""
+
def __init__(self, high_bits: int, low_bits: int) -> None:
"""
Initialize the Name with the high and low bits.
@@ -1883,6 +1889,62 @@ class IncludeCredentialSecrets(GenericPrivilege):
return obj_type in Privileges.SECRET_SUPPORTED_TYPES
+class ManageDomain(GenericPrivilege):
+ """The privilege to manage domains, including drafts."""
+
+ _ALLOW_INSTANCE: Optional[ManageDomain] = None
+ _DENY_INSTANCE: Optional[ManageDomain] = None
+
+ @staticmethod
+ def allow() -> ManageDomain:
+ """Return the privilege with the allow condition."""
+ if ManageDomain._ALLOW_INSTANCE is None:
+ ManageDomain._ALLOW_INSTANCE = ManageDomain(
+ Privilege.Condition.ALLOW, Privilege.Name.MANAGE_DOMAIN
+ )
+ return ManageDomain._ALLOW_INSTANCE
+
+ @staticmethod
+ def deny() -> ManageDomain:
+ """Return the privilege with the deny condition."""
+ if ManageDomain._DENY_INSTANCE is None:
+ ManageDomain._DENY_INSTANCE = ManageDomain(
+ Privilege.Condition.DENY, Privilege.Name.MANAGE_DOMAIN
+ )
+ return ManageDomain._DENY_INSTANCE
+
+ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:
+ return obj_type in Privileges.DOMAIN_SUPPORTED_TYPES
+
+
+class UseDomain(GenericPrivilege):
+ """The privilege to discover published domains and accessible members."""
+
+ _ALLOW_INSTANCE: Optional[UseDomain] = None
+ _DENY_INSTANCE: Optional[UseDomain] = None
+
+ @staticmethod
+ def allow() -> UseDomain:
+ """Return the privilege with the allow condition."""
+ if UseDomain._ALLOW_INSTANCE is None:
+ UseDomain._ALLOW_INSTANCE = UseDomain(
+ Privilege.Condition.ALLOW, Privilege.Name.USE_DOMAIN
+ )
+ return UseDomain._ALLOW_INSTANCE
+
+ @staticmethod
+ def deny() -> UseDomain:
+ """Return the privilege with the deny condition."""
+ if UseDomain._DENY_INSTANCE is None:
+ UseDomain._DENY_INSTANCE = UseDomain(
+ Privilege.Condition.DENY, Privilege.Name.USE_DOMAIN
+ )
+ return UseDomain._DENY_INSTANCE
+
+ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:
+ return obj_type in Privileges.DOMAIN_SUPPORTED_TYPES
+
+
class Privileges:
_PRIVILEGE_TYPES = {
Privilege.Name.CREATE_CATALOG: CreateCatalog,
@@ -1924,10 +1986,14 @@ class Privileges:
Privilege.Name.CREATE_SEMANTIC_MODEL: CreateSemanticModel,
Privilege.Name.USE_SEMANTIC_MODEL: UseSemanticModel,
Privilege.Name.MODIFY_SEMANTIC_MODEL: ModifySemanticModel,
+ Privilege.Name.MANAGE_DOMAIN: ManageDomain,
+ Privilege.Name.USE_DOMAIN: UseDomain,
Privilege.Name.USE_SECRETS: UseSecrets,
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS: IncludeCredentialSecrets,
}
+ DOMAIN_SUPPORTED_TYPES = {MetadataObject.Type.METALAKE, MetadataObject.Type.DOMAIN}
+
TABLE_SUPPORTED_TYPES = {
MetadataObject.Type.METALAKE,
MetadataObject.Type.CATALOG,
@@ -1988,6 +2054,7 @@ class Privileges:
MetadataObject.Type.MODEL,
}
MANAGE_GRANTS_SUPPORTED_TYPES = {
+ MetadataObject.Type.DOMAIN,
MetadataObject.Type.METALAKE,
MetadataObject.Type.CATALOG,
MetadataObject.Type.SCHEMA,
diff --git a/clients/client-python/gravitino/dto/authorization/securable_object_dto.py b/clients/client-python/gravitino/dto/authorization/securable_object_dto.py
index 87c05ec9f5..ba526b0f96 100644
--- a/clients/client-python/gravitino/dto/authorization/securable_object_dto.py
+++ b/clients/client-python/gravitino/dto/authorization/securable_object_dto.py
@@ -54,7 +54,11 @@ class SecurableObjectDTO(SecurableObject):
)
def __post_init__(self):
- if self._full_name and "." in self._full_name:
+ if (
+ self._type != MetadataObject.Type.DOMAIN
+ and self._full_name
+ and "." in self._full_name
+ ):
index = self._full_name.rfind(".")
self._parent = self._full_name[:index]
self._name = self._full_name[index + 1 :]
diff --git a/clients/client-python/gravitino/exceptions/base.py b/clients/client-python/gravitino/exceptions/base.py
index df0133a159..7257ed9cd3 100644
--- a/clients/client-python/gravitino/exceptions/base.py
+++ b/clients/client-python/gravitino/exceptions/base.py
@@ -20,14 +20,14 @@ class GravitinoRuntimeException(RuntimeError):
"""Base class for all Gravitino runtime exceptions."""
def __init__(self, message, *args):
- super().__init__(message % args)
+ super().__init__(message % args if args else message)
class RESTException(RuntimeError):
"""An exception thrown when a REST request fails."""
def __init__(self, message, *args):
- super().__init__(message % args)
+ super().__init__(message % args if args else message)
class HTTPResponseException(RESTException):
@@ -64,7 +64,7 @@ class IllegalArgumentException(ValueError):
"""Base class for all exceptions thrown when arguments are invalid."""
def __init__(self, message, *args):
- super().__init__(message % args)
+ super().__init__(message % args if args else message)
class IllegalNameIdentifierException(IllegalArgumentException):
diff --git a/clients/client-python/tests/integration/domain_api_edges_mixin.py b/clients/client-python/tests/integration/domain_api_edges_mixin.py
new file mode 100644
index 0000000000..eed563c384
--- /dev/null
+++ b/clients/client-python/tests/integration/domain_api_edges_mixin.py
@@ -0,0 +1,342 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from gravitino.api.authorization.owner import Owner
+from gravitino.api.authorization.privileges import Privileges
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.metadata_objects import MetadataObjects
+from gravitino.api.authorization.securable_objects import SecurableObjects
+from gravitino.api.domain import (
+ Domain,
+ DomainChange,
+ DomainMemberFilter,
+ DomainRelation,
+)
+from gravitino.api.tag import TagValue
+from gravitino.exceptions.base import (
+ ForbiddenException,
+ IllegalArgumentException,
+ NoSuchDomainException,
+ NoSuchTagException,
+ TagAlreadyExistsException,
+)
+
+
+class DomainApiEdgesMixin:
+ """Endpoint matrices shared by the ordinary and authorization Domain suites."""
+
+ def test_authorization_write_endpoint_matrix(self):
+ if not self.authorization:
+ self.skipTest("Requires an authorization-enabled server")
+ parent = self._domain("matrix-parent").publish()
+ child = parent.create_subdomain(
+ "matrix-child", None, {}, TagValue("matrix-child-tag"), True
+ ).publish()
+ target = self._domain("matrix-target").publish()
+
+ creation_parent = self._domain("creation-parent").publish()
+
+ for user in ("matrix_reader", "matrix_denied"):
+ reader = self._client(user)
+ self._grant(
+ user,
+ [
+ SecurableObjects.of_metalake(
+ self.name,
+ [
+ Privileges.allow("USE_DOMAIN"),
+ Privileges.allow("CREATE_TAG"),
+ ],
+ )
+ ],
+ )
+ if user == "matrix_denied":
+ self._grant(
+ user,
+ [
+ SecurableObjects.of_metalake(
+ self.name, [Privileges.allow("MANAGE_DOMAIN")]
+ ),
+ self._scope(child.name(), [Privileges.deny("MANAGE_DOMAIN")]),
+ self._scope(
+ creation_parent.name(), [Privileges.deny("MANAGE_DOMAIN")]
+ ),
+ ],
+ )
+ snapshot = reader.get_domain(child.name())
+ # Read permission remains effective despite an explicit management deny.
+ self.assertEqual([], snapshot.list_members(DomainMemberFilter()))
+ self.assertEqual([], snapshot.list_subdomains())
+ self.assertEqual([], snapshot.list_subdomains_info())
+ writes = {
+ "alter": lambda client=reader: client.alter_domain(
+ child.name(), DomainChange.update_comment("denied")
+ ),
+ "delete": lambda client=reader: client.delete_domain(child.name()),
+ "publish": snapshot.publish,
+ "unpublish": snapshot.unpublish,
+ "attach": lambda current=snapshot: current.attach_to_parent(
+ target.name()
+ ),
+ "detach": snapshot.detach_from_parent,
+ "backing_tag": lambda current=snapshot: current.update_backing_tag(
+ None
+ ),
+ "subdomain": lambda client=reader: client.get_domain(
+ creation_parent.name()
+ ).create_subdomain(
+ "denied-subdomain", None, {}, TagValue("denied-tag"), True
+ ),
+ }
+ if user == "matrix_reader":
+ writes["create"] = lambda client=reader: client.create_domain(
+ "denied-domain", None, {}, TagValue("denied-create-tag"), True
+ )
+ for endpoint, operation in writes.items():
+ with self.subTest(user=user, endpoint=endpoint):
+ with self.assertRaises(ForbiddenException):
+ operation()
+
+ # Rejected writes leave the cached state unchanged.
+ unchanged = self.lake.get_domain(child.name())
+ self.assertEqual(Domain.Status.PUBLISHED, unchanged.status())
+ self.assertEqual(parent.name(), unchanged.parent())
+ self.assertEqual(child.backing_tag(), unchanged.backing_tag())
+ self.assertEqual(child.comment(), unchanged.comment())
+ self.assertEqual([child.name()], parent.list_subdomains())
+ self.assertEqual([], creation_parent.list_subdomains())
+ for name in ("denied-domain", "denied-subdomain"):
+ with self.assertRaises(NoSuchDomainException):
+ self.lake.get_domain(name)
+ for name in ("denied-tag", "denied-create-tag"):
+ with self.assertRaises(NoSuchTagException):
+ self.lake.get_tag(name)
+
+ def test_authorization_non_owner_manager_write_endpoints(self):
+ if not self.authorization:
+ self.skipTest("Requires an authorization-enabled server")
+ parent = self._domain("allowed-parent").publish()
+ target = self._domain("allowed-target").publish()
+ child = parent.create_subdomain(
+ "allowed-child", None, {}, TagValue("allowed-child-tag"), True
+ ).publish()
+ creation_parent = self._domain("allowed-creation-parent").publish()
+ manager = self._client("allowed_manager")
+ self._grant(
+ "allowed_manager",
+ [
+ SecurableObjects.of_metalake(
+ self.name,
+ [Privileges.allow("MANAGE_DOMAIN"), Privileges.allow("CREATE_TAG")],
+ )
+ ],
+ )
+
+ # Domain ownership stays with the admin; tag ownership is satisfied independently.
+ self.lake.create_tag("manager-binding-tag", None, {})
+ self.lake.set_owner(
+ MetadataObjects.parse("manager-binding-tag", MetadataObject.Type.TAG),
+ "allowed_manager",
+ Owner.Type.USER,
+ )
+ managed = manager.get_domain(child.name())
+ self.assertEqual(
+ "managed",
+ manager.alter_domain(
+ child.name(), DomainChange.update_comment("managed")
+ ).comment(),
+ )
+ self.assertEqual(Domain.Status.DRAFT, managed.unpublish().status())
+ self.assertEqual(Domain.Status.PUBLISHED, managed.publish().status())
+ self.assertEqual(
+ target.name(), managed.attach_to_parent(target.name()).parent()
+ )
+ self.assertIsNone(managed.detach_from_parent().parent())
+ self.assertEqual(
+ TagValue("manager-binding-tag"),
+ managed.update_backing_tag(TagValue("manager-binding-tag")).backing_tag(),
+ )
+ self.assertIsNone(managed.update_backing_tag(None).backing_tag())
+
+ # These legal requests match the denied creation requests with management now allowed.
+ created = manager.create_domain(
+ "denied-domain", None, {}, TagValue("denied-create-tag"), True
+ )
+ subdomain = manager.get_domain(creation_parent.name()).create_subdomain(
+ "denied-subdomain", None, {}, TagValue("denied-tag"), True
+ )
+ self.assertEqual(creation_parent.name(), subdomain.parent())
+ self.assertEqual(created.name(), manager.get_domain(created.name()).name())
+ self.assertTrue(manager.delete_domain(child.name()))
+ with self.assertRaises(NoSuchDomainException):
+ self.lake.get_domain(child.name())
+
+ def test_unicode_names_and_backing_tag_value_length_boundaries(self):
+ _, table = self._relational_table()
+ for index, value in enumerate(("x" * 256, "😀" * 128)):
+ with self.subTest(index=index):
+ tag_name = f"unicode-boundary-{index}"
+ self.lake.create_tag(tag_name, None, {})
+ name = f"财务/😀,区域{index}"
+ binding = TagValue(tag_name, value)
+ domain = self.lake.create_domain(
+ name, "Unicode comment 中文😀", {"region": "亚洲😀"}, binding, False
+ )
+ loaded = self.lake.get_domain(name)
+ self.assertEqual(name, loaded.name())
+ self.assertEqual(binding, loaded.backing_tag())
+ self.assertEqual({"region": "亚洲😀"}, loaded.properties())
+
+ # Boundary values survive serialization, storage and membership resolution.
+ table.supports_tags().assign_tags([{"name": tag_name, "value": value}])
+ direct = {(DomainRelation.Type.DIRECT, None, None)}
+ self._assert_table_relations(domain, table, direct)
+ renamed = f"税务/😀,地区{index}"
+ changed = self.lake.alter_domain(name, DomainChange.rename(renamed))
+ self.assertEqual(renamed, self.lake.get_domain(renamed).name())
+ self.assertEqual(binding, changed.backing_tag())
+ self._assert_table_relations(changed, table, direct)
+ with self.assertRaises(NoSuchDomainException):
+ self.lake.get_domain(name)
+
+ # The Python client must enforce Java's UTF-16-unit limit before HTTP.
+ with self.assertRaises(IllegalArgumentException):
+ changed.update_backing_tag(TagValue(tag_name, value + "x"))
+ self.assertEqual(binding, self.lake.get_domain(renamed).backing_tag())
+ rejected_name = f"rejected-boundary-{index}"
+ with self.assertRaises(IllegalArgumentException):
+ self.lake.create_domain(
+ rejected_name, None, {}, TagValue(tag_name, value + "x"), False
+ )
+ with self.assertRaises(NoSuchDomainException):
+ self.lake.get_domain(rejected_name)
+ self._assert_table_relations(changed, table, direct)
+
+ def test_real_response_value_equality_and_snapshot_protection(self):
+ _, table = self._relational_table()
+ created = self.lake.create_domain(
+ "value-contract",
+ "original",
+ {"key": "value"},
+ TagValue("value-contract-tag"),
+ True,
+ )
+ loaded = self.lake.get_domain(created.name())
+ listed = self.lake.list_domains_info()[0]
+ self.assertEqual(created, loaded)
+ self.assertEqual(loaded, listed)
+ self.assertEqual(hash(created), hash(loaded))
+ self.assertIn(listed, {created})
+ loaded.properties().clear()
+ self.assertEqual({"key": "value"}, loaded.properties())
+
+ table.supports_tags().assign_tags(["value-contract-tag"])
+ member_filter = DomainMemberFilter(types=[MetadataObject.Type.TABLE])
+ member = loaded.list_members(member_filter)[0]
+ reloaded = loaded.list_members(member_filter)[0]
+ metadata_object = MetadataObjects.parse(
+ "ice.schema.orders", MetadataObject.Type.TABLE
+ )
+ self.assertEqual(member, reloaded)
+ self.assertEqual(hash(member), hash(reloaded))
+ self.assertIn(reloaded, {member})
+ self.assertEqual(metadata_object, member.object())
+ self.assertEqual(hash(metadata_object), hash(member.object()))
+ self.assertEqual("ice.schema", member.object().parent())
+
+ # Modifying returned collections must not change snapshots or their set membership.
+ member_hash = hash(member)
+ member.relations().clear()
+ self.assertEqual([DomainRelation(DomainRelation.Type.DIRECT)], member.relations())
+ self.assertEqual(member_hash, hash(member))
+ reverse = table.supports_domains().list_domains_info()[0]
+ reverse_reloaded = table.supports_domains().list_domains_info()[0]
+ self.assertEqual(reverse, reverse_reloaded)
+ reverse_hash = hash(reverse)
+ reverse.relations().clear()
+ self.assertEqual([DomainRelation(DomainRelation.Type.DIRECT)], reverse.relations())
+ self.assertEqual(reverse_hash, hash(reverse))
+ self.assertIn(reverse_reloaded, {reverse})
+
+ changed = self.lake.alter_domain(
+ loaded.name(),
+ DomainChange.update_comment("changed"),
+ DomainChange.set_property("key", "changed"),
+ )
+ self.assertNotEqual(loaded, changed)
+ self.assertEqual("original", loaded.comment())
+ self.assertEqual({"key": "value"}, loaded.properties())
+ self.assertEqual(created, loaded)
+
+ def test_missing_domain_endpoint_matrix(self):
+ removed = self._domain("removed")
+ self.lake.delete_domain(removed.name())
+ operations = {
+ "alter": lambda: self.lake.alter_domain(
+ removed.name(), DomainChange.update_comment("missing")
+ ),
+ "publish": removed.publish,
+ "unpublish": removed.unpublish,
+ "attach": lambda: removed.attach_to_parent("missing-parent"),
+ "detach": removed.detach_from_parent,
+ "backing_tag": lambda: removed.update_backing_tag(None),
+ "subdomains": removed.list_subdomains,
+ "subdomains_info": removed.list_subdomains_info,
+ "members": lambda: removed.list_members(DomainMemberFilter()),
+ "create_subdomain": lambda: removed.create_subdomain(
+ "orphan", None, {}, TagValue("orphan-tag"), True
+ ),
+ }
+ for endpoint, operation in operations.items():
+ with self.subTest(endpoint=endpoint):
+ with self.assertRaises(NoSuchDomainException):
+ operation()
+ with self.assertRaises(NoSuchTagException):
+ self.lake.get_tag("orphan-tag")
+ self.assertFalse(self.lake.delete_domain(removed.name()))
+
+ def test_invalid_bindings_leave_no_partial_changes(self):
+ domain = self._domain("binding-errors")
+ with self.assertRaises(NoSuchDomainException):
+ domain.attach_to_parent("missing-parent")
+ self.assertIsNone(self.lake.get_domain(domain.name()).parent())
+ with self.assertRaises(NoSuchTagException):
+ domain.update_backing_tag(TagValue("absent-tag"))
+ self.assertEqual(
+ domain.backing_tag(), self.lake.get_domain(domain.name()).backing_tag()
+ )
+
+ # A rejected creation must not adopt an existing tag or leave an orphan domain.
+ invalid = [
+ ("missing-binding", TagValue("absent-tag"), False, NoSuchTagException),
+ ("existing-binding", domain.backing_tag(), True, TagAlreadyExistsException),
+ (
+ "valued-new-tag",
+ TagValue("invalid-new-tag", "value"),
+ True,
+ IllegalArgumentException,
+ ),
+ ]
+ for name, tag, create_tag, error in invalid:
+ with self.subTest(name=name):
+ with self.assertRaises(error):
+ self.lake.create_domain(name, None, {}, tag, create_tag)
+ with self.assertRaises(NoSuchDomainException):
+ self.lake.get_domain(name)
+ with self.assertRaises(NoSuchTagException):
+ self.lake.get_tag("invalid-new-tag")
+ self.assertIsNotNone(self.lake.get_tag(domain.backing_tag().name()))
diff --git a/clients/client-python/tests/integration/test_domain.py b/clients/client-python/tests/integration/test_domain.py
new file mode 100644
index 0000000000..09379c9005
--- /dev/null
+++ b/clients/client-python/tests/integration/test_domain.py
@@ -0,0 +1,1100 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import os
+import threading
+from http.client import HTTPConnection
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from urllib.parse import urlsplit
+import shutil
+import tempfile
+import uuid
+from unittest.mock import patch
+
+from gravitino import Catalog, GravitinoAdminClient, GravitinoClient, NameIdentifier
+from gravitino.api.authorization.owner import Owner
+from gravitino.api.authorization.privileges import Privileges
+from gravitino.api.authorization.securable_objects import SecurableObjects
+from gravitino.api.domain import (
+ Domain,
+ DomainChange,
+ DomainMemberFilter,
+ DomainRelation,
+)
+from gravitino.api.file.fileset import Fileset
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.api.metadata_objects import MetadataObjects
+from gravitino.api.rel.column import Column
+from gravitino.api.rel.sql_representation import SQLRepresentation
+from gravitino.api.rel.types.types import Types
+from gravitino.api.semantic.dataset import Dataset
+from gravitino.api.semantic.semantic_model_definition import SemanticModelDefinition
+from gravitino.api.tag import TagValue
+from gravitino.api.tag.tag_change import TagChange
+from gravitino.auth.simple_auth_provider import SimpleAuthProvider
+from gravitino.client.metadata_object_domain_operations import (
+ MetadataObjectDomainOperations,
+)
+from gravitino.exceptions.base import (
+ BackingTagAlreadyBoundException,
+ DomainAlreadyExistsException,
+ ForbiddenException,
+ IllegalArgumentException,
+ NoSuchDomainException,
+ NoSuchTagException,
+ NonEmptyDomainException,
+ TagAlreadyExistsException,
+)
+
+from tests.integration.integration_test_env import IntegrationTestEnv
+from tests.integration.domain_api_edges_mixin import DomainApiEdgesMixin
+
+
+class TestDomain(DomainApiEdgesMixin, IntegrationTestEnv):
+ """Domain SDK tests using the standard Python integration server lifecycle."""
+
+ AUTHORIZATION = False
+
+ def setUp(self):
+ self.uri = "http://localhost:8090"
+ self.authorization = self.AUTHORIZATION
+ self.admin = GravitinoAdminClient(
+ self.uri, auth_data_provider=SimpleAuthProvider()
+ )
+ self.addCleanup(self.admin.close)
+ self.name = "python_domain_" + uuid.uuid4().hex[:12]
+ self.admin.create_metalake(self.name, "", {})
+ self.addCleanup(self.admin.drop_metalake, self.name, True)
+ self.lake = GravitinoClient(
+ self.uri, self.name, auth_data_provider=SimpleAuthProvider()
+ )
+ self.addCleanup(self.lake.close)
+ self.directory = tempfile.mkdtemp(prefix="gravitino-domain-it-")
+ self.addCleanup(shutil.rmtree, self.directory)
+
+ def tearDown(self):
+ # addCleanup owns this suite's clients and UUID metalake in both server modes.
+ pass
+
+ def _domain(self, name):
+ return self.lake.create_domain(
+ name, None, {}, TagValue(name.replace(".", "_") + " tag"), True
+ )
+
+ def _client(self, user):
+ self.lake.add_user(user)
+ with patch.dict(os.environ, {"GRAVITINO_USER": user}):
+ client = GravitinoClient(
+ self.uri, self.name, auth_data_provider=SimpleAuthProvider()
+ )
+ self.addCleanup(client.close)
+ return client
+
+ def _grant(self, user, objects):
+ role = "role_" + uuid.uuid4().hex[:10]
+ self.lake.create_role(role, securable_objects=objects)
+ self.lake.grant_roles_to_user([role], user)
+ return role
+
+ @staticmethod
+ def _scope(name, privileges):
+ return SecurableObjects.parse(name, MetadataObject.Type.DOMAIN, privileges)
+
+ def _relational_table(self):
+ # This JDBC URI belongs to Iceberg, not to the server metadata-store backend.
+ catalog = self.lake.create_catalog(
+ "ice",
+ Catalog.Type.RELATIONAL,
+ "lakehouse-iceberg",
+ "",
+ {
+ "catalog-backend": "jdbc",
+ "warehouse": self.directory + "/warehouse",
+ "uri": "jdbc:h2:mem:" + self.name + ";DB_CLOSE_DELAY=-1;MODE=MYSQL",
+ "jdbc-driver": "org.h2.Driver",
+ "jdbc-initialize": "true",
+ },
+ )
+ catalog.as_schemas().create_schema("schema", "", {})
+ columns = [Column.of("id", Types.LongType.get())]
+ table = catalog.as_table_catalog().create_table(
+ NameIdentifier.of("schema", "orders"), columns, properties={}
+ )
+ return catalog, table
+
+ def _catalogs(self):
+ catalog, table = self._relational_table()
+ columns = [Column.of("id", Types.LongType.get())]
+ hidden = catalog.as_table_catalog().create_table(
+ NameIdentifier.of("schema", "hidden"), columns, properties={}
+ )
+ view = catalog.as_view_catalog().create_view(
+ NameIdentifier.of("schema", "orders_view"),
+ columns,
+ [SQLRepresentation("spark", "SELECT id FROM ice.schema.orders")],
+ )
+ semantic = catalog.as_semantic_model_catalog().create_semantic_model(
+ NameIdentifier.of("schema", "business"),
+ "",
+ SemanticModelDefinition(
+ [Dataset("orders", NameIdentifier.of("ice", "schema", "orders"))]
+ ),
+ {},
+ )
+
+ # Include independent fileset and model catalogs in the same domain scope.
+ files = self.lake.create_catalog(
+ "files",
+ Catalog.Type.FILESET,
+ "hadoop",
+ "",
+ {"location": self.directory + "/files"},
+ )
+ files.as_schemas().create_schema("schema", "", {})
+ fileset = files.as_fileset_catalog().create_fileset(
+ NameIdentifier.of("schema", "data"),
+ "",
+ Fileset.Type.EXTERNAL,
+ self.directory + "/external",
+ {},
+ )
+
+ models = self.lake.create_catalog("models", Catalog.Type.MODEL, "model", "", {})
+ models.as_schemas().create_schema("schema", "", {})
+ model = models.as_model_catalog().register_model(
+ NameIdentifier.of("schema", "model"), "", {}
+ )
+ return catalog, table, hidden, view, semantic, fileset, model
+
+ def test_lifecycle_special_names_and_snapshots(self):
+ name = "Finance/US. East,?&+%"
+ draft = self._domain(name)
+ self.assertEqual([name], self.lake.list_domains())
+ self.assertEqual(name, self.lake.list_domains_info()[0].name())
+ self.assertEqual(name, self.lake.get_domain(name).name())
+
+ # Mutations return new snapshots; the original draft retains its loaded state.
+ published = draft.publish()
+ self.assertEqual(Domain.Status.PUBLISHED, published.status())
+ self.assertEqual(Domain.Status.DRAFT, draft.status())
+ self.assertEqual(Domain.Status.DRAFT, published.unpublish().status())
+
+ renamed = self.lake.alter_domain(
+ name,
+ DomainChange.rename("Renamed/US. East,?&+%"),
+ DomainChange.update_comment("new"),
+ DomainChange.set_property("key", "value"),
+ )
+ self.assertEqual({"key": "value"}, renamed.properties())
+ self.assertIsNone(draft.comment())
+ self.assertEqual({}, draft.properties())
+ self.assertEqual(
+ TagValue(name.replace(".", "_") + " tag"), renamed.backing_tag()
+ )
+ self.assertEqual(
+ {},
+ self.lake.alter_domain(
+ renamed.name(), DomainChange.remove_property("key")
+ ).properties(),
+ )
+
+ self.assertIsNone(
+ self.lake.alter_domain(
+ renamed.name(), DomainChange.update_comment(None)
+ ).comment()
+ )
+ self.assertEqual("new", renamed.comment())
+
+ # The snapshot keeps its name, so reusing that name redirects future mutations.
+ with self.assertRaises(NoSuchDomainException):
+ draft.publish()
+ replacement = self.lake.create_domain(
+ name, None, None, TagValue("replacement"), True
+ )
+ self.assertEqual(Domain.Status.PUBLISHED, draft.publish().status())
+ self.assertEqual(Domain.Status.DRAFT, replacement.status())
+ self.assertTrue(self.lake.delete_domain(name))
+ self.assertFalse(self.lake.delete_domain(name))
+
+ def test_hierarchy_and_backing_tag_errors(self):
+ parent = self._domain("Parent/with. spaces")
+ other = self._domain("Other/parent. name")
+ child = parent.create_subdomain(
+ "Tax,EU/child", None, None, TagValue("child tag"), True
+ )
+ self.assertEqual([child.name()], parent.list_subdomains())
+ self.assertEqual(child.name(), parent.list_subdomains_info()[0].name())
+
+ # Publication and deletion must respect the child relationship.
+ with self.assertRaises(NonEmptyDomainException):
+ self.lake.delete_domain(parent.name())
+ with self.assertRaises(IllegalArgumentException):
+ child.publish()
+ parent.publish()
+ published_child = child.publish()
+ with self.assertRaises(IllegalArgumentException):
+ parent.unpublish()
+ with self.assertRaises(IllegalArgumentException):
+ published_child.attach_to_parent(other.name())
+
+ # Move and detach use current server state while the loaded parent stays unchanged.
+ other.publish()
+ self.assertEqual(other.name(), child.attach_to_parent(other.name()).parent())
+ self.assertEqual(parent.name(), child.parent())
+ self.assertEqual([], parent.list_subdomains())
+ self.assertIsNone(child.detach_from_parent().parent())
+ self.assertEqual(parent.name(), child.parent())
+
+ # Binding changes preserve tags and reject conflicting assignments.
+ self.lake.create_tag("new tag", None, {}, ["finance", "risk"])
+ self.assertEqual(
+ TagValue("new tag", "finance"),
+ child.update_backing_tag(TagValue("new tag", "finance")).backing_tag(),
+ )
+ conflict = self.lake.create_domain(
+ "conflict", None, None, TagValue("new tag", "risk"), False
+ )
+ with self.assertRaises(BackingTagAlreadyBoundException):
+ conflict.update_backing_tag(TagValue("new tag", "finance"))
+ with self.assertRaises(NoSuchTagException):
+ child.update_backing_tag(TagValue("missing"))
+ self.assertIsNone(child.update_backing_tag(None).backing_tag())
+ self.assertEqual(TagValue("child tag"), child.backing_tag())
+ with self.assertRaises(TagAlreadyExistsException):
+ self.lake.create_domain("new", None, {}, TagValue("child tag"), True)
+ with self.assertRaises(DomainAlreadyExistsException):
+ self.lake.create_domain(parent.name(), None, {}, TagValue("unused"), True)
+
+ def test_members_relations_filters_and_nearest_assignment(self):
+ catalog, table, hidden, view, semantic, fileset, model = self._catalogs()
+ self.lake.create_tag("department", None, {}, ["finance", "risk"])
+ finance = self.lake.create_domain(
+ "Finance/US. East,?&+%", None, {}, TagValue("department", "finance"), False
+ )
+ risk = self.lake.create_domain(
+ "Risk,EU", None, {}, TagValue("department", "risk"), False
+ )
+ child = finance.create_subdomain(
+ "Trading,US/with. spaces?&+%", None, {}, TagValue("trading"), True
+ )
+
+ # The schema grants Finance membership; the table assignment takes precedence for Risk.
+ catalog.as_schemas().load_schema("schema").supports_tags().assign_tags(
+ [{"name": "department", "value": "finance"}]
+ )
+ table.supports_tags().assign_tags(["trading"])
+ hidden.supports_tags().assign_tags([{"name": "department", "value": "risk"}])
+ fileset.supports_tags().assign_tags(
+ [{"name": "department", "value": "finance"}]
+ )
+ model.supports_tags().assign_tags([{"name": "department", "value": "finance"}])
+
+ # The same table has both inherited and subdomain relations, with no precedence.
+ members = {
+ m.object().full_name(): m
+ for m in finance.list_members(DomainMemberFilter())
+ }
+ self.assertEqual(
+ {
+ "ice.schema.orders",
+ "ice.schema.orders_view",
+ "ice.schema.business",
+ "files.schema.data",
+ "models.schema.model",
+ },
+ set(members),
+ )
+ self.assertEqual(
+ {DomainRelation.Type.INHERITED, DomainRelation.Type.VIA_SUBDOMAIN},
+ {r.type() for r in members["ice.schema.orders"].relations()},
+ )
+ inherited = next(
+ r
+ for r in members["ice.schema.orders"].relations()
+ if r.type() == DomainRelation.Type.INHERITED
+ )
+ self.assertEqual("ice.schema", inherited.source().full_name())
+ self.assertEqual(
+ DomainRelation.Type.DIRECT,
+ members["files.schema.data"].relations()[0].type(),
+ )
+ self.assertEqual(
+ ["ice.schema.hidden"],
+ [m.object().full_name() for m in risk.list_members(DomainMemberFilter())],
+ )
+
+ # Reverse lookup must expose the same domain on every supported leaf resource.
+ for resource in (table, view, semantic, fileset, model):
+ self.assertIn(finance.name(), resource.supports_domains().list_domains())
+ self.assertIn(
+ finance.name(),
+ [d.name() for d in resource.supports_domains().list_domains_info()],
+ )
+
+ # Scope names contain commas; repeated names select a union rather than a CSV list.
+ self.assertEqual(
+ ["ice.schema.orders"],
+ [
+ m.object().full_name()
+ for m in finance.list_members(
+ DomainMemberFilter(domains=[child.name(), "unknown,scope"])
+ )
+ ],
+ )
+ self.assertEqual(
+ 5,
+ len(
+ finance.list_members(
+ DomainMemberFilter(domains=[finance.name(), child.name()])
+ )
+ ),
+ )
+ self.assertEqual(
+ {MetadataObject.Type.VIEW, MetadataObject.Type.MODEL},
+ {
+ m.object().type()
+ for m in finance.list_members(
+ DomainMemberFilter(
+ types=[MetadataObject.Type.VIEW, MetadataObject.Type.MODEL]
+ )
+ )
+ },
+ )
+ self.assertEqual(
+ 2, len(finance.list_members(DomainMemberFilter(name_contains="ORDERS")))
+ )
+ self.assertEqual(
+ [], finance.list_members(DomainMemberFilter(name_contains="/ ?&+%,"))
+ )
+ self.assertEqual(
+ [], finance.list_members(DomainMemberFilter(domains=["unknown,scope"]))
+ )
+
+ # Hierarchy and domain-name changes must appear without retagging any object.
+ new_parent = self._domain("new parent")
+ child.attach_to_parent(new_parent.name())
+ self.assertNotIn(new_parent.name(), view.supports_domains().list_domains())
+ self.assertIn(new_parent.name(), table.supports_domains().list_domains())
+ self.lake.alter_domain(child.name(), DomainChange.rename("renamed/child"))
+ self.assertIn("renamed/child", table.supports_domains().list_domains())
+ self.lake.delete_domain("renamed/child")
+ self.assertNotIn(new_parent.name(), table.supports_domains().list_domains())
+ self.assertEqual("trading", self.lake.get_tag("trading").name())
+ finance.update_backing_tag(None)
+ self.assertEqual([], table.supports_domains().list_domains())
+
+ def test_authorization_visibility_inheritance_denies_and_ownership(self):
+ if not self.authorization:
+ self.skipTest("Requires an authorization-enabled server")
+ parent = self._domain("Parent/auth. scope")
+ child = parent.create_subdomain(
+ "Child/auth. scope", None, {}, TagValue("child"), True
+ )
+ reader = self._client("reader")
+ manager = self._client("manager")
+ outsider = self._client("outsider")
+ owner = self._client("domain_owner")
+ self._grant(
+ "reader", [self._scope(parent.name(), [Privileges.allow("USE_DOMAIN")])]
+ )
+ self._grant(
+ "manager", [self._scope(parent.name(), [Privileges.allow("MANAGE_DOMAIN")])]
+ )
+
+ # USE_DOMAIN cannot reveal drafts; inherited MANAGE_DOMAIN can.
+ self.assertEqual([], reader.list_domains())
+ with self.assertRaises(NoSuchDomainException):
+ reader.get_domain(parent.name())
+ self.assertEqual(child.name(), manager.get_domain(child.name()).name())
+
+ # Publication reveals one level at a time to the reader.
+ manager.get_domain(parent.name()).publish()
+ self.assertEqual([parent.name()], reader.list_domains())
+ with self.assertRaises(NoSuchDomainException):
+ reader.get_domain(child.name())
+ manager.get_domain(child.name()).publish()
+ self.assertEqual({parent.name(), child.name()}, set(reader.list_domains()))
+ self.assertEqual([], outsider.list_domains())
+ with self.assertRaises(ForbiddenException):
+ outsider.get_domain(parent.name())
+ with self.assertRaises(ForbiddenException):
+ reader.get_domain(parent.name()).unpublish()
+
+ # A child deny overrides a grant inherited from the parent.
+ self._grant(
+ "reader", [self._scope(child.name(), [Privileges.deny("USE_DOMAIN")])]
+ )
+ self.assertEqual([parent.name()], reader.list_domains())
+ with self.assertRaises(ForbiddenException):
+ reader.get_domain(child.name())
+
+ # Owners bypass denies, and metalake grants also apply to child domains.
+ self.lake.set_owner(
+ MetadataObjects.parse(parent.name(), MetadataObject.Type.DOMAIN),
+ "domain_owner",
+ Owner.Type.USER,
+ )
+ self._grant(
+ "domain_owner",
+ [
+ self._scope(
+ child.name(),
+ [Privileges.deny("USE_DOMAIN"), Privileges.deny("MANAGE_DOMAIN")],
+ )
+ ],
+ )
+ self.assertEqual(child.name(), owner.get_domain(child.name()).name())
+ self.assertEqual(
+ Domain.Status.DRAFT, owner.get_domain(child.name()).unpublish().status()
+ )
+ inherited = self._client("lake_manager")
+ self._grant(
+ "lake_manager",
+ [
+ SecurableObjects.of_metalake(
+ self.name, [Privileges.allow("MANAGE_DOMAIN")]
+ )
+ ],
+ )
+ self.assertEqual(child.name(), inherited.get_domain(child.name()).name())
+
+ def test_authorization_backing_tag_creation_and_binding(self):
+ if not self.authorization:
+ self.skipTest("Requires an authorization-enabled server")
+ creator = self._client("creator")
+ self._grant(
+ "creator",
+ [
+ SecurableObjects.of_metalake(
+ self.name, [Privileges.allow("MANAGE_DOMAIN")]
+ )
+ ],
+ )
+ with self.assertRaises(ForbiddenException):
+ creator.create_domain("denied", None, {}, TagValue("new tag"), True)
+ self._grant(
+ "creator",
+ [SecurableObjects.of_metalake(self.name, [Privileges.allow("CREATE_TAG")])],
+ )
+
+ # Creating a backing tag needs CREATE_TAG in addition to domain management.
+ created = creator.create_domain(
+ "created", None, {}, TagValue("owned tag"), True
+ )
+
+ # Managing a domain does not confer ownership of another user's tag.
+ self.lake.create_tag("foreign tag", None, {})
+ with self.assertRaises(ForbiddenException):
+ created.update_backing_tag(TagValue("foreign tag"))
+ with self.assertRaises(ForbiddenException):
+ creator.create_domain("foreign", None, {}, TagValue("foreign tag"), False)
+
+ self.lake.set_owner(
+ MetadataObjects.parse("foreign tag", MetadataObject.Type.TAG),
+ "creator",
+ Owner.Type.USER,
+ )
+ bound = creator.create_domain("bound", None, {}, TagValue("foreign tag"), False)
+ self.assertEqual(TagValue("foreign tag"), bound.backing_tag())
+ self.assertIsNone(bound.update_backing_tag(None).backing_tag())
+ self.assertEqual(
+ TagValue("foreign tag"),
+ created.update_backing_tag(TagValue("foreign tag")).backing_tag(),
+ )
+ with self.assertRaises(BackingTagAlreadyBoundException):
+ creator.create_domain("conflict", None, {}, TagValue("foreign tag"), False)
+ with self.assertRaises(NoSuchTagException):
+ creator.create_domain("missing", None, {}, TagValue("missing tag"), False)
+
+ def test_authorization_member_access_without_tag_privileges(self):
+ if not self.authorization:
+ self.skipTest("Requires an authorization-enabled server")
+ catalog, table, _, _, _, _, _ = self._catalogs()
+ parent = self._domain("access parent")
+ child = parent.create_subdomain(
+ "access child", None, {}, TagValue("child tag"), True
+ )
+ parent.publish()
+ catalog.as_schemas().load_schema("schema").supports_tags().assign_tags(
+ [parent.backing_tag().name()]
+ )
+ table.supports_tags().assign_tags(["child tag"])
+
+ # Grant access to one table, without granting any tag privileges.
+ reader = self._client("object_reader")
+ cat_scope = SecurableObjects.of_catalog(
+ "ice", [Privileges.allow("USE_CATALOG")]
+ )
+ schema_scope = SecurableObjects.of_schema(
+ SecurableObjects.of_catalog("ice", []),
+ "schema",
+ [Privileges.allow("USE_SCHEMA")],
+ )
+ table_scope = SecurableObjects.of_table(
+ schema_scope, "orders", [Privileges.allow("SELECT_TABLE")]
+ )
+ self._grant(
+ "object_reader",
+ [
+ self._scope(parent.name(), [Privileges.allow("USE_DOMAIN")]),
+ cat_scope,
+ schema_scope,
+ table_scope,
+ ],
+ )
+
+ visible = reader.get_domain(parent.name()).list_members(DomainMemberFilter())
+ self.assertEqual(
+ ["ice.schema.orders"], [m.object().full_name() for m in visible]
+ )
+ self.assertEqual(
+ [DomainRelation.Type.INHERITED], [r.type() for r in visible[0].relations()]
+ )
+
+ self.assertEqual("ice.schema", visible[0].relations()[0].source().full_name())
+ self.assertEqual([], reader.get_domain(parent.name()).list_subdomains())
+ self.assertEqual([], reader.get_domain(parent.name()).list_subdomains_info())
+ self.assertEqual(
+ [parent.name()], [d.name() for d in reader.list_domains_info()]
+ )
+ self.assertEqual(
+ [],
+ reader.get_domain(parent.name()).list_members(
+ DomainMemberFilter(domains=[child.name()])
+ ),
+ )
+
+ # A hidden child contributes no roll-up relation until it is published.
+ child.publish()
+ visible = reader.get_domain(parent.name()).list_members(DomainMemberFilter())
+ self.assertEqual(
+ {DomainRelation.Type.INHERITED, DomainRelation.Type.VIA_SUBDOMAIN},
+ {r.type() for r in visible[0].relations()},
+ )
+ lookup = MetadataObjectDomainOperations(
+ self.name,
+ MetadataObjects.parse("ice.schema.orders", MetadataObject.Type.TABLE),
+ reader.get_metalake().rest_client,
+ )
+ self.assertEqual({parent.name(), child.name()}, set(lookup.list_domains()))
+
+ # Denying the child removes its relation while preserving inherited parent membership.
+ self._grant(
+ "object_reader",
+ [self._scope(child.name(), [Privileges.deny("USE_DOMAIN")])],
+ )
+ parent_only = reader.get_domain(parent.name()).list_members(
+ DomainMemberFilter()
+ )
+ self.assertEqual(1, len(parent_only))
+ self.assertEqual(
+ [DomainRelation.Type.INHERITED],
+ [r.type() for r in parent_only[0].relations()],
+ )
+ self.assertEqual([parent.name()], lookup.list_domains())
+ self.assertEqual(1, len(lookup.list_domains_info()[0].relations()))
+
+ # Revoking object access removes membership and blocks reverse lookup.
+ self._grant(
+ "object_reader",
+ [
+ SecurableObjects.of_table(
+ schema_scope, "orders", [Privileges.deny("SELECT_TABLE")]
+ )
+ ],
+ )
+ self.assertEqual(
+ [], reader.get_domain(parent.name()).list_members(DomainMemberFilter())
+ )
+ with self.assertRaises(ForbiddenException):
+ lookup.list_domains()
+
+ def test_authorization_move_rechecks_current_parent_and_metalake_owner(self):
+ if not self.authorization:
+ self.skipTest("Requires an authorization-enabled server")
+ first = self._domain("first").publish()
+ second = self._domain("second").publish()
+ child = first.create_subdomain(
+ "moving/child. name", None, {}, TagValue("moving tag"), True
+ ).publish()
+ manager = self._client("moving_manager")
+ owner = self._client("lake_owner")
+ self._grant(
+ "moving_manager",
+ [self._scope(first.name(), [Privileges.allow("MANAGE_DOMAIN")])],
+ )
+ snapshot = manager.get_domain(child.name())
+ with self.assertRaises(ForbiddenException):
+ snapshot.attach_to_parent(second.name())
+
+ # The old parent grant must stop authorizing mutations after the move.
+ child.attach_to_parent(second.name())
+ with self.assertRaises(ForbiddenException):
+ snapshot.unpublish()
+
+ self._grant(
+ "moving_manager",
+ [self._scope(second.name(), [Privileges.allow("MANAGE_DOMAIN")])],
+ )
+ self.assertEqual(Domain.Status.DRAFT, snapshot.unpublish().status())
+ self.assertEqual(first.name(), snapshot.parent())
+ self._grant(
+ "moving_manager",
+ [self._scope(child.name(), [Privileges.deny("MANAGE_DOMAIN")])],
+ )
+ with self.assertRaises(NoSuchDomainException):
+ manager.get_domain(child.name())
+ self._grant(
+ "lake_owner",
+ [
+ self._scope(
+ child.name(),
+ [Privileges.deny("MANAGE_DOMAIN"), Privileges.deny("USE_DOMAIN")],
+ )
+ ],
+ )
+
+ # Restore ownership even on assertion failure so the fixture can delete its metalake.
+ root = MetadataObjects.parse(self.name, MetadataObject.Type.METALAKE)
+ self.lake.set_owner(root, "lake_owner", Owner.Type.USER)
+ try:
+ self.assertEqual(child.name(), owner.get_domain(child.name()).name())
+ finally:
+ owner.set_owner(root, "anonymous", Owner.Type.USER)
+
+ def test_encoded_names_through_preserving_proxy(self):
+ target = urlsplit(self.uri)
+
+ class ProxyHandler(BaseHTTPRequestHandler):
+ def _forward(self):
+ # Keep the raw path and repeated query parameters, including encoded slashes.
+ connection = HTTPConnection(target.hostname, target.port, timeout=30)
+ try:
+ body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ headers = {
+ key: self.headers[key]
+ for key in ("Authorization", "Content-Type", "Accept")
+ if key in self.headers
+ }
+ connection.request(self.command, self.path, body, headers)
+ response = connection.getresponse()
+ data = response.read()
+
+ self.send_response(response.status)
+ self.send_header(
+ "Content-Type",
+ response.getheader("Content-Type", "application/json"),
+ )
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ finally:
+ connection.close()
+
+ do_GET = _forward
+ do_POST = _forward
+ do_PATCH = _forward
+ do_DELETE = _forward
+
+ def log_message(self, format, *args): # pylint: disable=redefined-builtin
+ pass
+
+ proxy = ThreadingHTTPServer(("127.0.0.1", 0), ProxyHandler)
+ worker = threading.Thread(target=proxy.serve_forever, daemon=True)
+ worker.start()
+ client = None
+ try:
+ # This proxy is owned by the Python suite and uses its ordinary server fixture.
+ client = GravitinoClient(
+ f"http://127.0.0.1:{proxy.server_port}",
+ self.name,
+ auth_data_provider=SimpleAuthProvider(),
+ )
+ domain = client.create_domain(
+ "Proxy/US. East,?&+%", None, {}, TagValue("proxy tag"), True
+ )
+ self.assertEqual(
+ "Proxy/US. East,?&+%", client.get_domain(domain.name()).name()
+ )
+ self.assertEqual(Domain.Status.PUBLISHED, domain.publish().status())
+ catalog, table = self._relational_table()
+ other = catalog.as_table_catalog().create_table(
+ NameIdentifier.of("schema", "other"),
+ [Column.of("id", Types.LongType.get())],
+ "",
+ {},
+ )
+ first = domain.create_subdomain(
+ "scope,one", None, {}, TagValue("proxy-first"), True
+ )
+ second = domain.create_subdomain(
+ "scope/two?&+%", None, {}, TagValue("proxy-second"), True
+ )
+ table.supports_tags().assign_tags(["proxy-first"])
+ other.supports_tags().assign_tags(["proxy-second"])
+
+ # Nonempty results detect dropped scopes, comma splitting and query decoding errors.
+ selected = domain.list_members(
+ DomainMemberFilter(
+ domains=[first.name(), "unknown,scope"], name_contains="ORDERS"
+ )
+ )
+ self.assertEqual(
+ ["ice.schema.orders"], [m.object().full_name() for m in selected]
+ )
+ self.assertEqual(
+ {
+ (
+ DomainRelation.Type.VIA_SUBDOMAIN,
+ MetadataObject.Type.DOMAIN,
+ first.name(),
+ )
+ },
+ self._relation_keys(selected[0].relations()),
+ )
+ self.assertEqual(
+ 2,
+ len(
+ domain.list_members(
+ DomainMemberFilter(domains=[first.name(), second.name()])
+ )
+ ),
+ )
+ self.assertEqual(
+ ["ice.schema.other"],
+ [
+ m.object().full_name()
+ for m in domain.list_members(
+ DomainMemberFilter(domains=[second.name()])
+ )
+ ],
+ )
+ self.assertEqual(
+ [], domain.list_members(DomainMemberFilter(domains=["unknown,scope"]))
+ )
+ self.assertEqual(
+ [],
+ domain.list_members(
+ DomainMemberFilter(domains=[first.name()], name_contains="other")
+ ),
+ )
+ self.assertTrue(client.delete_domain(first.name()))
+ self.assertTrue(client.delete_domain(second.name()))
+ self.assertTrue(client.delete_domain(domain.name()))
+ finally:
+ if client is not None:
+ client.close()
+ proxy.shutdown()
+ proxy.server_close()
+ worker.join(timeout=10)
+
+ @staticmethod
+ def _relation_keys(relations):
+ return {
+ (
+ relation.type(),
+ relation.source().type() if relation.source() else None,
+ relation.source().full_name() if relation.source() else None,
+ )
+ for relation in relations
+ }
+
+ def _assert_table_relations(self, domain, table, expected):
+ members = domain.list_members(
+ DomainMemberFilter(
+ types=[MetadataObject.Type.TABLE], name_contains="ice.schema.orders"
+ )
+ )
+ reverse = [
+ candidate
+ for candidate in table.supports_domains().list_domains_info()
+ if candidate.name() == domain.name()
+ ]
+ self.assertEqual(
+ bool(expected), domain.name() in table.supports_domains().list_domains()
+ )
+ if not expected:
+ self.assertEqual([], members)
+ self.assertEqual([], reverse)
+ return
+
+ self.assertEqual(1, len(members))
+ self.assertEqual("ice.schema.orders", members[0].object().full_name())
+ self.assertEqual(MetadataObject.Type.TABLE, members[0].object().type())
+ self.assertEqual(len(expected), len(members[0].relations()))
+ self.assertEqual(expected, self._relation_keys(members[0].relations()))
+ self.assertEqual(1, len(reverse))
+ self.assertEqual(len(expected), len(reverse[0].relations()))
+ self.assertEqual(expected, self._relation_keys(reverse[0].relations()))
+ self.assertEqual([], domain.relations())
+ for relation in members[0].relations():
+ if relation.type() == DomainRelation.Type.VIA_SUBDOMAIN:
+ self.assertEqual(
+ relation.source().full_name(), relation.source().name()
+ )
+ self.assertIsNone(relation.source().parent())
+
+ def test_nearest_tag_assignment_and_value_matching(self):
+ catalog, table = self._relational_table()
+ self.lake.create_tag("department", None, {}, ["finance", "risk", "Finance"])
+ finance = self.lake.create_domain(
+ "Finance", None, {}, TagValue("department", "finance"), False
+ )
+ risk = self.lake.create_domain(
+ "Risk", None, {}, TagValue("department", "risk"), False
+ )
+ capitalized = self.lake.create_domain(
+ "Capitalized", None, {}, TagValue("department", "Finance"), False
+ )
+ inherited_catalog = (
+ DomainRelation.Type.INHERITED,
+ MetadataObject.Type.CATALOG,
+ "ice",
+ )
+ inherited_schema = (
+ DomainRelation.Type.INHERITED,
+ MetadataObject.Type.SCHEMA,
+ "ice.schema",
+ )
+ direct = (DomainRelation.Type.DIRECT, None, None)
+ schema_tags = catalog.as_schemas().load_schema("schema").supports_tags()
+
+ with self.assertRaises(IllegalArgumentException):
+ finance.update_backing_tag(TagValue("department", "unknown"))
+ self.assertEqual(
+ TagValue("department", "finance"),
+ self.lake.get_domain(finance.name()).backing_tag(),
+ )
+
+ # A nearer schema assignment masks the catalog's value of the same tag.
+ catalog.supports_tags().assign_tags(
+ [{"name": "department", "value": "finance"}]
+ )
+ self._assert_table_relations(finance, table, {inherited_catalog})
+ self._assert_table_relations(capitalized, table, set())
+ schema_tags.assign_tags([{"name": "department", "value": "risk"}])
+ self._assert_table_relations(finance, table, set())
+ self._assert_table_relations(risk, table, {inherited_schema})
+
+ # Each direct value matches exactly; remaining values still mask inherited assignments.
+ table.supports_tags().assign_tags(
+ [
+ {"name": "department", "value": "finance"},
+ {"name": "department", "value": "Finance"},
+ ]
+ )
+ self._assert_table_relations(finance, table, {direct})
+ self._assert_table_relations(capitalized, table, {direct})
+ self._assert_table_relations(risk, table, set())
+ table.supports_tags().assign_tags(
+ tags_to_remove=[{"name": "department", "value": "finance"}]
+ )
+ self._assert_table_relations(finance, table, set())
+ self._assert_table_relations(capitalized, table, {direct})
+ self._assert_table_relations(risk, table, set())
+
+ # Removing assignments reveals the next ancestor, until no assignment remains.
+ table.supports_tags().assign_tags(
+ tags_to_remove=[{"name": "department", "value": "Finance"}]
+ )
+ self._assert_table_relations(risk, table, {inherited_schema})
+ schema_tags.assign_tags(
+ tags_to_remove=[{"name": "department", "value": "risk"}]
+ )
+ self._assert_table_relations(finance, table, {inherited_catalog})
+ catalog.supports_tags().assign_tags(
+ tags_to_remove=[{"name": "department", "value": "finance"}]
+ )
+ for domain in (finance, risk, capitalized):
+ self._assert_table_relations(domain, table, set())
+
+ # A backing binding without a value matches any valued or valueless assignment.
+ self.lake.create_tag("any-value", None, {})
+ any_value = self.lake.create_domain(
+ "Any", None, {}, TagValue("any-value"), False
+ )
+ table.supports_tags().assign_tags([{"name": "any-value", "value": "arbitrary"}])
+ self._assert_table_relations(any_value, table, {direct})
+ table.supports_tags().assign_tags(
+ tags_to_remove=[{"name": "any-value", "value": "arbitrary"}]
+ )
+ table.supports_tags().assign_tags(["any-value"])
+ self._assert_table_relations(any_value, table, {direct})
+ with self.assertRaises(BackingTagAlreadyBoundException):
+ self.lake.create_domain(
+ "Mixed", None, {}, TagValue("any-value", "arbitrary"), False
+ )
+
+ def test_multiple_subdomain_relations_and_backing_tag_identity(self):
+ catalog, table = self._relational_table()
+ parent = self._domain("Parent")
+ first = parent.create_subdomain(
+ "First/child.A", None, {}, TagValue("first-tag"), True
+ )
+ second = parent.create_subdomain(
+ "Second,child.B", None, {}, TagValue("second-tag"), True
+ )
+ catalog.supports_tags().assign_tags(["first-tag"])
+ catalog.as_schemas().load_schema("schema").supports_tags().assign_tags(
+ ["second-tag"]
+ )
+ table.supports_tags().assign_tags([parent.backing_tag().name()])
+ direct = (DomainRelation.Type.DIRECT, None, None)
+ first_path = (
+ DomainRelation.Type.VIA_SUBDOMAIN,
+ MetadataObject.Type.DOMAIN,
+ first.name(),
+ )
+ second_path = (
+ DomainRelation.Type.VIA_SUBDOMAIN,
+ MetadataObject.Type.DOMAIN,
+ second.name(),
+ )
+ inherited_catalog = (
+ DomainRelation.Type.INHERITED,
+ MetadataObject.Type.CATALOG,
+ "ice",
+ )
+ inherited_schema = (
+ DomainRelation.Type.INHERITED,
+ MetadataObject.Type.SCHEMA,
+ "ice.schema",
+ )
+
+ # The member is deduplicated, while all direct and child paths remain visible.
+ self._assert_table_relations(parent, table, {direct, first_path, second_path})
+ self._assert_table_relations(first, table, {inherited_catalog})
+ self._assert_table_relations(second, table, {inherited_schema})
+ selected = parent.list_members(
+ DomainMemberFilter(
+ domains=[first.name(), second.name()],
+ types=[MetadataObject.Type.TABLE],
+ name_contains="ORDERS",
+ )
+ )
+ self.assertEqual(1, len(selected))
+ self.assertEqual(
+ {direct, first_path, second_path},
+ self._relation_keys(selected[0].relations()),
+ )
+ self.assertEqual(
+ [],
+ parent.list_members(
+ DomainMemberFilter(
+ domains=[first.name()], types=[MetadataObject.Type.VIEW]
+ )
+ ),
+ )
+ self.assertEqual(
+ [], first.list_members(DomainMemberFilter(domains=[second.name()]))
+ )
+
+ # Removing one route must preserve the other routes and the member's own child scope.
+ table.supports_tags().assign_tags(tags_to_remove=[parent.backing_tag().name()])
+ self._assert_table_relations(parent, table, {first_path, second_path})
+ second.detach_from_parent()
+ self._assert_table_relations(parent, table, {first_path})
+ first = self.lake.alter_domain(
+ first.name(), DomainChange.rename("Renamed/child.A")
+ )
+ first_path = (
+ DomainRelation.Type.VIA_SUBDOMAIN,
+ MetadataObject.Type.DOMAIN,
+ first.name(),
+ )
+ self._assert_table_relations(parent, table, {first_path})
+ parent = self.lake.alter_domain(
+ parent.name(), DomainChange.rename("Renamed/parent.P")
+ )
+ self.assertEqual(parent.name(), self.lake.get_domain(first.name()).parent())
+ self._assert_table_relations(parent, table, {first_path})
+
+ # Tag identity survives rename, but deletion and same-name recreation cannot restore a binding.
+ self.lake.alter_tag("first-tag", TagChange.rename("renamed-first-tag"))
+ self.assertEqual(
+ "renamed-first-tag", self.lake.get_domain(first.name()).backing_tag().name()
+ )
+ self._assert_table_relations(parent, table, {first_path})
+ self.lake.delete_tag("renamed-first-tag")
+ self.assertIsNone(self.lake.get_domain(first.name()).backing_tag())
+ self._assert_table_relations(parent, table, set())
+ self.lake.create_tag("renamed-first-tag", None, {})
+ catalog.supports_tags().assign_tags(["renamed-first-tag"])
+ self._assert_table_relations(first, table, set())
+ self._assert_table_relations(parent, table, set())
+ first.update_backing_tag(TagValue("renamed-first-tag"))
+ self._assert_table_relations(first, table, {inherited_catalog})
+ self._assert_table_relations(parent, table, {first_path})
+ first.update_backing_tag(None)
+ self._assert_table_relations(parent, table, set())
+
+ def test_invalid_hierarchy_atomic_creation_and_idempotence(self):
+ parent = self._domain("Parent")
+ other = self._domain("Other")
+ child = parent.create_subdomain("Child", None, {}, TagValue("child-tag"), True)
+
+ self.lake.create_tag("existing-valued-tag", None, {}, ["finance"])
+ bound = parent.create_subdomain(
+ "Bound",
+ "existing tag",
+ {"key": "value"},
+ TagValue("existing-valued-tag", "finance"),
+ False,
+ )
+ self.assertEqual(parent.name(), bound.parent())
+ self.assertEqual(
+ TagValue("existing-valued-tag", "finance"), bound.backing_tag()
+ )
+ self.assertEqual({"key": "value"}, bound.properties())
+ with self.assertRaises(DomainAlreadyExistsException):
+ self.lake.alter_domain(other.name(), DomainChange.rename(parent.name()))
+ self.assertEqual(other.name(), self.lake.get_domain(other.name()).name())
+
+ # Rejected hierarchy or duplicate-name creation must not leave a domain or backing tag.
+ with self.assertRaises(IllegalArgumentException):
+ child.create_subdomain(
+ "Grandchild", None, {}, TagValue("grandchild-tag"), True
+ )
+ with self.assertRaises(NoSuchDomainException):
+ self.lake.get_domain("Grandchild")
+ with self.assertRaises(NoSuchTagException):
+ self.lake.get_tag("grandchild-tag")
+ with self.assertRaises(DomainAlreadyExistsException):
+ self.lake.create_domain(
+ parent.name(), None, {}, TagValue("unused-tag"), True
+ )
+ with self.assertRaises(NoSuchTagException):
+ self.lake.get_tag("unused-tag")
+ for domain, target in ((child, child), (other, child), (parent, other)):
+ with self.assertRaises(IllegalArgumentException):
+ domain.attach_to_parent(target.name())
+ self.assertEqual(parent.name(), child.attach_to_parent(parent.name()).parent())
+ self.assertEqual(
+ child.backing_tag(),
+ child.update_backing_tag(child.backing_tag()).backing_tag(),
+ )
+
+ # Repeated state changes and detach calls are safe; old snapshots stay unchanged.
+ self.assertEqual(Domain.Status.PUBLISHED, parent.publish().publish().status())
+ self.assertEqual(Domain.Status.PUBLISHED, child.publish().publish().status())
+ self.assertEqual(Domain.Status.DRAFT, child.unpublish().unpublish().status())
+ self.assertEqual(Domain.Status.DRAFT, parent.unpublish().unpublish().status())
+ self.assertIsNone(parent.detach_from_parent().parent())
+ self.assertIsNone(child.detach_from_parent().detach_from_parent().parent())
+ self.assertEqual(parent.name(), child.parent())
+ self.assertIsNotNone(child.audit_info().creator())
+ self.assertIsNotNone(child.audit_info().create_time())
diff --git a/clients/client-python/tests/integration/test_domain_authorization.py b/clients/client-python/tests/integration/test_domain_authorization.py
new file mode 100644
index 0000000000..2cecfcc49f
--- /dev/null
+++ b/clients/client-python/tests/integration/test_domain_authorization.py
@@ -0,0 +1,25 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from tests.integration.integration_test_env import AuthorizationIntegrationTestEnv
+from tests.integration import test_domain
+
+
+class TestDomainAuthorization(test_domain.TestDomain, AuthorizationIntegrationTestEnv):
+ """Use the existing authorization environment with the same Domain contract tests."""
+
+ AUTHORIZATION = True
diff --git a/clients/client-python/tests/unittests/authorization/test_domain_authorization.py b/clients/client-python/tests/unittests/authorization/test_domain_authorization.py
new file mode 100644
index 0000000000..1ac27dec2c
--- /dev/null
+++ b/clients/client-python/tests/unittests/authorization/test_domain_authorization.py
@@ -0,0 +1,93 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import json
+import unittest
+
+from gravitino.api.authorization.privileges import Privilege, Privileges
+from gravitino.api.authorization.securable_objects import SecurableObjects
+from gravitino.api.metadata_object import MetadataObject
+from gravitino.client.dto_converters import DTOConverters
+from gravitino.dto.authorization.privilege_dto import PrivilegeDTO
+from gravitino.dto.authorization.securable_object_dto import SecurableObjectDTO
+from gravitino.exceptions.base import (
+ GravitinoRuntimeException,
+ RESTException,
+ IllegalArgumentException,
+)
+
+
+class TestDomainAuthorization(unittest.TestCase):
+ def test_domain_privileges_and_role_wire_round_trip(self):
+ for name, bit in (("MANAGE_DOMAIN", 42), ("USE_DOMAIN", 43)):
+ for factory, condition in (
+ (Privileges.allow, Privilege.Condition.ALLOW),
+ (Privileges.deny, Privilege.Condition.DENY),
+ ):
+ with self.subTest(name=name, condition=condition):
+ privilege = factory(name)
+ self.assertIs(privilege, factory(name))
+ self.assertEqual(condition, privilege.condition())
+ self.assertEqual(0, privilege.name().high_bits)
+ self.assertEqual(1 << bit, privilege.name().low_bits)
+ for obj_type in MetadataObject.Type:
+ self.assertEqual(
+ obj_type
+ in {
+ MetadataObject.Type.METALAKE,
+ MetadataObject.Type.DOMAIN,
+ },
+ privilege.can_bind_to(obj_type),
+ )
+ dto = DTOConverters.to_privilege_dto(privilege)
+ self.assertEqual(
+ {"name": name.lower(), "condition": condition.value.lower()},
+ json.loads(dto.to_json()),
+ )
+ self.assertEqual(dto, PrivilegeDTO.from_json(dto.to_json()))
+ self.assertTrue(dto.can_bind_to(MetadataObject.Type.DOMAIN))
+ scope = SecurableObjects.parse(
+ "Finance/US. East,?&+%", MetadataObject.Type.DOMAIN, [privilege]
+ )
+ scope_dto = DTOConverters.to_securable_object_dto(scope)
+ restored = SecurableObjectDTO.from_json(scope_dto.to_json())
+ self.assertEqual(scope.name(), restored.name())
+ self.assertIsNone(restored.parent())
+ self.assertEqual(scope.privileges(), restored.privileges())
+ self.assertTrue(
+ Privileges.allow("MANAGE_GRANTS").can_bind_to(MetadataObject.Type.DOMAIN)
+ )
+ self.assertTrue(
+ Privileges.deny("MANAGE_GRANTS").can_bind_to(MetadataObject.Type.DOMAIN)
+ )
+
+ def test_remote_error_messages_are_not_format_strings(self):
+ for exception in (
+ GravitinoRuntimeException,
+ RESTException,
+ IllegalArgumentException,
+ ):
+ for message in (
+ "missing Finance/US. East,?&+%",
+ "literal %s",
+ "literal 100%%",
+ ):
+ with self.subTest(exception=exception, message=message):
+ self.assertEqual(message, str(exception(message)))
+ self.assertEqual(
+ "missing Finance%", str(exception("missing %s", "Finance%"))
+ )
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
index 02cb13e94e..3bde3cefea 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
@@ -247,7 +247,13 @@ public class BaseIT {
containerSuite.startPostgreSQLContainer(META_DATA);
POSTGRESQL_CONTAINER = containerSuite.getPostgreSQLContainer();
- String pgUrlWithoutSchema = POSTGRESQL_CONTAINER.getJdbcUrl(META_DATA);
+ // The embedded server runs on the test host, which may not route container-internal IPs.
+ String pgUrlWithoutSchema =
+ String.format(
+ "jdbc:postgresql://%s:%d/%s",
+ POSTGRESQL_CONTAINER.getContainer().getHost(),
+ POSTGRESQL_CONTAINER.getMappedPort(PostgreSQLContainer.PG_PORT),
+ META_DATA);
String randomSchemaName = RandomStringUtils.random(10, true, false);
// Connect to the PostgreSQL docker and create a schema
String currentExecuteSql = "";
@@ -298,7 +304,13 @@ public class BaseIT {
containerSuite.startMySQLContainer(META_DATA);
MYSQL_CONTAINER = containerSuite.getMySQLContainer();
- String mysqlUrl = MYSQL_CONTAINER.getJdbcUrl(META_DATA);
+ // Use published ports for metadata-store connections from the host JVM.
+ String mysqlUrl =
+ String.format(
+ "jdbc:mysql://%s:%d/%s",
+ MYSQL_CONTAINER.getContainer().getHost(),
+ MYSQL_CONTAINER.getMappedPort(MySQLContainer.MYSQL_PORT),
+ META_DATA);
LOG.info("MySQL URL: {}", mysqlUrl);
// Connect to the mysql docker and create a databases
try (Connection connection =