This is an automated email from the ASF dual-hosted git repository.

roryqi pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/main by this push:
     new 84022c1514 [#13127] improvement(server): include owner in metalake 
list responses (#13714)
84022c1514 is described below

commit 84022c1514edec309e8cc4badc404edffc303473
Author: dennismdejong <[email protected]>
AuthorDate: Wed Nov 11 02:48:27 2026 +0100

    [#13127] improvement(server): include owner in metalake list responses 
(#13714)
    
    ### What changes were proposed in this pull request?
    
    `GET /api/metalakes` now returns an `owner` for every listed metalake:
    
    ```json
    {
      "name": "metalake_a",
      "comment": null,
      "properties": null,
      "audit": { "creator": "admin", "createTime": "..." },
      "owner": { "name": "alice", "type": "user" }
    }
    ```
    
    - `MetalakeDTO` gains a nullable `owner` (`OwnerDTO`) plus
    `withOwner(...)`/`owner()`, owner-aware `equals`/`hashCode`, and
    `@JsonInclude(ALWAYS)` so the field is serialized as an explicit `null`
    instead of disappearing under the server's `NON_NULL` mapper.
    - `MetalakeOperations.listMetalakes()` resolves ownership **after**
    `MetadataAuthzHelper.filterMetalakes(...)`, so only metalakes the caller
    can see are looked up (one `OwnerDispatcher.getOwner(...)` call per
    visible metalake). Ownership is `null` when authorization is disabled or
    no owner is assigned.
    - The Java client forwards the owner into `GravitinoMetalake`, so
    `client.listMetalakes()[i].owner()` works; the CLI and the MCP
    `list_metalakes` tool forward the REST payload and pick the field up for
    free (the MCP tool documentation now lists it).
    - Docs: new `owner` property on the `Metalake` OpenAPI schema, and the
    documented owner `type` enum/example are corrected to the lower-case
    `user`/`group` values the server already emits.
    - `clients/cli` declares `jackson.annotations` explicitly: it compiles
    with `-Werror` and otherwise fails on `unknown enum constant
    Include.ALWAYS` for the inherited field.
    
    ### Why are the changes needed?
    
    Clients that display ownership alongside the metalake list had to issue
    one owner request per metalake. Supporting user and group owners
    directly in the list removes that N+1 pattern, and an explicit `null`
    distinguishes "authorization disabled / no owner assigned" from "field
    unsupported". All existing response fields are retained.
    
    Fix: #13127
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Each entry returned by `GET /api/metalakes` (and the Java client's
    `listMetalakes()`) includes `owner: {"name": ..., "type":
    "user"|"group"}` or `owner: null`. Because `MetalakeDTO` is shared,
    single-metalake responses (`GET`/`POST`/`PATCH`) also serialize `owner:
    null`, since those operations do not load ownership. Responses without
    the field still deserialize.
    
    ### How was this patch tested?
    
    - `./gradlew :common:test :server:test :server-common:test
    :clients:client-java:test` — 519 / 565 / 381 / 408 tests, 0 failures.
    - `TestMetalakeOperations` covers user and group owners, explicit `null`
    when no owner is assigned, explicit `null` when authorization is
    disabled, and that an invisible metalake's owner is never resolved (mock
    authorizer + `verify(owners, never())`), using the production
    `ObjectMapperProvider`.
    - `TestDTOJsonSerDe` covers owner round-trip for both owner types,
    equality/hashCode, and deserialization of legacy JSON without the field.
    - `TestGravitinoAdminClient` covers owner propagation through
    `listMetalakes()`.
    - `./gradlew :clients:cli:test -PskipITs` — 507 tests, 0 failures;
    `:clients:cli:javadoc` and `:docs:build` (Redocly OpenAPI lint) pass.
    - `:mcp-server:formatCheckPython`, `:mcp-server:pylint` (10.00/10) and
    the MCP unit tests (277 passed).
    - Spotless checks pass for all touched modules.
---
 clients/cli/build.gradle.kts                       |   1 +
 .../org/apache/gravitino/client/DTOConverters.java |   1 +
 .../apache/gravitino/client/GravitinoMetalake.java |   7 +-
 .../gravitino/client/TestGravitinoAdminClient.java |   6 +
 .../java/org/apache/gravitino/dto/MetalakeDTO.java |  85 +++++++++++-
 .../apache/gravitino/json/TestDTOJsonSerDe.java    |  39 +++++-
 docs/open-api/metalakes.yaml                       |   9 ++
 docs/open-api/owners.yaml                          |  12 +-
 mcp-server/mcp_server/tools/metalake.py            |   6 +
 .../server/web/rest/MetalakeOperations.java        |  32 ++++-
 .../server/web/rest/TestMetalakeOperations.java    | 149 +++++++++++++++++++++
 11 files changed, 330 insertions(+), 17 deletions(-)

diff --git a/clients/cli/build.gradle.kts b/clients/cli/build.gradle.kts
index cdc78c8efe..782b7d5bb3 100644
--- a/clients/cli/build.gradle.kts
+++ b/clients/cli/build.gradle.kts
@@ -26,6 +26,7 @@ dependencies {
   implementation(libs.commons.cli.new)
   implementation(libs.commons.csv)
   implementation(libs.guava)
+  implementation(libs.jackson.annotations)
   implementation(libs.slf4j.api)
   implementation(libs.slf4j.simple)
   implementation(project(":api"))
diff --git 
a/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
 
b/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
index f4ec27b104..e1777e4057 100644
--- 
a/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
+++ 
b/clients/client-java/src/main/java/org/apache/gravitino/client/DTOConverters.java
@@ -88,6 +88,7 @@ class DTOConverters {
         .withComment(metalake.comment())
         .withProperties(metalake.properties())
         .withAudit((AuditDTO) metalake.auditInfo())
+        .withOwner(metalake.owner())
         .withRestClient(client)
         .build();
   }
diff --git 
a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
 
b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
index 42149cbefb..979f40e450 100644
--- 
a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
+++ 
b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoMetalake.java
@@ -32,6 +32,7 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
+import javax.annotation.Nullable;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.Catalog;
 import org.apache.gravitino.CatalogChange;
@@ -48,6 +49,7 @@ import org.apache.gravitino.authorization.SupportsRoles;
 import org.apache.gravitino.authorization.User;
 import org.apache.gravitino.dto.AuditDTO;
 import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.authorization.OwnerDTO;
 import org.apache.gravitino.dto.authorization.SecurableObjectDTO;
 import org.apache.gravitino.dto.policy.PolicyAssociationSelectorDTO;
 import org.apache.gravitino.dto.requests.CatalogCreateRequest;
@@ -178,8 +180,9 @@ public class GravitinoMetalake extends MetalakeDTO
       String comment,
       Map<String, String> properties,
       AuditDTO auditDTO,
+      @Nullable OwnerDTO owner,
       RESTClient restClient) {
-    super(name, comment, properties, auditDTO);
+    super(name, comment, properties, auditDTO, owner);
     this.restClient = restClient;
     MetadataObject metalakeObject = MetadataObjects.of(null, name, 
MetadataObject.Type.METALAKE);
     this.metadataObjectRoleOperations =
@@ -1875,7 +1878,7 @@ public class GravitinoMetalake extends MetalakeDTO
       Preconditions.checkArgument(StringUtils.isNotBlank(name), "name must not 
be null or empty");
       Preconditions.checkArgument(audit != null, "audit must not be null");
 
-      return new GravitinoMetalake(name, comment, properties, audit, 
restClient);
+      return new GravitinoMetalake(name, comment, properties, audit, owner, 
restClient);
     }
   }
 
diff --git 
a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
 
b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
index 4073bca3be..dc57d10654 100644
--- 
a/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
+++ 
b/clients/client-java/src/test/java/org/apache/gravitino/client/TestGravitinoAdminClient.java
@@ -28,8 +28,10 @@ import org.apache.gravitino.Catalog;
 import org.apache.gravitino.CatalogChange;
 import org.apache.gravitino.MetalakeChange;
 import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.authorization.Owner;
 import org.apache.gravitino.dto.AuditDTO;
 import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.authorization.OwnerDTO;
 import org.apache.gravitino.dto.requests.CatalogCreateRequest;
 import org.apache.gravitino.dto.requests.CatalogUpdateRequest;
 import org.apache.gravitino.dto.requests.CatalogUpdatesRequest;
@@ -60,6 +62,7 @@ public class TestGravitinoAdminClient extends TestBase {
             .withComment("comment")
             .withAudit(
                 
AuditDTO.builder().withCreator("creator").withCreateTime(Instant.now()).build())
+            
.withOwner(OwnerDTO.builder().withName("alice").withType(Owner.Type.USER).build())
             .build();
     MetalakeDTO mockMetalake1 =
         MetalakeDTO.builder()
@@ -78,10 +81,13 @@ public class TestGravitinoAdminClient extends TestBase {
     Assertions.assertEquals("mock", metaLakes[0].name());
     Assertions.assertEquals("comment", metaLakes[0].comment());
     Assertions.assertEquals("creator", metaLakes[0].auditInfo().creator());
+    Assertions.assertEquals("alice", metaLakes[0].owner().name());
+    Assertions.assertEquals(Owner.Type.USER, metaLakes[0].owner().type());
 
     Assertions.assertEquals("mock1", metaLakes[1].name());
     Assertions.assertEquals("comment1", metaLakes[1].comment());
     Assertions.assertEquals("creator1", metaLakes[1].auditInfo().creator());
+    Assertions.assertNull(metaLakes[1].owner());
 
     // Test return empty metalake list
     MetalakeListResponse resp1 = new MetalakeListResponse(new MetalakeDTO[] 
{});
diff --git a/common/src/main/java/org/apache/gravitino/dto/MetalakeDTO.java 
b/common/src/main/java/org/apache/gravitino/dto/MetalakeDTO.java
index 0cd6aaff67..147ef5c837 100644
--- a/common/src/main/java/org/apache/gravitino/dto/MetalakeDTO.java
+++ b/common/src/main/java/org/apache/gravitino/dto/MetalakeDTO.java
@@ -18,14 +18,16 @@
  */
 package org.apache.gravitino.dto;
 
+import com.fasterxml.jackson.annotation.JsonInclude;
 import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
 import java.util.Map;
+import java.util.Objects;
 import javax.annotation.Nullable;
 import lombok.ToString;
 import org.apache.gravitino.Audit;
 import org.apache.gravitino.Metalake;
+import org.apache.gravitino.dto.authorization.OwnerDTO;
 
 /** Represents a Metalake Data Transfer Object (DTO) that implements the 
Metalake interface. */
 @ToString
@@ -45,6 +47,11 @@ public class MetalakeDTO implements Metalake {
   @JsonProperty("audit")
   private AuditDTO audit;
 
+  @Nullable
+  @JsonProperty("owner")
+  @JsonInclude(JsonInclude.Include.ALWAYS)
+  private OwnerDTO owner;
+
   /** Default constructor for Jackson deserialization. */
   protected MetalakeDTO() {}
 
@@ -58,10 +65,29 @@ public class MetalakeDTO implements Metalake {
    */
   protected MetalakeDTO(
       String name, String comment, Map<String, String> properties, AuditDTO 
audit) {
+    this(name, comment, properties, audit, null);
+  }
+
+  /**
+   * Creates a new instance of MetalakeDTO.
+   *
+   * @param name The name of the Metalake DTO.
+   * @param comment The comment of the Metalake DTO.
+   * @param properties The properties of the Metalake DTO.
+   * @param audit The audit information of the Metalake DTO.
+   * @param owner The owner of the Metalake DTO, or null if the owner is 
unavailable.
+   */
+  protected MetalakeDTO(
+      String name,
+      String comment,
+      Map<String, String> properties,
+      AuditDTO audit,
+      @Nullable OwnerDTO owner) {
     this.name = name;
     this.comment = comment;
     this.properties = properties;
     this.audit = audit;
+    this.owner = owner;
   }
 
   /**
@@ -96,6 +122,18 @@ public class MetalakeDTO implements Metalake {
     return audit;
   }
 
+  /**
+   * The owner of the metalake. Only populated for metalake list responses; 
other operations leave
+   * it null.
+   *
+   * @return The owner of the metalake, or null when authorization is 
disabled, no owner is
+   *     assigned, or ownership was not loaded.
+   */
+  @Nullable
+  public OwnerDTO owner() {
+    return owner;
+  }
+
   /**
    * A builder class for constructing instances of MetalakeDTO.
    *
@@ -115,6 +153,9 @@ public class MetalakeDTO implements Metalake {
     /** The audit information of the Metalake DTO. */
     protected AuditDTO audit;
 
+    /** The optional owner of the Metalake DTO. */
+    @Nullable protected OwnerDTO owner;
+
     /** Default constructor. */
     protected Builder() {}
 
@@ -162,6 +203,17 @@ public class MetalakeDTO implements Metalake {
       return (S) this;
     }
 
+    /**
+     * Sets the owner of the Metalake DTO.
+     *
+     * @param owner The owner of the Metalake DTO, or null if the owner is 
unavailable.
+     * @return The builder instance.
+     */
+    public S withOwner(@Nullable OwnerDTO owner) {
+      this.owner = owner;
+      return (S) this;
+    }
+
     /**
      * Builds an instance of MetalakeDTO using the builder's properties.
      *
@@ -171,7 +223,7 @@ public class MetalakeDTO implements Metalake {
     public MetalakeDTO build() {
       Preconditions.checkArgument(name != null && !name.isEmpty(), "name 
cannot be null or empty");
       Preconditions.checkArgument(audit != null, "audit cannot be null");
-      return new MetalakeDTO(name, comment, properties, audit);
+      return new MetalakeDTO(name, comment, properties, audit, owner);
     }
   }
 
@@ -184,10 +236,11 @@ public class MetalakeDTO implements Metalake {
       return false;
     }
     MetalakeDTO that = (MetalakeDTO) o;
-    return Objects.equal(name, that.name)
-        && Objects.equal(comment, that.comment)
+    return Objects.equals(name, that.name)
+        && Objects.equals(comment, that.comment)
         && propertyEqual(properties, that.properties)
-        && Objects.equal(audit, that.audit);
+        && Objects.equals(audit, that.audit)
+        && ownerEqual(owner, that.owner);
   }
 
   private boolean propertyEqual(Map<String, String> p1, Map<String, String> 
p2) {
@@ -203,12 +256,30 @@ public class MetalakeDTO implements Metalake {
       return true;
     }
 
-    return java.util.Objects.equals(p1, p2);
+    return Objects.equals(p1, p2);
+  }
+
+  private boolean ownerEqual(@Nullable OwnerDTO owner1, @Nullable OwnerDTO 
owner2) {
+    if (owner1 == owner2) {
+      return true;
+    }
+
+    if (owner1 == null || owner2 == null) {
+      return false;
+    }
+
+    return Objects.equals(owner1.name(), owner2.name()) && owner1.type() == 
owner2.type();
   }
 
   @Override
   public int hashCode() {
-    return Objects.hashCode(name, comment, audit, properties);
+    return Objects.hash(
+        name,
+        comment,
+        audit,
+        properties,
+        owner == null ? null : owner.name(),
+        owner == null ? null : owner.type());
   }
 
   /**
diff --git 
a/common/src/test/java/org/apache/gravitino/json/TestDTOJsonSerDe.java 
b/common/src/test/java/org/apache/gravitino/json/TestDTOJsonSerDe.java
index 82979b8eae..19a14c85e1 100644
--- a/common/src/test/java/org/apache/gravitino/json/TestDTOJsonSerDe.java
+++ b/common/src/test/java/org/apache/gravitino/json/TestDTOJsonSerDe.java
@@ -25,9 +25,11 @@ import com.google.common.collect.ImmutableMap;
 import java.time.Instant;
 import java.util.Map;
 import org.apache.gravitino.Catalog;
+import org.apache.gravitino.authorization.Owner;
 import org.apache.gravitino.dto.AuditDTO;
 import org.apache.gravitino.dto.CatalogDTO;
 import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.authorization.OwnerDTO;
 import org.apache.gravitino.dto.rel.ColumnDTO;
 import org.apache.gravitino.dto.rel.TableDTO;
 import org.apache.gravitino.dto.rel.expressions.FieldReferenceDTO;
@@ -58,7 +60,8 @@ public class TestDTOJsonSerDe {
   private final String auditJson =
       
"{\"creator\":%s,\"createTime\":%s,\"lastModifier\":%s,\"lastModifiedTime\":%s}";
 
-  private final String metalakeJson = 
"{\"name\":%s,\"comment\":%s,\"properties\":%s,\"audit\":%s}";
+  private final String metalakeJson =
+      
"{\"name\":%s,\"comment\":%s,\"properties\":%s,\"audit\":%s,\"owner\":null}";
 
   private final String columnJson =
       
"{\"name\":%s,\"type\":%s,\"comment\":%s,\"nullable\":%s,\"autoIncrement\":%s}";
@@ -174,6 +177,40 @@ public class TestDTOJsonSerDe {
     Assertions.assertEquals(metalake1, desermetalake1);
   }
 
+  @Test
+  public void testMetalakeOwnerSerDe() throws Exception {
+    AuditDTO audit = 
AuditDTO.builder().withCreator("admin").withCreateTime(Instant.EPOCH).build();
+    for (Owner.Type type : Owner.Type.values()) {
+      MetalakeDTO dto =
+          MetalakeDTO.builder()
+              .withName("lake")
+              .withAudit(audit)
+              
.withOwner(OwnerDTO.builder().withName("owner").withType(type).build())
+              .build();
+
+      String json = JsonUtils.objectMapper().writeValueAsString(dto);
+      MetalakeDTO restored = JsonUtils.objectMapper().readValue(json, 
MetalakeDTO.class);
+      Assertions.assertEquals("owner", restored.owner().name());
+      Assertions.assertEquals(type, restored.owner().type());
+      Assertions.assertEquals(dto, restored);
+      Assertions.assertEquals(dto.hashCode(), restored.hashCode());
+      Assertions.assertEquals(
+          "owner", 
JsonUtils.objectMapper().readTree(json).get("owner").get("name").asText());
+
+      MetalakeDTO differentOwner =
+          MetalakeDTO.builder()
+              .withName("lake")
+              .withAudit(audit)
+              
.withOwner(OwnerDTO.builder().withName("another-owner").withType(type).build())
+              .build();
+      Assertions.assertNotEquals(dto, differentOwner);
+    }
+
+    String legacy =
+        
"{\"name\":\"lake\",\"audit\":{\"creator\":\"admin\",\"createTime\":\"1970-01-01T00:00:00Z\"}}";
+    Assertions.assertNull(JsonUtils.objectMapper().readValue(legacy, 
MetalakeDTO.class).owner());
+  }
+
   @Test
   public void testCatalogDTOSerDe() throws Exception {
     AuditDTO audit =
diff --git a/docs/open-api/metalakes.yaml b/docs/open-api/metalakes.yaml
index 80e40e184a..4d6c629760 100644
--- a/docs/open-api/metalakes.yaml
+++ b/docs/open-api/metalakes.yaml
@@ -337,6 +337,15 @@ components:
           type: string
           description: A comment about the Metalake
           nullable: true
+        owner:
+          type: object
+          nullable: true
+          description: >-
+            The user or group owning the metalake, populated when listing 
metalakes.
+            Null when authorization is disabled, no owner is assigned, or 
ownership
+            was not loaded by the operation.
+          allOf:
+            - $ref: "./owners.yaml#/components/schemas/Owner"
         audit:
           $ref: "./openapi.yaml#/components/schemas/Audit"
         properties:
diff --git a/docs/open-api/owners.yaml b/docs/open-api/owners.yaml
index 5e8dea0d87..8df387d7a3 100644
--- a/docs/open-api/owners.yaml
+++ b/docs/open-api/owners.yaml
@@ -102,8 +102,8 @@ components:
         type:
           type: string
           enum:
-            - USER
-            - GROUP
+            - user
+            - group
           description: The type of the owner
 
     OwnerSetRequest:
@@ -118,8 +118,8 @@ components:
         type:
           type: string
           enum:
-            - USER
-            - GROUP
+            - user
+            - group
           description: The type of the owner
 
   responses:
@@ -139,7 +139,7 @@ components:
     OwnerSetRequest:
       value: {
         "name": "user1",
-        "type": "USER"
+        "type": "user"
       }
 
     OwnerResponse:
@@ -147,7 +147,7 @@ components:
         "code": 0,
         "owner": {
           "name": "user1",
-          "type": "USER",
+          "type": "user",
         }
       }
 
diff --git a/mcp-server/mcp_server/tools/metalake.py 
b/mcp-server/mcp_server/tools/metalake.py
index c2a93cac7b..dc12a7730c 100644
--- a/mcp-server/mcp_server/tools/metalake.py
+++ b/mcp-server/mcp_server/tools/metalake.py
@@ -48,6 +48,10 @@ def load_metalake_tools(mcp: FastMCP):
                 "audit": {
                   "creator": "anonymous",
                   "createTime": "2025-08-20T07:33:41.233089Z"
+                },
+                "owner": {
+                  "name": "alice",
+                  "type": "user"
                 }
               }
             ]
@@ -57,6 +61,8 @@ def load_metalake_tools(mcp: FastMCP):
             comment: A human-readable description of the metalake.
             properties: Metalake properties.
             audit: Metadata about the metalake's creation and modification.
+            owner: The user or group owning the metalake, or null when
+                authorization is disabled or no owner is assigned.
         """
         # require_metalake=False: this is the tool an agent calls when it does
         # not know a metalake yet, so it must work with none configured.
diff --git 
a/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java
 
b/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java
index ea390591a6..e45573c4bd 100644
--- 
a/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java
+++ 
b/server/src/main/java/org/apache/gravitino/server/web/rest/MetalakeOperations.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.server.web.rest;
 import com.codahale.metrics.annotation.ResponseMetered;
 import com.codahale.metrics.annotation.Timed;
 import java.util.Arrays;
+import javax.annotation.Nullable;
 import javax.inject.Inject;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
@@ -38,11 +39,16 @@ import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import org.apache.gravitino.Entity;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
 import org.apache.gravitino.Metalake;
 import org.apache.gravitino.MetalakeChange;
 import org.apache.gravitino.NameIdentifier;
 import org.apache.gravitino.Namespace;
+import org.apache.gravitino.authorization.OwnerDispatcher;
 import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.authorization.OwnerDTO;
 import org.apache.gravitino.dto.requests.MetalakeCreateRequest;
 import org.apache.gravitino.dto.requests.MetalakeSetRequest;
 import org.apache.gravitino.dto.requests.MetalakeUpdateRequest;
@@ -94,8 +100,32 @@ public class MetalakeOperations {
                 MetadataAuthzHelper.filterMetalakes(
                     metalakes,
                     
AuthorizationExpressionConstants.LOAD_METALAKE_AUTHORIZATION_EXPRESSION);
+            OwnerDispatcher ownerDispatcher = 
GravitinoEnv.getInstance().ownerDispatcher();
             MetalakeDTO[] metalakeDTOs =
-                
Arrays.stream(metalakes).map(DTOConverters::toDTO).toArray(MetalakeDTO[]::new);
+                Arrays.stream(metalakes)
+                    .map(
+                        metalake -> {
+                          @Nullable
+                          OwnerDTO owner =
+                              ownerDispatcher == null
+                                  ? null
+                                  : ownerDispatcher
+                                      .getOwner(
+                                          metalake.name(),
+                                          MetadataObjects.of(
+                                              null, metalake.name(), 
MetadataObject.Type.METALAKE))
+                                      .map(DTOConverters::toDTO)
+                                      .orElse(null);
+
+                          return MetalakeDTO.builder()
+                              .withName(metalake.name())
+                              .withComment(metalake.comment())
+                              .withProperties(metalake.properties())
+                              
.withAudit(DTOConverters.toDTO(metalake.auditInfo()))
+                              .withOwner(owner)
+                              .build();
+                        })
+                    .toArray(MetalakeDTO[]::new);
             Response response = Utils.ok(new 
MetalakeListResponse(metalakeDTOs));
             LOG.info("List {} metalakes in Gravitino", metalakeDTOs.length);
             return response;
diff --git 
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetalakeOperations.java
 
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetalakeOperations.java
index 6f112ce747..ae1acc07db 100644
--- 
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetalakeOperations.java
+++ 
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetalakeOperations.java
@@ -25,20 +25,25 @@ import static 
org.apache.gravitino.Configs.TREE_LOCK_MAX_NODE_IN_MEMORY;
 import static org.apache.gravitino.Configs.TREE_LOCK_MIN_NODE_IN_MEMORY;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import com.fasterxml.jackson.core.JsonParseException;
 import com.fasterxml.jackson.core.JsonParser;
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.JsonNode;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Lists;
 import java.io.IOException;
 import java.time.Instant;
 import java.util.Collections;
 import java.util.List;
+import java.util.Optional;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.GET;
 import javax.ws.rs.Path;
@@ -48,9 +53,16 @@ import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.reflect.FieldUtils;
 import org.apache.gravitino.Config;
+import org.apache.gravitino.Configs;
 import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.MetadataObjects;
 import org.apache.gravitino.MetalakeChange;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.authorization.Owner;
+import org.apache.gravitino.authorization.OwnerDispatcher;
 import org.apache.gravitino.dto.MetalakeDTO;
+import org.apache.gravitino.dto.authorization.OwnerDTO;
 import org.apache.gravitino.dto.requests.MetalakeCreateRequest;
 import org.apache.gravitino.dto.requests.MetalakeSetRequest;
 import org.apache.gravitino.dto.requests.MetalakeUpdateRequest;
@@ -70,11 +82,14 @@ import org.apache.gravitino.meta.SchemaVersion;
 import org.apache.gravitino.metalake.MetalakeDispatcher;
 import org.apache.gravitino.metalake.MetalakeManager;
 import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.server.authorization.GravitinoAuthorizerProvider;
+import org.apache.gravitino.server.web.ObjectMapperProvider;
 import org.apache.gravitino.server.web.mapper.JsonMappingExceptionMapper;
 import org.apache.gravitino.server.web.mapper.JsonParseExceptionMapper;
 import org.apache.gravitino.server.web.mapper.JsonProcessingExceptionMapper;
 import org.glassfish.hk2.utilities.binding.AbstractBinder;
 import org.glassfish.jersey.client.HttpUrlConnectorProvider;
+import org.glassfish.jersey.jackson.JacksonFeature;
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.TestProperties;
 import org.junit.jupiter.api.Assertions;
@@ -118,6 +133,7 @@ public class TestMetalakeOperations extends 
BaseOperationsTest {
 
     ResourceConfig resourceConfig = new ResourceConfig();
     resourceConfig.register(MetalakeOperations.class);
+    
resourceConfig.register(ObjectMapperProvider.class).register(JacksonFeature.class);
     resourceConfig.register(
         new AbstractBinder() {
           @Override
@@ -189,6 +205,139 @@ public class TestMetalakeOperations extends 
BaseOperationsTest {
     Assertions.assertEquals(metalakeName, metalakes[1].name());
   }
 
+  @Test
+  public void testListMetalakesIncludesOwner()
+      throws IllegalAccessException, JsonProcessingException {
+    OwnerDispatcher previousOwners = 
GravitinoEnv.getInstance().ownerDispatcher();
+    OwnerDispatcher owners = mock(OwnerDispatcher.class);
+    FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", 
owners, true);
+    try {
+      when(metalakeManager.listMetalakes())
+          .thenReturn(
+              new BaseMetalake[] {
+                newBaseMetalake("lake0", 1L),
+                newBaseMetalake("lake1", 2L),
+                newBaseMetalake("lake2", 3L)
+              });
+      when(owners.getOwner(
+              "lake0", MetadataObjects.of(null, "lake0", 
MetadataObject.Type.METALAKE)))
+          .thenReturn(
+              
Optional.of(OwnerDTO.builder().withName("alice").withType(Owner.Type.USER).build()));
+      when(owners.getOwner(
+              "lake1", MetadataObjects.of(null, "lake1", 
MetadataObject.Type.METALAKE)))
+          .thenReturn(
+              Optional.of(
+                  
OwnerDTO.builder().withName("admins").withType(Owner.Type.GROUP).build()));
+      when(owners.getOwner(
+              "lake2", MetadataObjects.of(null, "lake2", 
MetadataObject.Type.METALAKE)))
+          .thenReturn(Optional.empty());
+
+      try (Response response = target("/metalakes").request().get()) {
+        Assertions.assertEquals(Response.Status.OK.getStatusCode(), 
response.getStatus());
+        JsonNode entries =
+            ObjectMapperProvider.objectMapper()
+                .readTree(response.readEntity(String.class))
+                .get("metalakes");
+
+        Assertions.assertEquals(3, entries.size());
+        Assertions.assertEquals("lake0", entries.get(0).get("name").asText());
+        // Enum values are serialized in lower case, e.g. "user" and "group".
+        Assertions.assertEquals("alice", 
entries.get(0).get("owner").get("name").asText());
+        Assertions.assertEquals("user", 
entries.get(0).get("owner").get("type").asText());
+        Assertions.assertEquals("admins", 
entries.get(1).get("owner").get("name").asText());
+        Assertions.assertEquals("group", 
entries.get(1).get("owner").get("type").asText());
+        // An unassigned owner is returned explicitly as null.
+        Assertions.assertTrue(entries.get(2).has("owner"));
+        Assertions.assertTrue(entries.get(2).get("owner").isNull());
+      }
+    } finally {
+      FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", 
previousOwners, true);
+    }
+  }
+
+  @Test
+  public void testListMetalakesOwnerIsNullWithoutAuthorization()
+      throws IllegalAccessException, JsonProcessingException {
+    OwnerDispatcher previousOwners = 
GravitinoEnv.getInstance().ownerDispatcher();
+    FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", null, 
true);
+    try {
+      when(metalakeManager.listMetalakes())
+          .thenReturn(new BaseMetalake[] {newBaseMetalake("lake", 1L)});
+
+      try (Response response = target("/metalakes").request().get()) {
+        Assertions.assertEquals(Response.Status.OK.getStatusCode(), 
response.getStatus());
+        JsonNode entry =
+            ObjectMapperProvider.objectMapper()
+                .readTree(response.readEntity(String.class))
+                .get("metalakes")
+                .get(0);
+
+        Assertions.assertEquals("lake", entry.get("name").asText());
+        Assertions.assertTrue(entry.has("owner"));
+        Assertions.assertTrue(entry.get("owner").isNull());
+      }
+    } finally {
+      FieldUtils.writeField(GravitinoEnv.getInstance(), "ownerDispatcher", 
previousOwners, true);
+    }
+  }
+
+  @Test
+  public void testListMetalakesResolvesOwnerOnlyForVisibleMetalakes()
+      throws IllegalAccessException, JsonProcessingException {
+    GravitinoEnv env = GravitinoEnv.getInstance();
+    Config config = env.config();
+    GravitinoAuthorizerProvider authorizerProvider = 
GravitinoAuthorizerProvider.getInstance();
+    GravitinoAuthorizer previousAuthorizer = 
authorizerProvider.getGravitinoAuthorizer();
+    OwnerDispatcher previousOwners = env.ownerDispatcher();
+
+    OwnerDispatcher owners = mock(OwnerDispatcher.class);
+    GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+    when(authorizer.isMetalakeUser(eq("visible"), any())).thenReturn(true);
+    when(authorizer.isMetalakeUser(eq("hidden"), any())).thenReturn(false);
+    FieldUtils.writeField(env, "ownerDispatcher", owners, true);
+    FieldUtils.writeField(authorizerProvider, "gravitinoAuthorizer", 
authorizer, true);
+    Mockito.doReturn(true).when(config).get(ENABLE_AUTHORIZATION);
+    
Mockito.doReturn(4).when(config).get(Configs.GRAVITINO_AUTHORIZATION_THREAD_POOL_SIZE);
+    try {
+      when(metalakeManager.listMetalakes())
+          .thenReturn(
+              new BaseMetalake[] {newBaseMetalake("visible", 1L), 
newBaseMetalake("hidden", 2L)});
+      when(owners.getOwner(
+              "visible", MetadataObjects.of(null, "visible", 
MetadataObject.Type.METALAKE)))
+          .thenReturn(
+              
Optional.of(OwnerDTO.builder().withName("alice").withType(Owner.Type.USER).build()));
+
+      try (Response response = target("/metalakes").request().get()) {
+        Assertions.assertEquals(Response.Status.OK.getStatusCode(), 
response.getStatus());
+        JsonNode entries =
+            ObjectMapperProvider.objectMapper()
+                .readTree(response.readEntity(String.class))
+                .get("metalakes");
+
+        Assertions.assertEquals(1, entries.size());
+        Assertions.assertEquals("visible", 
entries.get(0).get("name").asText());
+        Assertions.assertEquals("alice", 
entries.get(0).get("owner").get("name").asText());
+      }
+
+      // Ownership of metalakes that the caller cannot see must not be 
resolved.
+      verify(owners, never()).getOwner(eq("hidden"), any());
+    } finally {
+      FieldUtils.writeField(env, "ownerDispatcher", previousOwners, true);
+      FieldUtils.writeField(authorizerProvider, "gravitinoAuthorizer", 
previousAuthorizer, true);
+      Mockito.doReturn(false).when(config).get(ENABLE_AUTHORIZATION);
+    }
+  }
+
+  private static BaseMetalake newBaseMetalake(String name, Long id) {
+    return BaseMetalake.builder()
+        .withName(name)
+        .withId(id)
+        .withAuditInfo(
+            
AuditInfo.builder().withCreator("admin").withCreateTime(Instant.EPOCH).build())
+        .withVersion(SchemaVersion.V_0_1)
+        .build();
+  }
+
   @Test
   public void testCreateMetalake() {
     MetalakeCreateRequest req =

Reply via email to