From a29e2d7373ac4da176acb5cb7a6a6e61064ea57f Mon Sep 17 00:00:00 2001 From: Pere Miquel Brull Date: Sat, 31 Oct 2026 18:28:54 +0000 Subject: [PATCH] fix(context): match shares by principal ID (#36663) Users, teams and domains have independent name namespaces. Match shared principals by their stored IDs and require a user reference for caller ownership checks, so namesakes cannot read memories or files. Reuse search's principal IDs and deny sharing when the caller lookup fails. (cherry picked from commit 9b32eb82ad95d45ac7e942f55eaf49833aac5324) --- .../McpContextMemoryPrincipalIdentityIT.java | 336 ++++++++++++++++++ .../mcp/tools/CompanyContextToolTest.java | 10 + .../context/ContextMemoryVisibility.java | 51 +-- .../drive/ContextFileVisibility.java | 1 + .../context/ContextMemoryVisibilityTest.java | 115 +++++- .../drive/ContextFileVisibilityTest.java | 139 +++++++- 6 files changed, 622 insertions(+), 30 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpContextMemoryPrincipalIdentityIT.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpContextMemoryPrincipalIdentityIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpContextMemoryPrincipalIdentityIT.java new file mode 100644 index 000000000000..9266a023032f --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/mcp/McpContextMemoryPrincipalIdentityIT.java @@ -0,0 +1,336 @@ +/* + * Copyright 2026 Collate + * Licensed 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.openmetadata.it.tests.mcp; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.http.HttpResponse; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.context.CreateContextMemory; +import org.openmetadata.schema.api.data.CreateContextFile; +import org.openmetadata.schema.api.data.CreateFolder; +import org.openmetadata.schema.api.domains.CreateDomain; +import org.openmetadata.schema.api.policies.CreatePolicy; +import org.openmetadata.schema.api.teams.CreateRole; +import org.openmetadata.schema.api.teams.CreateTeam; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.context.ContextMemory; +import org.openmetadata.schema.entity.context.ContextMemorySourceType; +import org.openmetadata.schema.entity.context.ContextMemoryStatus; +import org.openmetadata.schema.entity.context.MemoryShareConfig; +import org.openmetadata.schema.entity.context.MemorySharedPrincipal; +import org.openmetadata.schema.entity.context.MemoryVisibility; +import org.openmetadata.schema.entity.data.ContextFile; +import org.openmetadata.schema.entity.data.Folder; +import org.openmetadata.schema.entity.policies.Policy; +import org.openmetadata.schema.entity.policies.accessControl.Rule; +import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.ForbiddenException; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.services.context.ContextMemoryService; +import org.openmetadata.sdk.test.util.RestClient; +import org.openmetadata.service.Entity; + +/** Names shared by different principal types must never grant each other's access. */ +@Execution(ExecutionMode.CONCURRENT) +@ExtendWith(TestNamespaceExtension.class) +class McpContextMemoryPrincipalIdentityIT extends McpTestBase { + private static final String MEMORIES = "contextCenter/memories"; + private static final String FILES = "contextCenter/drive/files"; + private static final String ANSWER = "the-budget-is-only-for-the-listed-principal"; + private static final String FILE_CONTENT = + "the-file-description-is-only-for-the-listed-principal"; + + @BeforeAll + static void authenticateAdmin() throws Exception { + initAuth(); + } + + @ParameterizedTest + @ValueSource(strings = {Entity.TEAM, Entity.DOMAIN}) + void sharingAdmitsMembersButDeniesNamesakes(String principalType, TestNamespace ns) + throws Exception { + EntityReference principal = createPrincipal(ns, principalType); + User namesake = createUser(ns, new CreateUser().withName(principal.getName())); + User member = createMember(ns, principal); + MemoryShareConfig sharing = + new MemoryShareConfig() + .withVisibility(MemoryVisibility.SHARED) + .withSharedWith(List.of(new MemorySharedPrincipal().withPrincipal(principal))); + Folder folder = + post( + "contextCenter/drive/folders", + new CreateFolder().withName(ns.shortPrefix("folder")), + Folder.class); + try { + ContextFile file = createFile(ns, sharing, null, folder); + ContextMemory memory = createMemory(ns, sharing, null, file); + + assertEquals(memory.getId(), memoriesAs(member).get(memory.getId().toString()).getId()); + assertEquals(200, getResponse(FILES + "/" + file.getId(), bearerFor(member)).statusCode()); + assertListed( + MEMORIES + "?sourceEntityId=" + file.getId(), memory.getId().toString(), member, true); + assertListed(FILES + "?folderId=" + folder.getId(), file.getId().toString(), member, true); + assertMcpAnswer(memory, member, true); + assertCompanyContextAnswer(memory, member, true); + + assertMemoryHidden(memory, namesake); + assertFileHidden(file, namesake); + assertListed( + MEMORIES + "?sourceEntityId=" + file.getId(), memory.getId().toString(), namesake, false); + assertListed(FILES + "?folderId=" + folder.getId(), file.getId().toString(), namesake, false); + assertMcpAnswer(memory, namesake, false); + assertCompanyContextAnswer(memory, namesake, false); + } finally { + delete("contextCenter/drive/folders/" + folder.getId() + "?hardDelete=true&recursive=true"); + } + } + + @Test + void aTeamNamesakeCannotReadPrivateContentOrRestrictItsFiles(TestNamespace ns) throws Exception { + EntityReference team = createPrincipal(ns, Entity.TEAM); + Role editor = fileEditor(ns); + User namesake = + createUser( + ns, new CreateUser().withName(team.getName()).withRoles(List.of(editor.getId()))); + MemoryShareConfig privateShare = + new MemoryShareConfig().withVisibility(MemoryVisibility.PRIVATE); + ContextFile file = createFile(ns, privateShare, team, null); + ContextMemory memory = createMemory(ns, privateShare, team, file); + assertMemoryHidden(memory, namesake); + assertFileHidden(file, namesake); + assertMcpAnswer(memory, namesake, false); + + ContextFile open = + createFile(ns, new MemoryShareConfig().withVisibility(MemoryVisibility.ENTITY), team, null); + OpenMetadataClient caller = clientFor(namesake); + JsonNode editDescription = + JsonUtils.readTree("[{\"op\":\"replace\",\"path\":\"/description\",\"value\":\"edited\"}]"); + ContextFile edited = + caller + .getHttpClient() + .execute( + HttpMethod.PATCH, + "/v1/" + FILES + "/" + open.getId(), + editDescription, + ContextFile.class); + assertEquals("edited", edited.getDescription(), "the caller has ordinary file edit permission"); + + JsonNode restrict = + JsonUtils.readTree( + "[{\"op\":\"replace\",\"path\":\"/shareConfig/visibility\",\"value\":\"Private\"}]"); + assertThrows( + ForbiddenException.class, + () -> + caller + .getHttpClient() + .execute( + HttpMethod.PATCH, + "/v1/" + FILES + "/" + open.getId(), + restrict, + ContextFile.class)); + assertEquals(200, getResponse(FILES + "/" + open.getId(), bearerFor(namesake)).statusCode()); + } + + private static EntityReference createPrincipal(TestNamespace ns, String type) { + String name = ns.shortPrefix(type); + if (Entity.TEAM.equals(type)) { + return ns.trackRoot( + Entity.TEAM, + SdkClients.adminClient() + .teams() + .create(new CreateTeam().withName(name).withTeamType(CreateTeam.TeamType.GROUP))) + .getEntityReference(); + } + return ns.trackRoot( + Entity.DOMAIN, + SdkClients.adminClient() + .domains() + .create( + new CreateDomain() + .withName(name) + .withDescription("Shared principal") + .withDomainType(CreateDomain.DomainType.AGGREGATE))) + .getEntityReference(); + } + + private static User createMember(TestNamespace ns, EntityReference principal) { + CreateUser request = new CreateUser().withName(ns.shortPrefix("member")); + if (Entity.TEAM.equals(principal.getType())) { + request.withTeams(List.of(principal.getId())); + } else { + request.withDomains(List.of(principal.getFullyQualifiedName())); + } + return createUser(ns, request); + } + + private static User createUser(TestNamespace ns, CreateUser request) { + return ns.trackRoot( + Entity.USER, + SdkClients.adminClient() + .users() + .create(request.withEmail(request.getName() + "@test.openmetadata.org"))); + } + + private static ContextFile createFile( + TestNamespace ns, MemoryShareConfig sharing, EntityReference owner, Folder folder) + throws Exception { + ContextFile created = + ns.trackRoot( + Entity.CONTEXT_FILE, + post( + FILES, + new CreateContextFile() + .withName(ns.shortPrefix("file") + "_" + UUID.randomUUID()) + .withDescription(FILE_CONTENT) + .withOwners(owner == null ? null : List.of(owner)) + .withFolder(folder == null ? null : folder.getFullyQualifiedName()), + ContextFile.class)); + return RestClient.admin() + .patch( + "v1/" + FILES, + created.getId(), + JsonUtils.pojoToJson(created), + JsonUtils.deepCopy(created, ContextFile.class).withShareConfig(sharing), + ContextFile.class); + } + + private static ContextMemory createMemory( + TestNamespace ns, MemoryShareConfig sharing, EntityReference owner, ContextFile file) + throws Exception { + return ns.trackRoot( + Entity.CONTEXT_MEMORY, + new ContextMemoryService(SdkClients.adminClient().getHttpClient()) + .create( + new CreateContextMemory() + .withName(ns.shortPrefix("memory")) + .withQuestion("Who can read this budget?") + .withAnswer(ANSWER) + .withEntityStatus(ContextMemoryStatus.APPROVED) + .withSourceType(ContextMemorySourceType.FILE_EXTRACTION) + .withSourceEntity(file.getEntityReference()) + .withShareConfig(sharing) + .withOwners(owner == null ? null : List.of(owner)))); + } + + private static void assertMemoryHidden(ContextMemory memory, User user) { + ContextMemoryService caller = memoriesAs(user); + String id = memory.getId().toString(); + assertThrows(ForbiddenException.class, () -> caller.get(id)); + assertThrows(ForbiddenException.class, () -> caller.getByName(memory.getFullyQualifiedName())); + assertThrows(ForbiddenException.class, () -> caller.getVersionList(memory.getId())); + assertThrows(ForbiddenException.class, () -> caller.getVersion(id, memory.getVersion())); + assertThrows( + ForbiddenException.class, () -> caller.patch(memory.getId(), JsonUtils.readTree("[]"))); + } + + private static void assertFileHidden(ContextFile file, User user) throws Exception { + for (String path : + List.of(FILES + "/" + file.getId(), FILES + "/name/" + file.getFullyQualifiedName())) { + HttpResponse response = getResponse(path, bearerFor(user)); + assertEquals(403, response.statusCode(), response.body()); + assertThat(response.body()).doesNotContain(FILE_CONTENT); + } + } + + private static void assertListed(String path, String id, User user, boolean visible) + throws Exception { + HttpResponse response = getResponse(path, bearerFor(user)); + assertEquals(200, response.statusCode(), response.body()); + JsonNode data = OBJECT_MAPPER.readTree(response.body()).path("data"); + assertEquals(visible ? 1 : 0, data.size(), response.body()); + if (visible) { + assertEquals(id, data.get(0).path("id").asText()); + } + } + + private void assertMcpAnswer(ContextMemory memory, User user, boolean visible) throws Exception { + JsonNode response = + executeMcpRequest( + McpTestUtils.createGetEntityToolCall( + Entity.CONTEXT_MEMORY, memory.getFullyQualifiedName()), + bearerFor(user)); + assertEquals( + !visible, response.path("result").path("isError").asBoolean(false), response.toString()); + assertEquals(visible, response.toString().contains(ANSWER), response.toString()); + } + + private void assertCompanyContextAnswer(ContextMemory memory, User user, boolean visible) + throws Exception { + JsonNode response = + executeMcpRequest( + McpTestUtils.createToolCallRequest( + "company_context", Map.of("fqn", memory.getFullyQualifiedName())), + bearerFor(user)); + assertEquals(visible, response.toString().contains(ANSWER), response.toString()); + } + + private static Role fileEditor(TestNamespace ns) { + Policy policy = + ns.trackRoot( + Entity.POLICY, + SdkClients.adminClient() + .policies() + .create( + new CreatePolicy() + .withName(ns.shortPrefix("file-edit-policy")) + .withRules( + List.of( + new Rule() + .withName("EditFiles") + .withEffect(Rule.Effect.ALLOW) + .withResources(List.of(Entity.CONTEXT_FILE)) + .withOperations(List.of(MetadataOperation.EDIT_ALL)))))); + return ns.trackRoot( + Entity.ROLE, + SdkClients.adminClient() + .roles() + .create( + new CreateRole() + .withName(ns.shortPrefix("file-editor")) + .withPolicies(List.of(policy.getFullyQualifiedName())))); + } + + private static ContextMemoryService memoriesAs(User user) { + return new ContextMemoryService(clientFor(user).getHttpClient()); + } + + private static OpenMetadataClient clientFor(User user) { + return SdkClients.createClient(user.getEmail(), user.getEmail(), new String[] {}); + } + + private static String bearerFor(User user) { + return "Bearer " + tokenFor(user.getName()); + } +} diff --git a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java index c50cc5c60d0f..31290fd07730 100644 --- a/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java +++ b/openmetadata-mcp/src/test/java/org/openmetadata/mcp/tools/CompanyContextToolTest.java @@ -18,11 +18,13 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.security.Principal; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.Callable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -417,6 +419,7 @@ private ContextMemory sharedWith(ContextMemory memory, String userName) { new MemorySharedPrincipal() .withPrincipal( new EntityReference() + .withId(userId(userName)) .withType(Entity.USER) .withName(userName) .withFullyQualifiedName(userName)))); @@ -434,6 +437,9 @@ private CatalogSecurityContext securityContextFor(String userName) { private T withSubject( CatalogSecurityContext securityContext, String userName, Callable body) throws Exception { + entityMock + .when(() -> Entity.getEntityByName(eq(Entity.USER), eq(userName), anyString(), any())) + .thenReturn(new User().withId(userId(userName)).withName(userName)); try (MockedStatic subjects = mockStatic(DefaultAuthorizer.class)) { subjects .when(() -> DefaultAuthorizer.getSubjectContext(securityContext)) @@ -442,6 +448,10 @@ private T withSubject( } } + private static UUID userId(String userName) { + return UUID.nameUUIDFromBytes(userName.getBytes(StandardCharsets.UTF_8)); + } + private ContextMemory memory( String fqn, ContextMemorySourceType sourceType, MemoryVisibility visibility) { return new ContextMemory() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryVisibility.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryVisibility.java index 10db27cde594..6e67f0604cbc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryVisibility.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/context/ContextMemoryVisibility.java @@ -13,7 +13,6 @@ package org.openmetadata.service.resources.context; -import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import com.google.common.cache.Cache; @@ -21,7 +20,6 @@ import jakarta.ws.rs.ForbiddenException; import jakarta.ws.rs.core.SecurityContext; import java.util.Collection; -import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; @@ -39,6 +37,7 @@ import org.openmetadata.schema.type.Include; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.ContextMemoryRepository; +import org.openmetadata.service.search.security.ContextMemorySearchVisibility; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.slf4j.Logger; @@ -298,11 +297,16 @@ private static boolean isAdmin(SecurityContext securityContext) { return admin; } + /** + * Whether {@code userName} is among the owners. Only an owner of type user can be the caller: a + * team owner named like the caller is a different principal. + */ public static boolean isOwnedBy(ContextMemory memory, String userName) { - if (memory.getOwners() == null || memory.getOwners().isEmpty() || userName == null) { + if (nullOrEmpty(memory.getOwners()) || userName == null) { return false; } return memory.getOwners().stream() + .filter(o -> Entity.USER.equals(o.getType())) .anyMatch(o -> userName.equals(o.getName()) || userName.equals(o.getFullyQualifiedName())); } @@ -315,6 +319,10 @@ private static boolean isInSharedWithList(ContextMemory memory, String userName) * Whether {@code userName} is named by a sharing list, directly or through a team or domain they * belong to. Public because Context Center shares files by the same vocabulary, and one matcher * is what keeps the two from drifting apart. + * + *

Principals are matched by id, as search matches them. Users, teams and domains are named + * independently of each other, so a name does not say which of them was shared with: a user who + * signs up under a team's name is not a member of that team. */ public static boolean isSharedWith(List sharedWith, String userName) { if (nullOrEmpty(sharedWith)) { @@ -325,33 +333,26 @@ public static boolean isSharedWith(List sharedWith, Strin .anyMatch( sp -> sp.getPrincipal() != null - && (principalIds.contains(sp.getPrincipal().getName()) - || principalIds.contains(sp.getPrincipal().getFullyQualifiedName()))); + && sp.getPrincipal().getId() != null + && principalIds.contains(sp.getPrincipal().getId().toString())); } + /** + * The ids a sharing list may name to reach {@code userName}: their own, their teams' and their + * domains'. A user that cannot be resolved is shared nothing. + */ static Set resolvePrincipalIdentifiers(String userName) { - Set ids = new HashSet<>(); - ids.add(userName); - try { - User user = - Entity.getEntityByName(Entity.USER, userName, "teams,domains", Include.NON_DELETED); - addRefNames(ids, user.getTeams()); - addRefNames(ids, user.getDomains()); - } catch (Exception e) { - LOG.debug("Could not resolve teams/domains for user '{}'", userName, e); - } - return ids; - } - - private static void addRefNames(Set ids, List refs) { - for (EntityReference ref : listOrEmpty(refs)) { - if (ref.getName() != null) { - ids.add(ref.getName()); - } - if (ref.getFullyQualifiedName() != null) { - ids.add(ref.getFullyQualifiedName()); + Set ids = Set.of(); + if (!nullOrEmpty(userName)) { + try { + User user = + Entity.getEntityByName(Entity.USER, userName, "teams,domains", Include.NON_DELETED); + ids = Set.copyOf(ContextMemorySearchVisibility.sharedPrincipalIds(user)); + } catch (RuntimeException e) { + LOG.debug("Could not resolve shared principal ids for user '{}'", userName, e); } } + return ids; } private static String getVisibilityDeniedMessage(ContextMemory memory) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileVisibility.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileVisibility.java index d5d7342a22b3..ab3779c7ec9e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileVisibility.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/drive/ContextFileVisibility.java @@ -157,6 +157,7 @@ public static boolean isOwnedBy(ContextFile file, String userName) { return false; } return file.getOwners().stream() + .filter(owner -> Entity.USER.equals(owner.getType())) .anyMatch( owner -> userName.equals(owner.getName()) || userName.equals(owner.getFullyQualifiedName())); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/resources/context/ContextMemoryVisibilityTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/resources/context/ContextMemoryVisibilityTest.java index 588533e4358d..e20085bfc9f3 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/resources/context/ContextMemoryVisibilityTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/resources/context/ContextMemoryVisibilityTest.java @@ -23,6 +23,7 @@ import jakarta.ws.rs.ForbiddenException; import jakarta.ws.rs.core.SecurityContext; +import java.nio.charset.StandardCharsets; import java.security.Principal; import java.util.Arrays; import java.util.List; @@ -72,7 +73,8 @@ void setUp() { () -> Entity.getEntityByName( eq(Entity.USER), any(String.class), eq("teams,domains"), any())) - .thenAnswer(inv -> new User().withName(inv.getArgument(1))); + .thenAnswer( + inv -> new User().withId(userId(inv.getArgument(1))).withName(inv.getArgument(1))); } @AfterEach @@ -159,6 +161,72 @@ void testSharedMemory_visibleOnlyToListedPrincipals() { "charlie is not in the sharedWith list and must not see the memory"); } + @Test + void testSharedMemory_visibleToMembersOfAListedTeamOrDomain() { + EntityReference team = ref(Entity.TEAM, "treasury", "treasury"); + EntityReference domain = ref(Entity.DOMAIN, "legal", "corp.legal"); + userBelongsTo(BOB, List.of(team), List.of()); + userBelongsTo("charlie", List.of(), List.of(domain)); + + assertTrue(ContextMemoryVisibility.isVisibleToUser(sharedWith(team), BOB, false)); + assertFalse(ContextMemoryVisibility.isVisibleToUser(sharedWith(domain), BOB, false)); + assertTrue(ContextMemoryVisibility.isVisibleToUser(sharedWith(domain), "charlie", false)); + assertFalse(ContextMemoryVisibility.isVisibleToUser(sharedWith(team), "charlie", false)); + } + + @Test + void testSharedMemory_aPrincipalOfTheSameNameIsNotTheListedPrincipal() { + EntityReference team = ref(Entity.TEAM, "legal", "legal"); + userBelongsTo(BOB, List.of(team), List.of(ref(Entity.DOMAIN, "legal", "emea.legal"))); + + assertFalse( + ContextMemoryVisibility.isVisibleToUser(sharedWith(team), "legal", false), + "a user named like the team is not a member of it"); + assertFalse( + ContextMemoryVisibility.isVisibleToUser( + sharedWith(ref(Entity.DOMAIN, "legal", "legal")), BOB, false), + "a member of the team is not in the domain named like it"); + assertFalse( + ContextMemoryVisibility.isVisibleToUser( + sharedWith(ref(Entity.DOMAIN, "legal", "apac.legal")), BOB, false), + "sub-domains of different parents share a name"); + assertFalse( + ContextMemoryVisibility.isVisibleToUser(sharedWith(ref(Entity.USER, BOB, BOB)), BOB, false), + "a user who took the name of a deleted one does not inherit what that one was shared"); + } + + @Test + void testSharedMemory_hiddenFromAUserThatCannotBeResolved() { + entityStaticMock + .when(() -> Entity.getEntityByName(eq(Entity.USER), eq(BOB), eq("teams,domains"), any())) + .thenThrow(new IllegalStateException("no such user")); + + assertFalse(ContextMemoryVisibility.isVisibleToUser(sharedWith(principalRef(BOB)), BOB, false)); + } + + @Test + void testSharedMemory_missingIdsAndAnonymousCallersAreDenied() { + assertFalse( + ContextMemoryVisibility.isVisibleToUser( + sharedWith(principalRef(BOB).withId(null)), BOB, false)); + assertFalse( + ContextMemoryVisibility.isVisibleToUser(sharedWith(principalRef(BOB)), null, false)); + } + + @Test + void testSharedMemory_idsStillMatchAfterAPrincipalIsRenamed() { + EntityReference team = ref(Entity.TEAM, "old-name", "old-name"); + userBelongsTo( + BOB, List.of(ref(Entity.TEAM, "new-name", "new-name").withId(team.getId())), List.of()); + + assertTrue(ContextMemoryVisibility.isVisibleToUser(sharedWith(team), BOB, false)); + assertTrue( + ContextMemoryVisibility.isVisibleToUser( + sharedWith(principalRef(BOB).withName("old-user").withFullyQualifiedName("old-user")), + BOB, + false)); + } + @Test void testAnchoredEntityMemory_visibleOnlyToReadersOfTheAnchor() { ContextMemory anchored = @@ -267,6 +335,15 @@ void testIsOwnedBy_matchesByNameOrFqn() { assertFalse(ContextMemoryVisibility.isOwnedBy(memory, BOB)); } + @Test + void testIsOwnedBy_aUserNamedLikeTheOwningTeamIsNotAnOwner() { + ContextMemory memory = + new ContextMemory().withOwners(List.of(ref(Entity.TEAM, "treasury", "treasury"))); + + assertFalse(ContextMemoryVisibility.isOwnedBy(memory, "treasury")); + assertFalse(ContextMemoryVisibility.isVisibleToUser(memory, "treasury", false)); + } + @Test void testIsOwnedBy_returnsFalseWhenUserNameIsNull() { EntityReference owner = @@ -486,11 +563,41 @@ private ContextMemory memoryOwnedBy(String userName, MemoryVisibility visibility return memory; } + private ContextMemory sharedWith(EntityReference principal) { + return memoryOwnedBy(ALICE, MemoryVisibility.SHARED) + .withShareConfig( + new MemoryShareConfig() + .withVisibility(MemoryVisibility.SHARED) + .withSharedWith(List.of(new MemorySharedPrincipal().withPrincipal(principal)))); + } + + private void userBelongsTo( + String userName, List teams, List domains) { + entityStaticMock + .when( + () -> Entity.getEntityByName(eq(Entity.USER), eq(userName), eq("teams,domains"), any())) + .thenReturn( + new User() + .withId(userId(userName)) + .withName(userName) + .withTeams(teams) + .withDomains(domains)); + } + private EntityReference principalRef(String userName) { + return ref("user", userName, userName).withId(userId(userName)); + } + + private static EntityReference ref(String type, String name, String fqn) { return new EntityReference() .withId(UUID.randomUUID()) - .withType("user") - .withName(userName) - .withFullyQualifiedName(userName); + .withType(type) + .withName(name) + .withFullyQualifiedName(fqn); + } + + /** The id the mocked user lookup resolves {@code userName} to. */ + private static UUID userId(String userName) { + return UUID.nameUUIDFromBytes(userName.getBytes(StandardCharsets.UTF_8)); } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/resources/drive/ContextFileVisibilityTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/resources/drive/ContextFileVisibilityTest.java index 2ad361c5e8cb..82f9fbf014fd 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/resources/drive/ContextFileVisibilityTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/resources/drive/ContextFileVisibilityTest.java @@ -4,6 +4,8 @@ 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.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -11,17 +13,25 @@ import jakarta.json.JsonPatch; import jakarta.ws.rs.ForbiddenException; import jakarta.ws.rs.core.SecurityContext; +import java.nio.charset.StandardCharsets; import java.security.Principal; import java.util.List; +import java.util.UUID; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.openmetadata.schema.entity.context.MemoryShareConfig; +import org.openmetadata.schema.entity.context.MemorySharedPrincipal; import org.openmetadata.schema.entity.context.MemoryVisibility; import org.openmetadata.schema.entity.data.ContextFile; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.Include; import org.openmetadata.schema.utils.ResultList; +import org.openmetadata.service.Entity; import org.openmetadata.service.security.DefaultAuthorizer; import org.openmetadata.service.security.policyevaluator.SubjectContext; @@ -72,6 +82,126 @@ void publicFilesRemainRestrictedToTheirOwners() { assertTrue(ContextFileVisibility.isVisibleToUser(file, ALICE, false)); } + @Test + void aUserNamedLikeTheOwningTeamIsNotAnOwner() { + ContextFile file = + fileOwnedBy(ALICE, MemoryVisibility.PRIVATE) + .withOwners( + List.of( + new EntityReference() + .withId(UUID.randomUUID()) + .withType(Entity.TEAM) + .withName(BOB))); + + assertFalse(ContextFileVisibility.isOwnedBy(file, BOB)); + assertFalse(ContextFileVisibility.isVisibleToUser(file, BOB, false)); + } + + @ParameterizedTest + @ValueSource(strings = {Entity.TEAM, Entity.DOMAIN}) + void aSharedPrincipalMustMatchById(String principalType) { + EntityReference principal = + new EntityReference().withId(UUID.randomUUID()).withType(principalType).withName(BOB); + User caller = new User().withId(UUID.randomUUID()).withName(BOB); + ContextFile file = + fileOwnedBy(ALICE, MemoryVisibility.SHARED) + .withShareConfig( + new MemoryShareConfig() + .withVisibility(MemoryVisibility.SHARED) + .withSharedWith(List.of(new MemorySharedPrincipal().withPrincipal(principal)))); + + try (MockedStatic entities = Mockito.mockStatic(Entity.class)) { + entities + .when( + () -> Entity.getEntityByName(Entity.USER, BOB, "teams,domains", Include.NON_DELETED)) + .thenReturn(caller); + assertFalse(ContextFileVisibility.isVisibleToUser(file, BOB, false)); + + if (Entity.TEAM.equals(principalType)) { + caller.withTeams(List.of(principal)); + } else { + caller.withDomains(List.of(principal)); + } + assertTrue(ContextFileVisibility.isVisibleToUser(file, BOB, false)); + } + } + + @Test + void aUserNamedLikeTheOwningTeamCannotRestrictTheFile() { + ContextFile open = fileOwnedBy(BOB, MemoryVisibility.ENTITY); + open.getOwners().getFirst().withType(Entity.TEAM).withId(UUID.randomUUID()); + ContextFile restricted = + fileOwnedBy(BOB, MemoryVisibility.PRIVATE).withOwners(open.getOwners()); + + assertThrows(ForbiddenException.class, () -> restrictAs(BOB, false, open, restricted)); + assertDoesNotThrow(() -> restrictAs(BOB, true, open, restricted)); + } + + @ParameterizedTest + @EnumSource( + value = MemoryVisibility.class, + names = {"PRIVATE", "SHARED"}) + void enforcementDeniesATeamNamesakeAndAdmitsAUserOwner(MemoryVisibility visibility) { + ContextFile teamOwned = fileOwnedBy(BOB, visibility); + teamOwned.getOwners().getFirst().withType(Entity.TEAM).withId(UUID.randomUUID()); + SecurityContext caller = securityContextFor(BOB); + try (MockedStatic authorizer = Mockito.mockStatic(DefaultAuthorizer.class)) { + authorizer + .when(() -> DefaultAuthorizer.getSubjectContext(caller)) + .thenReturn(new SubjectContext(new User().withName(BOB), null, null)); + + assertThrows( + ForbiddenException.class, + () -> ContextFileVisibility.enforceVisibility(teamOwned, caller)); + assertDoesNotThrow( + () -> ContextFileVisibility.enforceVisibility(fileOwnedBy(BOB, visibility), caller)); + } + } + + @Test + void folderChildrenExcludeATeamOwnersNamesake() { + ContextFile teamOwned = fileOwnedBy(BOB, MemoryVisibility.PRIVATE); + teamOwned.getOwners().getFirst().withType(Entity.TEAM).withId(UUID.randomUUID()); + ContextFile own = fileOwnedBy(BOB, MemoryVisibility.PRIVATE); + ContextFile orgWide = fileOwnedBy(ALICE, MemoryVisibility.ENTITY); + SecurityContext caller = securityContextFor(BOB); + try (MockedStatic authorizer = Mockito.mockStatic(DefaultAuthorizer.class)) { + authorizer + .when(() -> DefaultAuthorizer.getSubjectContext(caller)) + .thenReturn(new SubjectContext(new User().withName(BOB), null, null)); + + assertEquals( + List.of(own, orgWide), + ContextFileVisibility.filterVisible(List.of(teamOwned, own, orgWide), caller)); + } + } + + @Test + void anAnonymousReaderCannotReadAPrivateFile() { + assertThrows( + ForbiddenException.class, + () -> + ContextFileVisibility.enforceVisibility( + fileOwnedBy(BOB, MemoryVisibility.PRIVATE), null)); + } + + @Test + void emptyPagesKeepTheirPagingWithoutLookingUpACaller() { + ResultList empty = new ResultList<>(List.of(), BEFORE, AFTER, 0); + + assertSame(empty, ContextFileVisibility.filterByVisibility(empty, null)); + assertNull(ContextFileVisibility.filterByVisibility(null, null)); + } + + @Test + void readsRequestOwnersEvenWhenTheCallerOmitsThem() { + assertEquals("owners", ContextFileVisibility.guardFields(null)); + assertEquals("owners", ContextFileVisibility.guardFields("")); + assertEquals("description,owners", ContextFileVisibility.guardFields("description")); + assertEquals("owners", ContextFileVisibility.guardFields("owners")); + assertEquals("*", ContextFileVisibility.guardFields("*")); + } + @Test void onlyUnrestrictedAndEntityFilesAreOrgWide() { assertTrue(ContextFileVisibility.isOrgWide(new ContextFile())); @@ -147,7 +277,14 @@ private static ResultList visibleTo( } private static ContextFile fileOwnedBy(String owner, MemoryVisibility visibility) { - ContextFile file = new ContextFile().withOwners(List.of(new EntityReference().withName(owner))); + ContextFile file = + new ContextFile() + .withOwners( + List.of( + new EntityReference() + .withId(UUID.nameUUIDFromBytes(owner.getBytes(StandardCharsets.UTF_8))) + .withType(Entity.USER) + .withName(owner))); return visibility == null ? file : file.withShareConfig(new MemoryShareConfig().withVisibility(visibility));