diff --git a/docs/decisions/2026-11-13-a-listing-filters-its-rows-in-sql-compiled-from-the-callers-policies.md b/docs/decisions/2026-11-13-a-listing-filters-its-rows-in-sql-compiled-from-the-callers-policies.md index 8978cd32ac05..f3ecd881c6b4 100644 --- a/docs/decisions/2026-11-13-a-listing-filters-its-rows-in-sql-compiled-from-the-callers-policies.md +++ b/docs/decisions/2026-11-13-a-listing-filters-its-rows-in-sql-compiled-from-the-callers-policies.md @@ -1,11 +1,12 @@ # A listing filters its rows in SQL compiled from the caller's policies, and checks rows one at a time only where SQL cannot decide them - **Status:** Accepted -- **Revisions:** v1 2026-11-13 (initial); v2 2026-12-02 (team subtree limit) +- **Revisions:** v1 2026-11-13 (initial); v2 2026-12-02 (team subtree limit); v3 2026-12-07 + (custom list and aggregate endpoints carry the scope, the services overview first) - **Deciders:** OpenMetadata maintainers - **Guard:** `RowFilterDifferentialIT`, `ListRowPolicyConditionsIT`, `ListRowAuthorizationIT`, `RowFilterCompilerTest`, `SqlRowFilterRendererTest`, `ListFilterAccessScopeTest`, - `ListingConditionGuardTest`, `ListCountCacheTest` + `ListingConditionGuardTest`, `ListCountCacheTest`, `ServicesOverviewResourceIT` - **Related:** `docs/plans/2026-11-09-list-access-scope-design.md`; supersedes ADR:2026-11-03-a-listing-returns-only-rows-the-caller-may-read; ADR:2026-11-03-search-applies-the-same-access-rules-as-entity-reads @@ -55,6 +56,13 @@ conditional allow such as `ViewAll` with `isOwner()` answers 403 to the whole li users, and a deleted team brings no deny rules. An item read of a stored procedure or an API endpoint loads its parent with only the parent's live owners, as a table's read and every listing do. +- A custom list or aggregate endpoint over a listed type, which reads its rows without + `EntityResource`, carries the same scope: it asks `listScope` once per type, admits the type on + the entry rule above, and computes every number it returns (counts, per-bucket counts, totals) + with a query that carries the scope. Where the scope is inexact, it checks a bounded candidate set + one row at a time (`ViewPermissionFilter.retainPermittedIds`) and counts the rows that pass. A type + with more candidates than the bound is left out of the response rather than counted from part of + its rows. `GET /v1/services/overview` is the first such endpoint (bound: 10,000 candidates). - `TeamPolicySnapshot` keeps the snapshots of the last 4 policy generations, each for `SubjectCache.POLICIES_TTL` (2 minutes). A team or policy change made on another server is then seen within the bound the compiled policies already have. A snapshot keeps at most 256 team @@ -71,8 +79,9 @@ conditional allow such as `ViewAll` with `isOwner()` answers 403 to the whole li - A scoped count runs its correlated conditions on every page, uncached. Each team that holds a deny policy adds an owner subquery. Their cost was not measured. - An `Authorizer` that does not override `listScope` checks every row of every page. -- Search-backed lists, `/history`, time-series lists, custom list endpoints, MCP tools and filters - built outside `EntityResource` keep their current checks. A list filter can still be built +- Search-backed lists, `/history`, time-series lists, MCP tools, filters built outside + `EntityResource` and the custom list endpoints not yet moved onto the scope keep their current + checks. A list filter can still be built without a scope. The later steps of `docs/plans/2026-11-09-list-access-scope-design.md` cover them. - Revisit the 2,000-team limit, the 4 generations and the 256 subtrees if a tenant's team graph or diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RowFilterDifferentialIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RowFilterDifferentialIT.java index 414b06e578da..8b0e793e0555 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RowFilterDifferentialIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/RowFilterDifferentialIT.java @@ -44,16 +44,21 @@ import org.openmetadata.it.util.TestNamespace; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.policies.CreatePolicy; +import org.openmetadata.schema.api.services.CreateDriveService; import org.openmetadata.schema.api.teams.CreateRole; import org.openmetadata.schema.entity.policies.Policy; import org.openmetadata.schema.entity.policies.accessControl.Rule; +import org.openmetadata.schema.entity.services.DriveService; import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.services.connections.drive.GoogleDriveConnection; +import org.openmetadata.schema.type.DriveConnection; 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.service.Entity; +import org.openmetadata.service.jdbi3.ServicesOverviewRepository; import org.openmetadata.service.security.listaccess.ListAccess; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -98,6 +103,10 @@ public class RowFilterDifferentialIT { private static final Set NOTHING_TO_REFUSE = Set.of(Entity.USER + "/" + Scenario.TEAM_OUTSIDER, Entity.USER + "/" + Scenario.NO_OWNER); + private static final String OVERVIEW_PATH = "/v1/services/overview"; + private static final int OVERVIEW_PAGE_SIZE = 100; + private static final int SMALL_ROW_CHECK_WINDOW = 2; + private static final String ORGANIZATION_POLICY = "OrganizationPolicy"; private static final String ORGANIZATION_VIEW_RULE = "OrganizationPolicy-ViewAll-Rule"; private static final String DATA_CONSUMER_POLICY = "DataConsumerPolicy"; @@ -299,6 +308,135 @@ void aCallerWhoOwnsNothingGetsAnEmptyListingRatherThanARefusal() throws Exceptio }); } + static Stream overviewCases() { + return serviceTypes() + .flatMap(type -> Stream.of(Scenario.values()).map(rule -> Arguments.of(type, rule))); + } + + static Stream serviceTypes() { + return new TreeSet<>(ListAccess.coveredTypes()) + .stream().filter(Entity.getServiceEntityTypes()::contains); + } + + /** The services overview names and counts exactly the services the same caller can open. */ + @ParameterizedTest(name = "{0} {1}") + @MethodSource("overviewCases") + void theServicesOverviewShowsExactlyTheServicesItsItemEndpointsRead(String type, Scenario rule) + throws Exception { + Caller caller = fixture.callers.get(rule); + if (rule == Scenario.OWNER_ALLOWED) { + withTheOwnerRuleAsTheOnlyViewGrant(() -> compareOverviewWithItemReads(type, caller)); + } else { + compareOverviewWithItemReads(type, caller); + } + } + + /** + * A type whose rows are checked one by one, with more candidates than the row-check window, is + * left out of the overview, counts included, rather than counted from part of its rows. + */ + @Test + void aRowCheckedTypeWithMoreCandidatesThanTheWindowIsLeftOutOfTheOverview() throws Exception { + Caller caller = fixture.driveDomainCaller(); + for (int i = 0; i <= SMALL_ROW_CHECK_WINDOW; i++) { + fixture.driveService("overflow" + i); + } + String query = + OVERVIEW_PATH + + "?limit=1000&entityType=" + + Entity.DATABASE_SERVICE + + "&entityType=" + + Entity.DRIVE_SERVICE; + assertTrue(get(caller.client(), query).path("counts").has(Entity.DRIVE_SERVICE)); + + int previous = ServicesOverviewRepository.setRowCheckWindowForTesting(SMALL_ROW_CHECK_WINDOW); + try { + JsonNode overview = get(caller.client(), query); + + assertFalse(overview.path("counts").has(Entity.DRIVE_SERVICE), "counts"); + assertFalse( + overview.path("serviceTypeCounts").has(Entity.DRIVE_SERVICE), "serviceTypeCounts"); + overview + .path("data") + .forEach( + row -> assertFalse(Entity.DRIVE_SERVICE.equals(row.path("entityType").asText()))); + assertTrue(overview.path("counts").has(Entity.DATABASE_SERVICE), "other types stay"); + } finally { + ServicesOverviewRepository.setRowCheckWindowForTesting(previous); + } + } + + /** + * A caller whose only view grant is an Allow on {@code hasDomain()} sees, in the overview, the + * services of its domain and those with no domain, with counts to match. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("serviceTypes") + void aDomainAllowOnlyCallerSeesInTheOverviewTheServicesItCanOpen(String type) throws Exception { + withTheOwnerRuleAsTheOnlyViewGrant( + () -> compareOverviewWithItemReads(type, fixture.domainAllowed)); + } + + private static void compareOverviewWithItemReads(String type, Caller caller) throws Exception { + String collection = COLLECTIONS.get(type); + Set readable = rowsReadAs(caller, collection, adminListing(collection)); + Overview overview = overviewAll(caller, type, "", UNIVERSE_PAGE_SIZE); + + assertFalse(mine(type, readable).isEmpty(), type + " has no row " + caller.name() + " reads"); + assertEquals(new TreeSet<>(readable), new TreeSet<>(overview.names()), "data"); + assertEquals(readable.size(), overview.names().size(), "a service came back on two pages"); + assertEquals(Set.of(readable.size()), new HashSet<>(overview.totals()), "paging.total"); + assertEquals(readable.size(), overview.count(), "counts"); + assertEquals(readable.size(), overview.connectorCount(), "serviceTypeCounts"); + assertEquals(readable.size(), overview.healthCount(), "healthCounts"); + assertEquals( + overview.names().reversed(), + overviewAll(caller, type, "&sortOrder=desc", UNIVERSE_PAGE_SIZE).names(), + "desc"); + assertEquals( + overview.names(), overviewAll(caller, type, "", OVERVIEW_PAGE_SIZE).names(), "paging"); + } + + /** What the overview returned for one service type, walked page by page. */ + private record Overview( + List names, List totals, int count, int connectorCount, int healthCount) {} + + private static Overview overviewAll(Caller caller, String type, String query, int pageSize) + throws Exception { + List names = new ArrayList<>(); + List totals = new ArrayList<>(); + JsonNode page; + do { + page = + get( + caller.client(), + OVERVIEW_PATH + + "?includeHealth=true&limit=" + + pageSize + + "&offset=" + + names.size() + + "&entityType=" + + type + + query); + page.path("data").forEach(row -> names.add(row.path("fullyQualifiedName").asText())); + totals.add(page.path("paging").path("total").asInt(-1)); + } while (page.path("data").size() == pageSize); + return new Overview( + names, + totals, + page.path("counts").path(type).asInt(-1), + sum(page.path("serviceTypeCounts").path(type)), + sum(page.path("healthCounts").path(type))); + } + + private static int sum(JsonNode counts) { + int total = 0; + for (JsonNode value : counts) { + total += value.asInt(); + } + return total; + } + private static void compareListingWithItemReads(String type, Scenario rule) throws Exception { assertTrue(fixture.rowsByType.containsKey(type), "no fixture for declared type " + type); assertFalse(fixture.rowsByType.get(type).isEmpty(), "no rows in the fixture of " + type); @@ -501,6 +639,7 @@ private static final class Fixture { private Ref otherUser; private Ref leaver; private Caller nobody; + private Caller domainAllowed; private String domain; private String subDomain; private String otherDomain; @@ -536,6 +675,7 @@ Fixture build() { callers.put( Scenario.OWNER_ALLOWED, caller(user("allowed", List.of(callerTeam.id()), null, null))); nobody = caller(user("nobody", List.of(), null, null)); + domainAllowed = caller(user("domainAllowed", List.of(), domain, domainAllowRole())); rootTypes(); databaseChain(); siblingServices(); @@ -829,6 +969,10 @@ private Policy denyPolicy(String name, String condition) { .withOperations(List.of(MetadataOperation.ALL)) .withEffect(Rule.Effect.DENY) .withCondition(condition); + return policy(name, deny); + } + + private Policy policy(String name, Rule rule) { return ns.trackRoot( Entity.POLICY, admin @@ -836,8 +980,64 @@ private Policy denyPolicy(String name, String condition) { .create( new CreatePolicy() .withName(ns.prefix(name)) - .withDescription("Refuses the rows the condition names") - .withRules(List.of(deny)))); + .withDescription("Decides the rows the condition names") + .withRules(List.of(rule)))); + } + + /** Grants view on the rows of the caller's domain and on rows with no domain, nothing else. */ + private Role domainAllowRole() { + return roleWith( + "domainAllow", + new Rule() + .withName("allowDomain") + .withResources(new ArrayList<>(TYPES)) + .withOperations(List.of(MetadataOperation.VIEW_ALL)) + .withEffect(Rule.Effect.ALLOW) + .withCondition("hasDomain()")); + } + + private Role roleWith(String name, Rule rule) { + Policy policy = policy(name + "Policy", rule); + return ns.trackRoot( + Entity.ROLE, + admin + .roles() + .create( + new CreateRole() + .withName(ns.prefix(name + "Role")) + .withDescription("Decides the rows the condition names") + .withPolicies(List.of(policy.getFullyQualifiedName())))); + } + + /** + * A caller in the fixture's domain refused drive services outside it. Drive services have no + * declared row storage, so the overview checks each of them for this caller. + */ + private Caller driveDomainCaller() { + Role role = + roleWith( + "driveDomain", + new Rule() + .withName("denyOutsideDomain") + .withResources(List.of(Entity.DRIVE_SERVICE)) + .withOperations(List.of(MetadataOperation.ALL)) + .withEffect(Rule.Effect.DENY) + .withCondition("!hasDomain()")); + return caller(user("driveDomain", List.of(), domain, role)); + } + + private void driveService(String label) { + CreateDriveService request = + new CreateDriveService() + .withName(ns.prefix(label + "_" + suffix)) + .withServiceType(CreateDriveService.DriveServiceType.GoogleDrive) + .withConnection(new DriveConnection().withConfig(new GoogleDriveConnection())) + .withDomains(List.of(domain)); + DriveService created = + admin + .getHttpClient() + .execute(HttpMethod.POST, "/v1/services/driveServices", request, DriveService.class); + ns.trackRoot(Entity.DRIVE_SERVICE, created.getId()); } private Role role(Scenario scenario) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ServicesOverviewResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ServicesOverviewResourceIT.java index 11b99d5a7976..1e79b928c7a2 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ServicesOverviewResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/ServicesOverviewResourceIT.java @@ -19,11 +19,16 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.net.URI; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.TreeMap; import java.util.UUID; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -34,22 +39,33 @@ import org.openmetadata.it.util.TestNamespace; import org.openmetadata.it.util.TestNamespaceExtension; import org.openmetadata.schema.api.data.CreateDashboardDataModel.DashboardServiceType; +import org.openmetadata.schema.api.domains.CreateDomain; import org.openmetadata.schema.api.policies.CreatePolicy; import org.openmetadata.schema.api.services.CreateDashboardService; +import org.openmetadata.schema.api.services.CreateDatabaseService; +import org.openmetadata.schema.api.services.CreateDriveService; +import org.openmetadata.schema.api.services.DatabaseConnection; 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.domains.Domain; import org.openmetadata.schema.entity.policies.Policy; import org.openmetadata.schema.entity.policies.accessControl.Rule; import org.openmetadata.schema.entity.services.DashboardService; import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.entity.services.DriveService; import org.openmetadata.schema.entity.teams.Role; import org.openmetadata.schema.entity.teams.Team; import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.services.connections.dashboard.MetabaseConnection; +import org.openmetadata.schema.services.connections.drive.GoogleDriveConnection; import org.openmetadata.schema.type.DashboardConnection; +import org.openmetadata.schema.type.DriveConnection; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.TagLabel; import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.fluent.DatabaseServices; import org.openmetadata.sdk.network.HttpMethod; import org.openmetadata.sdk.network.RequestOptions; @@ -120,6 +136,10 @@ private DatabaseService snowflake(TestNamespace ns, String name) { } private DashboardService metabase(TestNamespace ns, String name) { + return metabaseIn(ns, name, null); + } + + private DashboardService metabaseIn(TestNamespace ns, String name, Domain domain) { CreateDashboardService request = new CreateDashboardService() .withName(ns.prefix(name)) @@ -129,7 +149,8 @@ private DashboardService metabase(TestNamespace ns, String name) { .withConfig( new MetabaseConnection() .withHostPort(URI.create("http://localhost:3000")) - .withUsername("admin"))); + .withUsername("admin"))) + .withDomains(domain == null ? null : List.of(domain.getFullyQualifiedName())); return ns.trackRoot( Entity.DASHBOARD_SERVICE, SdkClients.adminClient().dashboardServices().create(request)); } @@ -539,43 +560,547 @@ void aNonAdminSeesTheServiceTypesTheyArePermitted(TestNamespace ns) throws Excep */ private OpenMetadataClient clientDeniedOn(TestNamespace ns, String... deniedResources) throws Exception { - OpenMetadataClient admin = SdkClients.adminClient(); - String prefix = ns.shortPrefix(); - Rule deny = new Rule() .withName("DenyServiceTypes") .withResources(List.of(deniedResources)) .withOperations(List.of(MetadataOperation.VIEW_ALL, MetadataOperation.VIEW_BASIC)) .withEffect(Rule.Effect.DENY); + return clientWithDeny(ns, "denysvc", deny, List.of()); + } - CreatePolicy createPolicy = new CreatePolicy(); - createPolicy.setName(prefix + "_denySvcPol"); - createPolicy.setRules(List.of(deny)); - Policy policy = admin.policies().create(createPolicy); + /** + * A client for a user in {@code domain} whose role hides the given services outside their domains, + * the way a domain-scoped role is usually written on top of the organization's default view grant. + */ + private OpenMetadataClient domainScopedClient( + TestNamespace ns, String label, Domain domain, String... resources) throws Exception { + return clientWithDeny( + ns, label, denyOutsideDomain(resources), List.of(domain.getFullyQualifiedName())); + } - CreateRole createRole = new CreateRole(); - createRole.setName(prefix + "_denySvcRole"); - createRole.setPolicies(List.of(policy.getFullyQualifiedName())); - Role role = admin.roles().create(createRole); + private OpenMetadataClient clientWithDeny( + TestNamespace ns, String label, Rule deny, List userDomains) throws Exception { + Role role = roleWith(ns, label, deny); CreateTeam createTeam = new CreateTeam(); - createTeam.setName(prefix + "_denySvcTeam"); + createTeam.setName(ns.shortPrefix() + "_" + label + "_team"); createTeam.setTeamType(CreateTeam.TeamType.GROUP); createTeam.setDefaultRoles(List.of(role.getId())); - Team team = admin.teams().create(createTeam); + Team team = SdkClients.adminClient().teams().create(createTeam); + + return userClient(ns, label, List.of(team.getId()), List.of(), userDomains); + } + + private Role roleWith(TestNamespace ns, String label, Rule... rules) { + OpenMetadataClient admin = SdkClients.adminClient(); + String prefix = ns.shortPrefix() + "_" + label; - String email = prefix + "_denysvc@test.openmetadata.org"; + CreatePolicy createPolicy = new CreatePolicy(); + createPolicy.setName(prefix + "_pol"); + createPolicy.setRules(List.of(rules)); + Policy policy = admin.policies().create(createPolicy); + + CreateRole createRole = new CreateRole(); + createRole.setName(prefix + "_role"); + createRole.setPolicies(List.of(policy.getFullyQualifiedName())); + return admin.roles().create(createRole); + } + + private OpenMetadataClient userClient( + TestNamespace ns, String label, List teams, List roles, List domains) { + String prefix = ns.shortPrefix() + "_" + label; + String email = prefix + "@test.openmetadata.org"; CreateUser createUser = new CreateUser(); - createUser.setName(prefix + "_denysvc"); + createUser.setName(prefix); createUser.setEmail(email); - createUser.setTeams(List.of(team.getId())); - User user = admin.users().create(createUser); - assertNotNull(user, "the restricted user should be created"); + createUser.setTeams(teams); + createUser.setRoles(roles); + createUser.setDomains(domains); + User user = SdkClients.adminClient().users().create(createUser); + assertNotNull(user, "the user should be created"); return SdkClients.createClient(email, email, new String[] {}); } + private static Rule denyOutsideDomain(String... resources) { + return new Rule() + .withName("DenyOutsideDomain") + .withResources(List.of(resources)) + .withOperations(List.of(MetadataOperation.ALL)) + .withEffect(Rule.Effect.DENY) + .withCondition("!hasDomain()"); + } + + private static Rule allowView(String... resources) { + return new Rule() + .withName("AllowView") + .withResources(List.of(resources)) + .withOperations(List.of(MetadataOperation.VIEW_ALL)) + .withEffect(Rule.Effect.ALLOW); + } + + private static final String POSTGRES = "Postgres"; + private static final String SNOWFLAKE = "Snowflake"; + private static final String PII_SENSITIVE = "PII.Sensitive"; + private static final int PAGE_OF_TWO = 2; + + /** A database service of an estate, with what the overview's filters select it by. */ + private record Svc(DatabaseService service, String connector, Domain domain, boolean deleted) { + String name() { + return service.getName(); + } + } + + /** + * Database services sharing one search scope, one for each case the roles tell apart: in the home + * domain, in its sub-domain, in another domain, in none, owned by a team, tagged, and soft-deleted. + * They are listed in name order. + */ + private record Estate( + String scope, Domain home, Domain homeChild, Domain other, List services) { + Svc named(String suffix) { + return services.stream() + .filter(svc -> svc.name().startsWith(scope + "_" + suffix)) + .findFirst() + .orElseThrow(); + } + } + + private Estate estate(TestNamespace ns) throws Exception { + Domain home = domain(ns, "ovHome", null); + Domain homeChild = domain(ns, "ovHomeChild", home); + Domain other = domain(ns, "ovOther", null); + Team owners = groupTeam(ns, "ovOwners"); + String scope = "ovScope" + UUID.randomUUID().toString().substring(0, 8); + EntityReference ownerTeam = new EntityReference().withId(owners.getId()).withType(Entity.TEAM); + TagLabel sensitive = + new TagLabel() + .withTagFQN(PII_SENSITIVE) + .withSource(TagLabel.TagSource.CLASSIFICATION) + .withLabelType(TagLabel.LabelType.MANUAL); + List services = + List.of( + service(ns, new CreateDatabaseService().withName(scope + "_a_home"), POSTGRES, home), + service( + ns, new CreateDatabaseService().withName(scope + "_b_child"), POSTGRES, homeChild), + service(ns, new CreateDatabaseService().withName(scope + "_c_other"), SNOWFLAKE, other), + service(ns, new CreateDatabaseService().withName(scope + "_d_none"), POSTGRES, null), + service( + ns, + new CreateDatabaseService() + .withName(scope + "_e_owned") + .withOwners(List.of(ownerTeam)), + SNOWFLAKE, + null), + service( + ns, + new CreateDatabaseService() + .withName(scope + "_f_tagged") + .withTags(List.of(sensitive)), + POSTGRES, + home), + softDeleted( + service( + ns, + new CreateDatabaseService().withName(scope + "_g_deleted"), + POSTGRES, + home)), + softDeleted( + service( + ns, + new CreateDatabaseService().withName(scope + "_h_deleted"), + SNOWFLAKE, + other))); + return new Estate(scope, home, homeChild, other, services); + } + + private Svc service( + TestNamespace ns, CreateDatabaseService request, String connector, Domain domain) { + request + .withName(ns.prefix(request.getName())) + .withServiceType(CreateDatabaseService.DatabaseServiceType.fromValue(connector)) + .withConnection(new DatabaseConnection().withConfig(connectionFor(connector))) + .withDomains(domain == null ? null : List.of(domain.getFullyQualifiedName())); + DatabaseService created = + ns.trackRoot( + Entity.DATABASE_SERVICE, SdkClients.adminClient().databaseServices().create(request)); + return new Svc(created, connector, domain, false); + } + + private Object connectionFor(String connector) { + return POSTGRES.equals(connector) + ? DatabaseServices.postgresConnection().hostPort("localhost:5432").username("test").build() + : DatabaseServices.snowflakeConnection() + .account("test-account") + .username("test") + .warehouse("test-warehouse") + .build(); + } + + private Svc softDeleted(Svc svc) { + SdkClients.adminClient().databaseServices().delete(svc.service().getId().toString()); + return new Svc(svc.service(), svc.connector(), svc.domain(), true); + } + + private Domain domain(TestNamespace ns, String name, Domain parent) { + CreateDomain create = + new CreateDomain() + .withName(ns.prefix(name)) + .withDescription("Domain for services overview access tests") + .withDomainType(CreateDomain.DomainType.AGGREGATE) + .withParent(parent == null ? null : parent.getFullyQualifiedName()); + Domain created = SdkClients.adminClient().domains().create(create); + return parent == null ? ns.trackRoot(Entity.DOMAIN, created) : created; + } + + private Team groupTeam(TestNamespace ns, String name) { + CreateTeam createTeam = new CreateTeam(); + createTeam.setName(ns.shortPrefix() + "_" + name); + createTeam.setTeamType(CreateTeam.TeamType.GROUP); + return SdkClients.adminClient().teams().create(createTeam); + } + + private static List fqns(Domain... domains) { + return List.of(domains).stream().map(Domain::getFullyQualifiedName).toList(); + } + + /** Whether the caller's GET of the service, deleted ones included, succeeds. */ + private boolean canRead(OpenMetadataClient caller, Svc svc) throws Exception { + boolean readable = true; + try { + caller + .getHttpClient() + .executeForString( + HttpMethod.GET, + "/v1/services/databaseServices/" + svc.service().getId() + "?include=all", + null, + RequestOptions.builder().build()); + } catch (OpenMetadataException refused) { + assertEquals(403, refused.getStatusCode(), "a GET is either read or refused"); + readable = false; + } + return readable; + } + + /** + * The overview shows the caller exactly the services of the estate that the caller's item GETs + * read, and every number it returns agrees with them, under each filter, sort and page it offers. + */ + private void assertOverviewMatchesItemReads(OpenMetadataClient caller, Estate estate) + throws Exception { + assertOverviewMatchesItemReads(caller, estate, false); + } + + /** + * As above. With {@code roleReplacesDomain}, the caller's domain-only role replaces a requested + * domain with the role's own domains, as it does on every listing, so {@code domain=} narrows + * nothing for that caller. + */ + private void assertOverviewMatchesItemReads( + OpenMetadataClient caller, Estate estate, boolean roleReplacesDomain) throws Exception { + List readable = new ArrayList<>(); + for (Svc svc : estate.services()) { + if (canRead(caller, svc)) { + readable.add(svc); + } + } + List live = readable.stream().filter(svc -> !svc.deleted()).toList(); + List deleted = readable.stream().filter(Svc::deleted).toList(); + List inOther = + roleReplacesDomain + ? live + : live.stream().filter(svc -> estate.other().equals(svc.domain())).toList(); + List snowflake = live.stream().filter(svc -> SNOWFLAKE.equals(svc.connector())).toList(); + String query = + "q=" + estate.scope() + "&entityType=" + DATABASE_SERVICE + "&includeHealth=true"; + String all = query + "&limit=1000"; + String otherDomain = + URLEncoder.encode(estate.other().getFullyQualifiedName(), StandardCharsets.UTF_8); + + assertVariant(caller, all, live, live); + assertVariant(caller, all + "&serviceType=" + SNOWFLAKE, live, snowflake); + assertVariant(caller, all + "&health=notRun", live, live); + assertVariant(caller, all + "&domain=" + otherDomain, inOther, inOther); + assertVariant(caller, all + "&include=deleted", deleted, deleted); + assertVariant(caller, all + "&include=all", readable, readable); + assertEquals( + names(live).reversed(), listedNames(overviewAs(caller, all + "&sortOrder=desc")), "desc"); + assertEquals(names(live), pagedNames(caller, query, live.size()), "offset paging"); + } + + /** The response counts {@code counted}, its universe, and lists {@code listed}, in name order. */ + private void assertVariant( + OpenMetadataClient caller, String query, List counted, List listed) + throws Exception { + JsonNode response = overviewAs(caller, query); + + assertEquals(names(listed), listedNames(response), query); + assertEquals(listed.size(), response.get("paging").get("total").asInt(), query); + assertEquals(counted.size(), countFor(response, DATABASE_SERVICE), query + " counts"); + assertEquals(counted.size(), response.get("total").asInt(), query + " total"); + assertEquals( + byConnector(counted), + MAPPER.convertValue( + response.get("serviceTypeCounts").get(DATABASE_SERVICE), + new TypeReference>() {}), + query + " serviceTypeCounts"); + assertEquals( + counted.size(), + sumOf(response.path("healthCounts").path(DATABASE_SERVICE)), + query + " healthCounts"); + } + + private List pagedNames(OpenMetadataClient caller, String query, int total) + throws Exception { + List names = new ArrayList<>(); + for (int offset = 0; offset < total; offset += PAGE_OF_TWO) { + JsonNode page = overviewAs(caller, query + "&limit=" + PAGE_OF_TWO + "&offset=" + offset); + assertEquals(total, page.get("paging").get("total").asInt(), "paging.total at " + offset); + names.addAll(listedNames(page)); + } + return names; + } + + private static List names(List services) { + return services.stream().map(Svc::name).toList(); + } + + private static List listedNames(JsonNode response) { + List names = new ArrayList<>(); + response.get("data").forEach(service -> names.add(service.get("name").asText())); + return names; + } + + private static Map byConnector(List services) { + Map counts = new TreeMap<>(); + services.forEach(svc -> counts.merge(svc.connector(), 1, Integer::sum)); + return counts; + } + + private void assertRefused(OpenMetadataClient caller, Svc svc) throws Exception { + assertFalse(canRead(caller, svc), "the caller must not open " + svc.name()); + } + + private DriveService googleDriveIn(TestNamespace ns, String name, Domain domain) + throws Exception { + CreateDriveService request = + new CreateDriveService() + .withName(ns.prefix(name)) + .withServiceType(CreateDriveService.DriveServiceType.GoogleDrive) + .withConnection(new DriveConnection().withConfig(new GoogleDriveConnection())) + .withDomains(List.of(domain.getFullyQualifiedName())); + return ns.trackRoot( + Entity.DRIVE_SERVICE, + SdkClients.adminClient() + .getHttpClient() + .execute(HttpMethod.POST, "/v1/services/driveServices", request, DriveService.class)); + } + + @Test + void anAdminSeesEveryService(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + + assertOverviewMatchesItemReads(SdkClients.adminClient(), estate); + } + + /** The organization's default view grant has no condition, so it reaches every service. */ + @Test + void aCallerWithTheUnconditionalViewGrantSeesEveryService(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + OpenMetadataClient caller = + userClient(ns, "viewall", List.of(), List.of(), fqns(estate.home())); + + assertOverviewMatchesItemReads(caller, estate); + } + + /** + * Database services have their domains in SQL, so the caller's scope decides counts, the list and + * health in the queries themselves. A domain covers its sub-domains, and a service with no domain + * stays visible under {@code !hasDomain()}. + */ + @Test + void aDomainScopedCallerSeesTheirDomainItsSubDomainAndServicesWithNoDomain(TestNamespace ns) + throws Exception { + Estate estate = estate(ns); + OpenMetadataClient caller = + clientWithDeny(ns, "dbdom", denyOutsideDomain(DATABASE_SERVICE), fqns(estate.home())); + assertTrue(canRead(caller, estate.named("b_child")), "a domain covers its sub-domain"); + assertTrue(canRead(caller, estate.named("d_none")), "a service with no domain is readable"); + assertRefused(caller, estate.named("c_other")); + + assertOverviewMatchesItemReads(caller, estate); + } + + @Test + void aSubDomainCallerDoesNotSeeTheParentDomainsServices(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + OpenMetadataClient caller = + clientWithDeny( + ns, "childdom", denyOutsideDomain(DATABASE_SERVICE), fqns(estate.homeChild())); + assertRefused(caller, estate.named("a_home")); + assertTrue(canRead(caller, estate.named("b_child"))); + + assertOverviewMatchesItemReads(caller, estate); + } + + @Test + void aCallerInTwoDomainsSeesTheServicesOfBoth(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + OpenMetadataClient caller = + clientWithDeny( + ns, + "twodoms", + denyOutsideDomain(DATABASE_SERVICE), + fqns(estate.home(), estate.other())); + assertTrue(canRead(caller, estate.named("c_other"))); + + assertOverviewMatchesItemReads(caller, estate); + } + + @Test + void aCallerWithNoDomainSeesOnlyServicesWithNoDomain(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + OpenMetadataClient caller = + clientWithDeny(ns, "nodom", denyOutsideDomain(DATABASE_SERVICE), List.of()); + assertRefused(caller, estate.named("a_home")); + assertTrue(canRead(caller, estate.named("d_none"))); + + assertOverviewMatchesItemReads(caller, estate); + } + + @Test + void aDomainOnlyAccessRoleCallerSeesTheirDomainsServices(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + Role domainOnly = SdkClients.adminClient().roles().getByName("DomainOnlyAccessRole"); + OpenMetadataClient caller = + userClient(ns, "domonly", List.of(), List.of(domainOnly.getId()), fqns(estate.home())); + assertRefused(caller, estate.named("c_other")); + + assertOverviewMatchesItemReads(caller, estate, true); + } + + /** A Deny on rows outside the caller's domain wins over an Allow that names every row. */ + @Test + void anExplicitDenyOverridesAnAllowOnTheSameServices(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + Role role = + roleWith(ns, "denywins", allowView(DATABASE_SERVICE), denyOutsideDomain(DATABASE_SERVICE)); + OpenMetadataClient caller = + userClient(ns, "denywins", List.of(), List.of(role.getId()), fqns(estate.home())); + assertRefused(caller, estate.named("c_other")); + + assertOverviewMatchesItemReads(caller, estate); + } + + /** + * A Deny on {@code noOwner()} is true for the type itself, which has no owner, so a check on the + * type alone would hide every service; the type is admitted on its rows instead. + */ + @Test + void aDenyOnServicesWithNoOwnerLeavesTheOwnedOnes(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + Rule denyUnowned = + new Rule() + .withName("DenyUnowned") + .withResources(List.of(DATABASE_SERVICE)) + .withOperations(List.of(MetadataOperation.ALL)) + .withEffect(Rule.Effect.DENY) + .withCondition("noOwner()"); + OpenMetadataClient caller = clientWithDeny(ns, "noowner", denyUnowned, List.of()); + assertTrue(canRead(caller, estate.named("e_owned"))); + assertRefused(caller, estate.named("a_home")); + + assertOverviewMatchesItemReads(caller, estate); + } + + /** SQL cannot decide a tag condition, so each candidate service is checked as its GET is. */ + @Test + void aDenyOnATagHidesTheTaggedServiceAndItsCounts(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + Rule denyTagged = + new Rule() + .withName("DenyTagged") + .withResources(List.of(DATABASE_SERVICE)) + .withOperations(List.of(MetadataOperation.ALL)) + .withEffect(Rule.Effect.DENY) + .withCondition("matchAnyTag('" + PII_SENSITIVE + "')"); + OpenMetadataClient caller = clientWithDeny(ns, "tagdeny", denyTagged, fqns(estate.home())); + assertRefused(caller, estate.named("f_tagged")); + + assertOverviewMatchesItemReads(caller, estate); + } + + /** + * Two roles each scope their own service type: the domain condition narrows database services + * and leaves the dashboard services the other role grants untouched. + */ + @Test + void eachOfTwoRolesNarrowsOnlyTheServiceTypeItNames(TestNamespace ns) throws Exception { + Estate estate = estate(ns); + DashboardService otherDomainDashboard = + metabaseIn(ns, estate.scope() + "_z_dash", estate.other()); + Role databaseRole = roleWith(ns, "dbrole", denyOutsideDomain(DATABASE_SERVICE)); + Role dashboardRole = roleWith(ns, "dashrole", allowView(DASHBOARD_SERVICE)); + OpenMetadataClient caller = + userClient( + ns, + "tworoles", + List.of(), + List.of(databaseRole.getId(), dashboardRole.getId()), + fqns(estate.home())); + assertRefused(caller, estate.named("c_other")); + assertNotNull(caller.dashboardServices().get(otherDomainDashboard.getId().toString())); + + JsonNode response = overviewAs(caller, "limit=1000&q=" + estate.scope()); + + assertTrue(listedNames(response).contains(otherDomainDashboard.getName())); + assertEquals(1, countFor(response, DASHBOARD_SERVICE)); + assertEquals( + countFor(response, DATABASE_SERVICE) + 1, response.get("paging").get("total").asInt()); + assertOverviewMatchesItemReads(caller, estate); + } + + /** + * Drive services have no declared row storage, so a domain condition cannot be decided in SQL and + * each candidate is checked as its item endpoint checks it, counts included. + */ + @Test + void aDomainScopedCallerSeesOnlyTheDriveServicesTheirDomainAllows(TestNamespace ns) + throws Exception { + Domain finance = domain(ns, "ovDriveFinance", null); + Domain sales = domain(ns, "ovDriveSales", null); + OpenMetadataClient caller = domainScopedClient(ns, "drivedom", finance, Entity.DRIVE_SERVICE); + String scope = "driveScope" + UUID.randomUUID().toString().substring(0, 8); + DriveService inDomain = googleDriveIn(ns, scope + "_a_in", finance); + googleDriveIn(ns, scope + "_b_out", sales); + + JsonNode response = + overviewAs( + caller, + "limit=1000&includeHealth=true&q=" + scope + "&entityType=" + Entity.DRIVE_SERVICE); + + assertEquals(List.of(inDomain.getName()), namespacedNames(response, ns)); + assertEquals(1, countFor(response, Entity.DRIVE_SERVICE)); + assertEquals(1, response.get("paging").get("total").asInt()); + assertEquals( + 1, response.get("serviceTypeCounts").get(Entity.DRIVE_SERVICE).get("GoogleDrive").asInt()); + assertEquals(1, sumOf(response.get("healthCounts").get(Entity.DRIVE_SERVICE))); + } + + @Test + void aCallerWhoMayViewNoServiceTypeIsRefused(TestNamespace ns) throws Exception { + OpenMetadataClient refused = + clientDeniedOn(ns, Entity.getServiceEntityTypes().toArray(String[]::new)); + + OpenMetadataException refusal = + assertThrows( + OpenMetadataException.class, + () -> overviewAs(refused, "limit=500"), + "a caller with no view grant on any service type is refused, not shown an empty estate"); + assertEquals(403, refusal.getStatusCode()); + } + /** * The endpoint evaluates VIEW_BASIC per service entity type and drops the ones the caller cannot * see, rather than failing the whole request. Without this the count maps a client drives its diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServicesOverviewRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServicesOverviewRepository.java index 71fbabd39853..cddfbba7eaed 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServicesOverviewRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ServicesOverviewRepository.java @@ -22,6 +22,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; @@ -29,8 +30,12 @@ import org.openmetadata.schema.api.services.ServiceHealth; import org.openmetadata.schema.api.services.ServiceSummary; import org.openmetadata.schema.api.services.ServicesOverview; +import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.Paging; import org.openmetadata.service.Entity; +import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.ViewPermissionFilter; +import org.openmetadata.service.security.listaccess.CallerScope; import org.openmetadata.service.util.EntityUtil; /** @@ -47,7 +52,10 @@ *
  • Reads keys, then hydrates only the page. Each entity type contributes an index-only * {@code (name, id)} scan; those are merged and sliced, and only the surviving page is * deserialized from {@code json}. The number of rows deserialized is therefore bounded by - * {@code limit} regardless of how many services exist. + * {@code limit} regardless of how many services exist, except for a type whose access the + * caller's scope cannot decide in SQL: its candidates, up to {@link + * ServicesOverviewRequest#MAX_WINDOW}, are loaded for the per-row check, and a type with more + * is left out of the response. * */ @Slf4j @@ -59,14 +67,47 @@ public class ServicesOverviewRepository { */ private static final String SUMMARY_FIELDS = "owners,tags"; + /** The summary's fields (owners, tags) are ViewBasic fields, as on each service's own GET. */ + public static final List VIEW_OPERATIONS = + List.of(MetadataOperation.VIEW_BASIC); + + /** + * How many candidates of a type whose rows are checked one by one may be checked. A type with more + * is left out of the response: a count over a truncated candidate set would look exact and be + * wrong. Equal to {@link ServicesOverviewRequest#MAX_WINDOW} outside tests. + */ + private static volatile int rowCheckWindow = ServicesOverviewRequest.MAX_WINDOW; + private final ServiceHealthProvider healthProvider; + private final ViewPermissionFilter viewPermissionFilter; - public ServicesOverviewRepository(ServiceHealthProvider healthProvider) { + public ServicesOverviewRepository(ServiceHealthProvider healthProvider, Authorizer authorizer) { this.healthProvider = healthProvider; + this.viewPermissionFilter = new ViewPermissionFilter(authorizer); + } + + /** + * Sets how many candidates a row-checked type may have, so a test can exceed it without thousands + * of services. Returns the previous value, for the test to restore. + */ + public static int setRowCheckWindowForTesting(int window) { + int previous = rowCheckWindow; + rowCheckWindow = window; + return previous; } - public ServicesOverview getOverview(SecurityContext securityContext, ServicesOverviewRequest r) { - Map> byConnector = countsByConnector(securityContext, r); + /** + * The overview of {@code requested}'s service types, each read within the caller's {@code scopes}, + * which the resource resolved when it decided which types the caller may list. + */ + public ServicesOverview getOverview( + SecurityContext securityContext, + ServicesOverviewRequest requested, + Map scopes) { + Map access = accessByType(securityContext, requested, scopes); + ServicesOverviewRequest r = requested.restrictedTo(access.keySet()); + OverviewCaller caller = new OverviewCaller(securityContext, access); + Map> byConnector = countsByConnector(caller, r); Map counts = sumInner(byConnector); assertHealthFilterIsSatisfiable(counts, r); boolean universeResolvable = isUniverseResolvable(counts, r); @@ -75,10 +116,10 @@ public ServicesOverview getOverview(SecurityContext securityContext, ServicesOve // entity type. Deriving them independently ran it twice on every request that asks for health // — which the Connections page does on every load. Map> universeKeys = - r.includeHealth() && universeResolvable ? universeKeys(securityContext, r) : Map.of(); + r.includeHealth() && universeResolvable ? universeKeys(caller, r) : Map.of(); Map universeHealth = universeHealth(universeKeys); Map> byHealth = countsByHealth(universeKeys, universeHealth); - List keys = listKeys(securityContext, r); + List keys = listKeys(caller, r); List page = slice(keys, r.offset(), r.limit()); List data = hydrate(page, pageHealth(r, page, universeHealth), r); int listTotal = listTotal(counts, byConnector, keys, r); @@ -95,21 +136,144 @@ public ServicesOverview getOverview(SecurityContext securityContext, ServicesOve /** A merged-page key. {@code name}/{@code id} mirror the DB's {@code ORDER BY name, id}. */ record TypedKey(String entityType, String name, UUID id) {} + private record OverviewCaller(SecurityContext securityContext, Map access) { + TypeAccess of(String entityType) { + return access.get(entityType); + } + } + + /** + * The services of one type the caller may read. The caller's compiled scope narrows every query of + * the type, as on the type's own list endpoint + * (ADR:2026-11-13-a-listing-filters-its-rows-in-sql-compiled-from-the-callers-policies). Where SQL + * cannot decide every row (e.g. a domain condition on a type with no declared row storage), {@code + * readableKeys} holds the rows that passed the per-row check, with each one's connector, and the + * type is counted and listed from them. + */ + private record TypeAccess( + CallerScope scope, List readableKeys, Map serviceTypeById) { + static TypeAccess decidedInSql(CallerScope scope) { + return new TypeAccess(scope, null, null); + } + + boolean isDecidedInSql() { + return readableKeys == null; + } + + Map connectorCounts() { + Map counts = new LinkedHashMap<>(); + serviceTypeById.values().forEach(type -> counts.merge(type, 1, Integer::sum)); + return counts; + } + + /** The readable keys of the listed connectors, or of every connector when none is selected. */ + List listedKeys(Set serviceTypes) { + return nullOrEmpty(serviceTypes) + ? readableKeys + : readableKeys.stream() + .filter(key -> serviceTypes.contains(serviceTypeById.get(key.id()))) + .toList(); + } + } + + // ---------------------------------------------------------------- access + + private Map accessByType( + SecurityContext securityContext, ServicesOverviewRequest r, Map scopes) { + Map access = new LinkedHashMap<>(); + for (String entityType : r.entityTypes()) { + typeAccess(securityContext, r, entityType, scopes.get(entityType)) + .ifPresent(typeAccess -> access.put(entityType, typeAccess)); + } + return access; + } + + private Optional typeAccess( + SecurityContext securityContext, + ServicesOverviewRequest r, + String entityType, + CallerScope scope) { + return scope.exact() + ? Optional.of(TypeAccess.decidedInSql(scope)) + : rowCheckedAccess(securityContext, r, entityType, scope); + } + + /** + * Checks each candidate row as the service's own GET checks it. A type with more candidates than + * the row-check window is left out entirely, counts included, rather than counted from part of + * its rows. + */ + private Optional rowCheckedAccess( + SecurityContext securityContext, + ServicesOverviewRequest r, + String entityType, + CallerScope scope) { + int window = rowCheckWindow; + ListFilter filter = scopedFilter(securityContext, r, entityType, scope); + List candidates = scanKeys(entityType, filter, window + 1, true); + Optional access = Optional.empty(); + if (candidates.size() > window) { + LOG.warn( + "services overview: leaving out {}, whose more than {} candidates are each checked for " + + "this caller; narrow the request with q or domain", + entityType, + window); + } else { + access = Optional.of(checkedAccess(securityContext, entityType, scope, candidates)); + } + return access; + } + + private TypeAccess checkedAccess( + SecurityContext securityContext, + String entityType, + CallerScope scope, + List candidates) { + Map> readable = readableRows(securityContext, entityType, candidates); + Map serviceTypeById = new HashMap<>(); + readable.values().forEach(row -> serviceTypeById.put(row.getId(), serviceTypeOf(row))); + List readableKeys = + candidates.stream().filter(key -> readable.containsKey(key.id())).toList(); + return new TypeAccess(scope, readableKeys, serviceTypeById); + } + + @SuppressWarnings("unchecked") + private Map> readableRows( + SecurityContext securityContext, String entityType, List candidates) { + EntityRepository> repository = + (EntityRepository>) Entity.getEntityRepository(entityType); + Map> readable = new HashMap<>(); + viewPermissionFilter + .retainPermittedIds( + securityContext, + entityType, + repository, + candidates.stream().map(TypedKey::id).toList(), + VIEW_OPERATIONS) + .forEach(row -> readable.put(row.getId(), row)); + return readable; + } + // ---------------------------------------------------------------- counts private Map> countsByConnector( - SecurityContext securityContext, ServicesOverviewRequest r) { + OverviewCaller caller, ServicesOverviewRequest r) { Map> result = new LinkedHashMap<>(); for (String entityType : r.entityTypes()) { - result.put(entityType, connectorCounts(securityContext, r, entityType)); + TypeAccess access = caller.of(entityType); + result.put( + entityType, + access.isDecidedInSql() + ? connectorCounts(caller, r, entityType) + : access.connectorCounts()); } return result; } private Map connectorCounts( - SecurityContext securityContext, ServicesOverviewRequest r, String entityType) { + OverviewCaller caller, ServicesOverviewRequest r, String entityType) { Map counts = new LinkedHashMap<>(); - ListFilter filter = countFilter(securityContext, r, entityType); + ListFilter filter = countFilter(caller, r, entityType); for (EntityDAO.ServiceTypeCount row : Entity.getEntityRepository(entityType).getDao().listCountByServiceType(filter)) { counts.merge(row.serviceType(), row.count(), Integer::sum); @@ -218,11 +382,19 @@ private Map pageHealth( * universe — including the ones with no pipelines, which no pipeline-side query can see. */ private Map> universeKeys( - SecurityContext securityContext, ServicesOverviewRequest r) { + OverviewCaller caller, ServicesOverviewRequest r) { Map> keys = new LinkedHashMap<>(); for (String entityType : r.entityTypes()) { - ListFilter filter = countFilter(securityContext, r, entityType); - keys.put(entityType, scanKeys(entityType, filter, ServicesOverviewRequest.MAX_WINDOW, true)); + TypeAccess access = caller.of(entityType); + keys.put( + entityType, + access.isDecidedInSql() + ? scanKeys( + entityType, + countFilter(caller, r, entityType), + ServicesOverviewRequest.MAX_WINDOW, + true) + : access.readableKeys()); } return keys; } @@ -236,11 +408,10 @@ private Map> universeKeys( * universe-wide map: the filter only ever narrows {@code data}, which is scoped to the listed * types, so it has no business depending on how large some unrelated service type happens to be. */ - private List listKeys(SecurityContext securityContext, ServicesOverviewRequest r) { + private List listKeys(OverviewCaller caller, ServicesOverviewRequest r) { List> perType = new ArrayList<>(); for (String entityType : r.listEntityTypes()) { - ListFilter filter = listFilter(securityContext, r, entityType); - perType.add(scanKeys(entityType, filter, r.keyScanLimit(), r.ascending())); + perType.add(readableListKeys(caller, r, entityType)); } Map health = healthForFilter(r, perType); return merge( @@ -258,6 +429,15 @@ private Map healthForFilter( return health; } + /** A type whose rows are checked one by one is listed from the rows already checked. */ + private List readableListKeys( + OverviewCaller caller, ServicesOverviewRequest r, String entityType) { + TypeAccess access = caller.of(entityType); + return access.isDecidedInSql() + ? scanKeys(entityType, listFilter(caller, r, entityType), r.keyScanLimit(), r.ascending()) + : access.listedKeys(r.serviceTypes()); + } + private List scanKeys( String entityType, ListFilter filter, int limit, boolean ascending) { return Entity.getEntityRepository(entityType) @@ -392,8 +572,16 @@ private String serviceTypeOf(EntityInterface entity) { /** Filters that scope the counted universe. Deliberately excludes the list-only selectors. */ private ListFilter countFilter( - SecurityContext securityContext, ServicesOverviewRequest r, String entityType) { - ListFilter filter = new ListFilter(r.include()); + OverviewCaller caller, ServicesOverviewRequest r, String entityType) { + return scopedFilter(caller.securityContext(), r, entityType, caller.of(entityType).scope()); + } + + private ListFilter scopedFilter( + SecurityContext securityContext, + ServicesOverviewRequest r, + String entityType, + CallerScope scope) { + ListFilter filter = new ListFilter(r.include()).withAccessScope(scope); if (r.excludeProvider() != null) { filter.addQueryParam("excludeProvider", r.excludeProvider().value()); } @@ -408,8 +596,8 @@ private ListFilter countFilter( } private ListFilter listFilter( - SecurityContext securityContext, ServicesOverviewRequest r, String entityType) { - ListFilter filter = countFilter(securityContext, r, entityType); + OverviewCaller caller, ServicesOverviewRequest r, String entityType) { + ListFilter filter = countFilter(caller, r, entityType); if (!nullOrEmpty(r.serviceTypes())) { filter.addQueryParam("connectorType", String.join(",", r.serviceTypes())); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/EntityResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/EntityResource.java index 0bb530fec251..b9c8571aaeed 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/EntityResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/EntityResource.java @@ -919,15 +919,10 @@ private List readableRows( if (rows.isEmpty()) { return rows; } - List copies = - repository.get( - null, - rows.stream().map(T::getId).distinct().toList(), - ResourceContext.authorizationFields(repository), - Include.ALL); + List ids = rows.stream().map(T::getId).distinct().toList(); Set readable = viewPermissionFilter - .retainPermitted(securityContext, entityType, repository, copies, operations) + .retainPermittedIds(securityContext, entityType, repository, ids, operations) .stream() .map(EntityInterface::getId) .collect(Collectors.toSet()); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/ServicesOverviewResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/ServicesOverviewResource.java index 4bb5cc424e3a..3471cf0fa72c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/ServicesOverviewResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/services/ServicesOverviewResource.java @@ -13,6 +13,7 @@ package org.openmetadata.service.resources.services; import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; +import static org.openmetadata.service.jdbi3.ServicesOverviewRepository.VIEW_OPERATIONS; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -33,7 +34,9 @@ import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.SecurityContext; +import java.util.LinkedHashMap; import java.util.LinkedHashSet; +import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.stream.Collectors; @@ -50,6 +53,7 @@ import org.openmetadata.service.resources.Collection; import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.Authorizer; +import org.openmetadata.service.security.listaccess.CallerScope; import org.openmetadata.service.security.policyevaluator.OperationContext; import org.openmetadata.service.security.policyevaluator.ResourceContext; @@ -73,7 +77,8 @@ public class ServicesOverviewResource { public ServicesOverviewResource(Authorizer authorizer) { this.authorizer = authorizer; this.repository = - new ServicesOverviewRepository(new ServiceHealthProvider(Entity.getCollectionDAO())); + new ServicesOverviewRepository( + new ServiceHealthProvider(Entity.getCollectionDAO()), authorizer); } @GET @@ -159,7 +164,12 @@ public ServicesOverview getOverview( include, domain, excludeProvider); - return repository.getOverview(securityContext, authorizedScope(securityContext, request)); + Map scopes = viewableScopes(securityContext, request.entityTypes()); + if (scopes.isEmpty()) { + throw new AuthorizationException( + "User does not have VIEW_BASIC permission on any of the requested service types"); + } + return repository.getOverview(securityContext, request.restrictedTo(scopes.keySet()), scopes); } /** @@ -173,27 +183,30 @@ public ServicesOverview getOverview( *

    So permission is evaluated per type and the unauthorized ones are dropped before anything is * counted or listed — an unauthorized type is absent from the response rather than merely absent * from {@code data}. This does make {@code total} caller-dependent, which is correct: it is the - * size of the estate *this* caller can see. + * size of the estate *this* caller can see. Within a permitted type, the repository keeps only the + * services the caller may read, as the type's own list endpoint does. + * + *

    A type is permitted on the same rule as the type's own list endpoint + * ({@code EntityResource.authorizeListing}): when the caller's policies decide its rows, they + * authorize it, since a check on the type alone cannot see the rows a condition allows (e.g. an + * {@code isOwner()} grant); otherwise the check on the type decides. Each type's scope is resolved + * once here and handed to the repository, so the two decisions cannot drift apart. * *

    Each check goes through the injected {@link Authorizer} rather than evaluating policies * directly, so the endpoint follows whatever authorization the deployment configured. Calling the * policy evaluator straight would make this the one endpoint that still enforces RBAC under a * no-op authorizer, silently hiding service types the rest of the API serves. */ - private ServicesOverviewRequest authorizedScope( - SecurityContext securityContext, ServicesOverviewRequest request) { - Set allowed = viewableTypes(securityContext, request.entityTypes()); - if (allowed.isEmpty()) { - throw new AuthorizationException( - "User does not have VIEW_BASIC permission on any of the requested service types"); + private Map viewableScopes( + SecurityContext securityContext, Set requested) { + Map scopes = new LinkedHashMap<>(); + for (String entityType : requested) { + CallerScope scope = authorizer.listScope(securityContext, entityType, VIEW_OPERATIONS); + if (scope.authorizesListing(VIEW_OPERATIONS) || canView(securityContext, entityType)) { + scopes.put(entityType, scope); + } } - return request.restrictedTo(allowed); - } - - private Set viewableTypes(SecurityContext securityContext, Set requested) { - return requested.stream() - .filter(entityType -> canView(securityContext, entityType)) - .collect(Collectors.toCollection(LinkedHashSet::new)); + return scopes; } private boolean canView(SecurityContext securityContext, String entityType) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java index 3b3e377246ca..9fe98f00bca4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/security/ViewPermissionFilter.java @@ -108,6 +108,24 @@ check, new EntityReference().withId(row.getId()).withType(entityType), context)) return permitted; } + /** + * The rows with {@code ids} the caller may read with every one of {@code operations}, decided on + * copies loaded with exactly the fields authorization reads, deleted rows included. + */ + public > List retainPermittedIds( + SecurityContext securityContext, + String entityType, + EntityRepository repository, + List ids, + List operations) { + List copies = + ids.isEmpty() + ? List.of() + : repository.get( + null, ids, ResourceContext.authorizationFields(repository), Include.ALL); + return retainPermitted(securityContext, entityType, repository, copies, operations); + } + /** * Whether the caller may perform {@code operations} on {@code resource} as {@code context} * describes it, for a row whose item endpoint authorizes it through another entity, as a test