diff --git a/bootstrap/sql/migrations/native/2.1.2/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.2/mysql/postDataMigrationSQLScript.sql index 290488876a4c..a18a17650c45 100644 --- a/bootstrap/sql/migrations/native/2.1.2/mysql/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.1.2/mysql/postDataMigrationSQLScript.sql @@ -21,3 +21,23 @@ WHERE name IN ( 'UsageBotRole') AND (COALESCE(json ->> '$.provider', '') <> 'system' OR COALESCE(json ->> '$.allowDelete', '') <> 'false'); + +-- OrganizationPolicy-NoOwner-Rule names the data asset types anyone may claim when they have no +-- owner. Applied only where the policy has one rule of that name and it is still the shipped one; +-- every other rule is left as stored. ADR:2026-12-02-only-data-assets-can-be-claimed-by-default +UPDATE policy_entity +SET json = JSON_SET( + json, + REPLACE(JSON_UNQUOTE(JSON_SEARCH(json, 'one', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')), '.name', '.resources'), + JSON_ARRAY('apiCollection', 'apiEndpoint', 'chart', 'container', 'dashboard', 'dashboardDataModel', + 'database', 'databaseSchema', 'directory', 'file', 'llmModel', 'mcpServer', 'metric', 'mlmodel', + 'pipeline', 'query', 'report', 'searchIndex', 'spreadsheet', 'storedProcedure', 'table', 'topic', + 'worksheet'), + REPLACE(JSON_UNQUOTE(JSON_SEARCH(json, 'one', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')), '.name', '.description'), + 'Allow anyone to set the owner of an unowned data asset discovered from a source system.') +WHERE CAST(name AS BINARY) = 'OrganizationPolicy' + AND JSON_LENGTH(JSON_SEARCH(json, 'all', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')) = 1 + AND JSON_EXTRACT(json, REPLACE(JSON_UNQUOTE(JSON_SEARCH(json, 'one', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')), '.name', '.effect')) = 'allow' + AND JSON_EXTRACT(json, REPLACE(JSON_UNQUOTE(JSON_SEARCH(json, 'one', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')), '.name', '.condition')) = 'noOwner()' + AND JSON_EXTRACT(json, REPLACE(JSON_UNQUOTE(JSON_SEARCH(json, 'one', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')), '.name', '.operations')) = JSON_ARRAY('EditOwners') + AND LOWER(CAST(JSON_EXTRACT(json, REPLACE(JSON_UNQUOTE(JSON_SEARCH(json, 'one', 'OrganizationPolicy-NoOwner-Rule', NULL, '$.rules[*].name')), '.name', '.resources')) AS CHAR)) = '["all"]'; diff --git a/bootstrap/sql/migrations/native/2.1.2/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.2/postgres/postDataMigrationSQLScript.sql index ad06e994d586..cd1a9d20a02f 100644 --- a/bootstrap/sql/migrations/native/2.1.2/postgres/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.1.2/postgres/postDataMigrationSQLScript.sql @@ -21,3 +21,30 @@ WHERE name IN ( 'UsageBotRole') AND (COALESCE(json ->> 'provider', '') <> 'system' OR COALESCE(json ->> 'allowDelete', '') <> 'false'); + +-- OrganizationPolicy-NoOwner-Rule names the data asset types anyone may claim when they have no +-- owner. Applied only where the policy has one rule of that name and it is still the shipped one; +-- every other rule is left as stored. ADR:2026-12-02-only-data-assets-can-be-claimed-by-default +UPDATE policy_entity +SET json = jsonb_set(json, '{rules}', ( + SELECT jsonb_agg( + CASE WHEN existing.rule->>'name' = 'OrganizationPolicy-NoOwner-Rule' + AND existing.rule->>'effect' = 'allow' + AND existing.rule->>'condition' = 'noOwner()' + AND existing.rule->'operations' = '["EditOwners"]'::jsonb + AND lower((existing.rule->'resources')::text) = '["all"]' + THEN existing.rule || jsonb_build_object( + 'resources', '["apiCollection", "apiEndpoint", "chart", "container", "dashboard", "dashboardDataModel", "database", "databaseSchema", "directory", "file", "llmModel", "mcpServer", "metric", "mlmodel", "pipeline", "query", "report", "searchIndex", "spreadsheet", "storedProcedure", "table", "topic", "worksheet"]'::jsonb, + 'description', 'Allow anyone to set the owner of an unowned data asset discovered from a source system.') + ELSE existing.rule END + ORDER BY existing.position) + FROM jsonb_array_elements(json->'rules') WITH ORDINALITY AS existing(rule, position))) +WHERE name = 'OrganizationPolicy' + AND (SELECT count(*) = 1 + AND bool_and(r.rule->>'effect' = 'allow' + AND r.rule->>'condition' = 'noOwner()' + AND r.rule->'operations' = '["EditOwners"]'::jsonb + AND lower((r.rule->'resources')::text) = '["all"]') + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(json->'rules') = 'array' THEN json->'rules' END) AS r(rule) + WHERE r.rule->>'name' = 'OrganizationPolicy-NoOwner-Rule'); diff --git a/docs/decisions/2026-12-02-only-data-assets-can-be-claimed-by-default.md b/docs/decisions/2026-12-02-only-data-assets-can-be-claimed-by-default.md new file mode 100644 index 000000000000..e3dc215c4207 --- /dev/null +++ b/docs/decisions/2026-12-02-only-data-assets-can-be-claimed-by-default.md @@ -0,0 +1,43 @@ +# Only data assets can be claimed by default + +- **Status:** Accepted +- **Revisions:** v1 2026-12-02 (initial) +- **Deciders:** AdriĆ  Manero +- **Guard:** `OrganizationPolicyDefaultsTest`, `OrganizationPolicyClaimSqlMigrationTest`, + `OrganizationPolicyDefaultsIT` +- **Related:** ADR:2026-11-03-seeded-policies-are-not-reset-on-startup + +## Context +The Organization Policy applies to every user. `OrganizationPolicy-NoOwner-Rule` lets anyone set +the owner of an item that has no owner, so that data nobody looks after gets an owner. Data +discovered from source systems arrives with no owner; other items get one when they are created, +or from admins and Data Stewards. + +## Decision +- `OrganizationPolicy-NoOwner-Rule` keeps its name, effect, operation (`EditOwners`) and condition + (`noOwner()`), and its `resources` name the data assets discovered from a source system: + `apiCollection`, `apiEndpoint`, `chart`, `container`, `dashboard`, `dashboardDataModel`, + `database`, `databaseSchema`, `directory`, `file`, `llmModel`, `mcpServer`, `metric`, `mlmodel`, + `pipeline`, `query`, `report`, `searchIndex`, `spreadsheet`, `storedProcedure`, `table`, `topic`, + `worksheet`. +- The list lives in the rule, where admins see and change it. The permission engine has no notion + of a data asset, and no deny rule backs the list, so roles an admin grants are not overridden. +- Ingestion pipelines live in a service but are OpenMetadata's own setup, so they are not named. + Governance types (glossaries, domains, test cases and the like) are not named either: admins and + Data Stewards assign their owners. +- An upgrade applies the list through one statement in the post data migration of each line's + next patch release (`2.1.2`, and `2.0.11` on the 2.0 line), with the same text on every line. + It changes only that rule's `resources` and `description`, and only in the policy named exactly + `OrganizationPolicy` whose single rule of that name is still the shipped one: `allow`, + `EditOwners`, `noOwner()`, on `all` in any case. Any other rule is left as stored, and a second + run matches nothing. + +## Consequences +- Users with the default roles claim the listed types as before. Admins and Data Stewards set the + owner of other items. Owners set before the upgrade stay. +- A claim rule an admin changed is not migrated: it keeps whatever it names. Admins learn of the + change from the release notes, which say the rule now lists the data asset types and ask admins + who changed it to review its resources. The upgrade logs no warning. +- A new data asset type can be claimed once it is added to the seed and, for upgraded + installations, to a migration statement guarded the same way. `OrganizationPolicyDefaultsTest` + fails when a type with owners and a service is neither listed nor named as an exception. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrganizationPolicyDefaultsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrganizationPolicyDefaultsIT.java new file mode 100644 index 000000000000..17ca88809326 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/OrganizationPolicyDefaultsIT.java @@ -0,0 +1,517 @@ +/* + * 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; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.URI; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +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.function.Executable; +import org.openmetadata.it.auth.JwtAuthProvider; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.DatabaseServiceTestFactory; +import org.openmetadata.it.factories.GlossaryTestFactory; +import org.openmetadata.it.factories.TableTestFactory; +import org.openmetadata.it.factories.UserTestFactory; +import org.openmetadata.it.tests.mcp.McpTestBase; +import org.openmetadata.it.tests.mcp.McpTestUtils; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.api.ai.CreateMcpServer; +import org.openmetadata.schema.api.data.CreateMetric; +import org.openmetadata.schema.api.domains.CreateDomain; +import org.openmetadata.schema.api.domains.CreateDomain.DomainType; +import org.openmetadata.schema.api.events.CreateEventSubscription; +import org.openmetadata.schema.api.policies.CreatePolicy; +import org.openmetadata.schema.api.services.CreateMcpService; +import org.openmetadata.schema.api.services.ingestionPipelines.CreateIngestionPipeline; +import org.openmetadata.schema.api.tasks.CreateTask; +import org.openmetadata.schema.api.tasks.ResolveTask; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.entity.ai.McpServer; +import org.openmetadata.schema.entity.ai.McpServerType; +import org.openmetadata.schema.entity.ai.McpTransportType; +import org.openmetadata.schema.entity.data.Glossary; +import org.openmetadata.schema.entity.data.Metric; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.domains.Domain; +import org.openmetadata.schema.entity.events.AlertType; +import org.openmetadata.schema.entity.events.EventSubscription; +import org.openmetadata.schema.entity.events.SubscriptionDestination; +import org.openmetadata.schema.entity.policies.Policy; +import org.openmetadata.schema.entity.policies.accessControl.Rule; +import org.openmetadata.schema.entity.services.DatabaseService; +import org.openmetadata.schema.entity.services.ingestionPipelines.AirflowConfig; +import org.openmetadata.schema.entity.services.ingestionPipelines.IngestionPipeline; +import org.openmetadata.schema.entity.services.ingestionPipelines.PipelineType; +import org.openmetadata.schema.entity.tasks.Task; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.metadataIngestion.DatabaseServiceMetadataPipeline; +import org.openmetadata.schema.metadataIngestion.SourceConfig; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.OwnershipUpdatePayload; +import org.openmetadata.schema.type.Permission; +import org.openmetadata.schema.type.ResourceDescriptor; +import org.openmetadata.schema.type.ResourcePermission; +import org.openmetadata.schema.type.TaskCategory; +import org.openmetadata.schema.type.TaskEntityType; +import org.openmetadata.schema.type.TaskResolutionType; +import org.openmetadata.schema.type.Webhook; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.schema.utils.ResultList; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.network.HttpClient; +import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.network.RequestOptions; +import org.openmetadata.service.Entity; + +/** + * The default Organization Policy lets anyone set the owner of an unowned data asset discovered + * from a source system, and of nothing else; admins and Data Stewards assign the owners of other + * items. ADR:2026-12-02-only-data-assets-can-be-claimed-by-default + */ +@ExtendWith(TestNamespaceExtension.class) +class OrganizationPolicyDefaultsIT extends McpTestBase { + private static final RequestOptions JSON_PATCH = + RequestOptions.builder().header("Content-Type", "application/json-patch+json").build(); + private static final String MCP_SERVICE = "organization-policy-defaults-mcp"; + private static final String CLAIM_RULE = "OrganizationPolicy-NoOwner-Rule"; + private static final String DENIED = "Authorization error"; + + /** Types patch_entity hands to their own REST PATCH API before checking the caller. */ + private static final Set OWN_PATCH_API = + Set.of(Entity.TEAM, Entity.EVENT_SUBSCRIPTION, Entity.APPLICATION, Entity.INGESTION_PIPELINE); + + /** An item the claim is tried on: its REST path, and the entity type and FQN MCP addresses. */ + private record Item(String entityType, String path, String fqn) {} + + @BeforeAll + static void setUp() throws Exception { + initAuth(); + admin() + .executeForString( + HttpMethod.PUT, + "/v1/services/mcpServices", + new CreateMcpService() + .withName(MCP_SERVICE) + .withServiceType(CreateMcpService.McpServiceType.Mcp), + RequestOptions.builder().build()); + } + + @Test + void aUserWithNoRoleClaimsUnownedDataAssets(TestNamespace ns) { + final User user = UserTestFactory.createUser(ns, "assetClaimer"); + for (Item item : dataAssets(ns)) { + assertUnowned(item); + setOwner(clientFor(user), item.path(), user); + assertEquals(List.of(user.getId()), ownerIds(item), item.path()); + } + } + + @Test + void aUserWithNoRoleCannotClaimOtherUnownedItems(TestNamespace ns) { + final User user = UserTestFactory.createUser(ns, "itemClaimer"); + for (Item item : otherItems(ns)) { + assertUnowned(item); + assertEquals(403, statusOf(() -> setOwner(clientFor(user), item.path(), user)), item.path()); + assertUnowned(item); + } + } + + @Test + void theMcpPatchToolGivesTheSameResults(TestNamespace ns) throws Exception { + final User user = UserTestFactory.createUser(ns, "mcpClaimer"); + for (Item item : dataAssets(ns)) { + final JsonNode result = mcpSetOwner(user, item); + assertFalse(result.path("isError").asBoolean(), item.path() + ": " + result); + assertEquals(List.of(user.getId()), ownerIds(item), item.path()); + } + for (Item item : patchedByTheMcpTool(otherItems(ns))) { + final JsonNode result = mcpSetOwner(user, item); + assertTrue(result.path("isError").asBoolean(), item.path() + ": " + result); + assertTrue(result.toString().contains(DENIED), item.path() + ": " + result); + assertUnowned(item); + } + } + + @Test + void anOwnershipTaskTheUserResolvesGivesTheSameResults(TestNamespace ns) { + final User user = UserTestFactory.createUser(ns, "taskResolver"); + final Item table = item(Entity.TABLE, "/v1/tables/", table(ns)); + approveOwnershipTask(ns, user, table); + assertEquals(List.of(user.getId()), ownerIds(table)); + + for (Item item : + List.of(organizationPolicy(), item(Entity.GLOSSARY, "/v1/glossaries/", glossary(ns)))) { + final Task task = ownershipTask(ns, user, item); + assertEquals( + 403, statusOf(() -> resolve(clientFor(user), task, TaskResolutionType.Approved))); + assertUnowned(item); + resolve(admin(), task, TaskResolutionType.Rejected); + } + } + + @Test + void permissionsShowWhereTheUserMaySetAnOwner(TestNamespace ns) { + final User user = UserTestFactory.createUser(ns, "permissionReader"); + final Table table = table(ns); + + assertEquals( + Permission.Access.ALLOW, editOwners(user, "/v1/permissions/table/" + table.getId())); + assertEquals( + Permission.Access.NOT_ALLOW, + editOwners(user, "/v1/permissions/policy/name/OrganizationPolicy")); + // A policy this test made, so the answer does not depend on who owns the seeded one. + assertEquals( + Permission.Access.NOT_ALLOW, + editOwners(user, "/v1/permissions/policy/" + policy(ns).getId())); + } + + @Test + void everyClaimableTypeIsARegisteredResourceWithEditOwners() { + final Rule claimRule = + SdkClients.adminClient().policies().getByName("OrganizationPolicy").getRules().stream() + .filter(rule -> CLAIM_RULE.equals(rule.getName())) + .findFirst() + .orElseThrow(); + final Set withEditOwners = new TreeSet<>(); + for (ResourceDescriptor descriptor : + admin() + .execute(HttpMethod.GET, "/v1/policies/resources", null, ResourceDescriptorList.class) + .getData()) { + if (descriptor.getOperations().contains(MetadataOperation.EDIT_OWNERS)) { + withEditOwners.add(descriptor.getName()); + } + } + final Set missing = new TreeSet<>(claimRule.getResources()); + missing.removeAll(withEditOwners); + assertEquals(Set.of(), missing); + } + + @Test + void adminsAndDataStewardsAssignOwners(TestNamespace ns) { + final User owner = UserTestFactory.createUser(ns, "assignedOwner"); + final Item glossary = item(Entity.GLOSSARY, "/v1/glossaries/", glossary(ns)); + final Item policy = item(Entity.POLICY, "/v1/policies/", policy(ns)); + final Item stewardGlossary = item(Entity.GLOSSARY, "/v1/glossaries/", glossary(ns)); + setOwner(admin(), glossary.path(), owner); + setOwner(admin(), policy.path(), owner); + setOwner(dataSteward(ns), stewardGlossary.path(), owner); + for (Item item : List.of(glossary, policy, stewardGlossary)) { + assertEquals(List.of(owner.getId()), ownerIds(item), item.path()); + } + } + + @Test + void anOwnerKeepsEditingWhatTheyOwn(TestNamespace ns) { + final User owner = UserTestFactory.createUser(ns, "existingOwner"); + final Item glossary = item(Entity.GLOSSARY, "/v1/glossaries/", glossary(ns)); + final Item table = item(Entity.TABLE, "/v1/tables/", table(ns)); + for (Item item : List.of(glossary, table)) { + setOwner(admin(), item.path(), owner); + final String describe = + JsonUtils.pojoToJson( + List.of(Map.of("op", "add", "path", "/description", "value", "Kept by its owner"))); + clientFor(owner).executeForString(HttpMethod.PATCH, item.path(), describe, JSON_PATCH); + } + } + + // ---------------------------------------------------------------- items + + private static List dataAssets(final TestNamespace ns) { + return List.of( + item(Entity.TABLE, "/v1/tables/", table(ns)), + item(Entity.METRIC, "/v1/metrics/", metric(ns)), + item(Entity.MCP_SERVER, "/v1/mcpServers/", mcpServer(ns))); + } + + private static List otherItems(final TestNamespace ns) { + final DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + return List.of( + organizationPolicy(), + seeded(Entity.TEAM, "/v1/teams/", "Organization"), + seeded(Entity.EVENT_SUBSCRIPTION, "/v1/events/subscriptions/", "ActivityFeedAlert"), + item(Entity.EVENT_SUBSCRIPTION, "/v1/events/subscriptions/", alert(ns)), + seeded(Entity.APPLICATION, "/v1/apps/", "SearchIndexingApplication"), + seeded( + Entity.WORKFLOW_DEFINITION, + "/v1/governance/workflowDefinitions/", + "GlossaryTermApprovalWorkflow"), + item(Entity.GLOSSARY, "/v1/glossaries/", glossary(ns)), + item(Entity.DOMAIN, "/v1/domains/", domain(ns)), + item(Entity.DATABASE_SERVICE, "/v1/services/databaseServices/", service), + item( + Entity.INGESTION_PIPELINE, + "/v1/services/ingestionPipelines/", + ingestionPipeline(ns, service))); + } + + private static Item organizationPolicy() { + return seeded(Entity.POLICY, "/v1/policies/", "OrganizationPolicy"); + } + + private static Item item(final String entityType, final String collection, final Object entity) { + final JsonNode node = JsonUtils.valueToTree(entity); + return new Item( + entityType, collection + node.get("id").asText(), node.get("fullyQualifiedName").asText()); + } + + /** An item the server seeds, found by name. */ + private static Item seeded(final String entityType, final String collection, final String name) { + final JsonNode node = + JsonUtils.readTree( + admin().executeForString(HttpMethod.GET, collection + "name/" + name, null)); + return new Item( + entityType, collection + node.get("id").asText(), node.get("fullyQualifiedName").asText()); + } + + private static Table table(final TestNamespace ns) { + final DatabaseService service = DatabaseServiceTestFactory.createPostgres(ns); + return TableTestFactory.createSimple( + ns, DatabaseSchemaTestFactory.createSimple(ns, service).getFullyQualifiedName()); + } + + private static Metric metric(final TestNamespace ns) { + return SdkClients.adminClient() + .metrics() + .create( + new CreateMetric() + .withName(ns.prefix("metric" + shortId())) + .withDescription("A metric nobody owns")); + } + + private static McpServer mcpServer(final TestNamespace ns) { + final CreateMcpServer create = + new CreateMcpServer() + .withName(ns.prefix("mcpServer" + shortId())) + .withService(MCP_SERVICE) + .withServerType(McpServerType.DataAccess) + .withTransportType(McpTransportType.Stdio); + return admin().execute(HttpMethod.POST, "/v1/mcpServers", create, McpServer.class); + } + + private static Glossary glossary(final TestNamespace ns) { + return GlossaryTestFactory.createWithName(ns, "glossary" + shortId()); + } + + private static Domain domain(final TestNamespace ns) { + return SdkClients.adminClient() + .domains() + .create( + new CreateDomain() + .withName(ns.prefix("domain" + shortId())) + .withDomainType(DomainType.AGGREGATE) + .withDescription("A domain nobody owns")); + } + + private static EventSubscription alert(final TestNamespace ns) { + final SubscriptionDestination webhook = + new SubscriptionDestination() + .withId(UUID.randomUUID()) + .withType(SubscriptionDestination.SubscriptionType.WEBHOOK) + .withCategory(SubscriptionDestination.SubscriptionCategory.EXTERNAL) + .withConfig( + new Webhook() + .withEndpoint(URI.create("http://localhost:8585/api/v1/test/webhook/test"))); + return SdkClients.adminClient() + .eventSubscriptions() + .create( + new CreateEventSubscription() + .withName(ns.prefix("alert" + shortId())) + .withDescription("An alert an admin created") + .withAlertType(AlertType.NOTIFICATION) + .withResources(List.of("all")) + .withEnabled(false) + .withDestinations(List.of(webhook))); + } + + private static IngestionPipeline ingestionPipeline( + final TestNamespace ns, final DatabaseService service) { + return SdkClients.adminClient() + .ingestionPipelines() + .create( + new CreateIngestionPipeline() + .withName(ns.prefix("ingestion" + shortId())) + .withPipelineType(PipelineType.METADATA) + .withService(service.getEntityReference()) + .withSourceConfig( + new SourceConfig().withConfig(new DatabaseServiceMetadataPipeline())) + .withAirflowConfig(new AirflowConfig().withStartDate(new Date()))); + } + + private static Policy policy(final TestNamespace ns) { + final Rule rule = + new Rule() + .withName("viewTables") + .withEffect(Rule.Effect.ALLOW) + .withResources(List.of(Entity.TABLE)) + .withOperations(List.of(MetadataOperation.VIEW_BASIC)); + return ns.trackRoot( + Entity.POLICY, + admin() + .execute( + HttpMethod.POST, + "/v1/policies", + new CreatePolicy() + .withName(ns.prefix("policy" + shortId())) + .withRules(List.of(rule)), + Policy.class)); + } + + // ---------------------------------------------------------------- ways to write + + private static void setOwner(final HttpClient client, final String path, final User owner) { + final Map reference = Map.of("id", owner.getId().toString(), "type", "user"); + final String patch = + JsonUtils.pojoToJson( + List.of(Map.of("op", "add", "path", "/owners", "value", List.of(reference)))); + client.executeForString(HttpMethod.PATCH, path, patch, JSON_PATCH); + } + + /** The items patch_entity patches itself; the REST test covers the others. */ + private static List patchedByTheMcpTool(final List items) { + return items.stream().filter(item -> !OWN_PATCH_API.contains(item.entityType())).toList(); + } + + private JsonNode mcpSetOwner(final User user, final Item item) throws Exception { + final Map reference = new LinkedHashMap<>(); + reference.put("id", user.getId().toString()); + reference.put("type", "user"); + final String patch = + JsonUtils.pojoToJson( + List.of(Map.of("op", "add", "path", "/owners", "value", List.of(reference)))); + final String token = + "Bearer " + + JwtAuthProvider.tokenFor(user.getEmail(), user.getEmail(), new String[] {}, 3600); + return executeMcpRequest( + McpTestUtils.createPatchEntityToolCall(item.entityType(), item.fqn(), patch), token) + .path("result"); + } + + private static void approveOwnershipTask( + final TestNamespace ns, final User user, final Item item) { + resolve(clientFor(user), ownershipTask(ns, user, item), TaskResolutionType.Approved); + } + + /** An admin files a task asking to make {@code user} the owner, and assigns it to them. */ + private static Task ownershipTask(final TestNamespace ns, final User user, final Item item) { + final CreateTask create = + new CreateTask() + .withName(ns.prefix("ownership" + shortId())) + .withDescription("Set the owner") + .withCategory(TaskCategory.MetadataUpdate) + .withType(TaskEntityType.OwnershipUpdate) + .withAbout(TaskResourceIT.entityLink(item.entityType(), item.fqn())) + .withAssignees(List.of(user.getFullyQualifiedName())) + .withPayload( + new OwnershipUpdatePayload() + .withCurrentOwners(List.of()) + .withNewOwners(List.of(user.getEntityReference())) + .withReason("Set the owner")); + final Task task = SdkClients.adminClient().tasks().create(create); + TaskResourceIT.awaitTaskReadyForWorkflowResolution(task.getId()); + return task; + } + + private static void resolve( + final HttpClient client, final Task task, final TaskResolutionType resolution) { + client.execute( + HttpMethod.POST, + "/v1/tasks/" + task.getId() + "/resolve", + new ResolveTask().withResolutionType(resolution).withComment(resolution.value()), + Task.class); + } + + // ---------------------------------------------------------------- reading back + + private static void assertUnowned(final Item item) { + assertEquals(List.of(), ownerIds(item), item.path() + " must start unowned"); + } + + private static List ownerIds(final Item item) { + final JsonNode owners = + JsonUtils.readTree( + admin() + .executeForString( + HttpMethod.GET, + item.path(), + null, + RequestOptions.builder().queryParam("fields", "owners").build())) + .path("owners"); + return JsonUtils.convertValue(owners, EntityReferenceList.class).stream() + .map(EntityReference::getId) + .toList(); + } + + private static Permission.Access editOwners(final User user, final String path) { + final ResourcePermission permission = + clientFor(user).execute(HttpMethod.GET, path, null, ResourcePermission.class); + return permission.getPermissions().stream() + .filter(p -> p.getOperation() == MetadataOperation.EDIT_OWNERS) + .map(Permission::getAccess) + .findFirst() + .orElseThrow(); + } + + private static int statusOf(final Executable request) { + return assertThrows(OpenMetadataException.class, request).getStatusCode(); + } + + // ---------------------------------------------------------------- callers + + /** A user of its own with the seeded DataSteward role. */ + private static HttpClient dataSteward(final TestNamespace ns) { + final String name = "steward_" + shortId(); + final CreateUser create = + new CreateUser() + .withName(name) + .withEmail(name + "@test.om.org") + .withRoles(List.of(SdkClients.adminClient().roles().getByName("DataSteward").getId())); + final User steward = ns.trackRoot(Entity.USER, SdkClients.adminClient().users().create(create)); + return clientFor(steward); + } + + private static HttpClient clientFor(final User user) { + return SdkClients.createClient(user.getName(), user.getEmail(), new String[] {}) + .getHttpClient(); + } + + private static HttpClient admin() { + return SdkClients.adminClient().getHttpClient(); + } + + private static String shortId() { + return UUID.randomUUID().toString().substring(0, 8); + } + + static class ResourceDescriptorList extends ResultList {} + + static class EntityReferenceList extends ArrayList {} +} diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java index f9134f41325a..373078b278e0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TaskResourceIT.java @@ -140,7 +140,7 @@ public class TaskResourceIT extends BaseEntityIT { private static final String REQUESTED_DESCRIPTION = "Description requested by the creator"; - private static String entityLink(String entityType, String entityFqn) { + static String entityLink(String entityType, String entityFqn) { return String.format("<#E::%s::%s>", entityType, entityFqn); } @@ -5834,7 +5834,7 @@ private static void awaitOneAuditedUpdateBy( assertEquals(1, entries.size(), "audit log entries of " + entityFqn + ": " + entries); } - private void awaitTaskReadyForWorkflowResolution(UUID taskId) { + static void awaitTaskReadyForWorkflowResolution(UUID taskId) { Awaitility.await("task workflow materialization for " + taskId) .atMost(Duration.ofSeconds(20)) .pollInterval(Duration.ofMillis(250)) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/WorkflowTriggerPermissionsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/WorkflowTriggerPermissionsIT.java index 32305ddaf6ec..f7c058b4582e 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/WorkflowTriggerPermissionsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/WorkflowTriggerPermissionsIT.java @@ -201,7 +201,7 @@ void test_triggerTestConnection_dataConsumer_withoutServiceName_returns403(TestN @EnumSource(WorkflowUpdateMethod.class) void test_editTestConnection_cannotRetargetStoredSecrets( WorkflowUpdateMethod method, TestNamespace ns) throws Exception { - final WorkflowEditFixture fixture = workflowClaimedByNonServiceOwner(ns, method); + final WorkflowEditFixture fixture = workflowOwnedByNonServiceOwner(ns, method); final CreateWorkflow edit = testConnectionRequest(fixture.workflow().getName(), fixture.ownedService().getName()) .withDescription("Retarget connection") @@ -244,7 +244,7 @@ void test_editTestConnection_cannotRetargetStoredSecrets( @EnumSource(WorkflowUpdateMethod.class) void test_editTestConnection_cannotBypassTriggerBySwitchingType( WorkflowUpdateMethod method, TestNamespace ns) throws Exception { - final WorkflowEditFixture fixture = workflowClaimedByNonServiceOwner(ns, method); + final WorkflowEditFixture fixture = workflowOwnedByNonServiceOwner(ns, method); final CreateWorkflow edit = queryRunnerRequest(fixture.workflow().getName(), SharedEntities.get().USER3_REF) .withDescription("Switch workflow type") @@ -268,7 +268,7 @@ private enum WorkflowUpdateMethod { private record WorkflowEditFixture( Workflow workflow, DatabaseService ownedService, OpenMetadataClient editor, String token) {} - private WorkflowEditFixture workflowClaimedByNonServiceOwner( + private WorkflowEditFixture workflowOwnedByNonServiceOwner( TestNamespace ns, WorkflowUpdateMethod method) throws Exception { final OpenMetadataClient admin = SdkClients.adminClient(); final EntityReference attacker = SharedEntities.get().USER3_REF; @@ -293,19 +293,20 @@ private WorkflowEditFixture workflowClaimedByNonServiceOwner( final String token = tokenFor(email, new String[] {}); assertEquals(403, triggerWorkflow(workflow.getId(), token).statusCode()); - final ArrayNode claim = JsonUtils.getObjectMapper().createArrayNode(); - claim + // An admin assigns the owner: a workflow cannot be claimed. + final ArrayNode assignOwner = JsonUtils.getObjectMapper().createArrayNode(); + assignOwner .addObject() .put("op", "add") .put("path", "/owners") .set("value", JsonUtils.valueToTree(List.of(attacker))); - final Workflow claimed = editor.workflows().patch(workflow.getId(), claim); + final Workflow owned = admin.workflows().patch(workflow.getId(), assignOwner); assertEquals( "*********", - JsonUtils.valueToTree(claimed.getRequest()) + JsonUtils.valueToTree(owned.getRequest()) .at("/connection/config/authType/password") .asText()); - return new WorkflowEditFixture(claimed, ownedService, editor, token); + return new WorkflowEditFixture(owned, ownedService, editor, token); } private Workflow editWorkflow( diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/AppEventSubscriptionRemovalIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/AppEventSubscriptionRemovalIT.java index 02a12360c41f..87a5abfbb3b6 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/AppEventSubscriptionRemovalIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/alerts/AppEventSubscriptionRemovalIT.java @@ -44,8 +44,8 @@ /** * An app's alerts come from its own code, never from its marketplace definition, and only the - * server records them on the app (ADR:2026-10-26-an-apps-alerts-come-from-its-code). A signed-up - * user can own an app and its definition, since neither has an owner, so whatever the app or its + * server records them on the app (ADR:2026-10-26-an-apps-alerts-come-from-its-code). An admin can + * make a signed-up user the owner of an app and its definition, so whatever the app or its * definition holds was theirs to decide. */ // Installs and deletes apps, which walks every app's scheduler job: isolated like AppsResourceIT. @@ -127,8 +127,8 @@ private static OwnedApp ownedApp(final TestNamespace ns, final String appName) { final User user = UserTestFactory.createUser(ns, "appOwner"); final HttpClient asOwner = SdkClients.createClient(user.getName(), user.getEmail(), new String[] {}).getHttpClient(); - claim(asOwner, "/v1/apps/marketplace/" + definition.getId(), user); - claim(asOwner, "/v1/apps/" + app.getId(), user); + assignOwner("/v1/apps/marketplace/" + definition.getId(), user); + assignOwner("/v1/apps/" + app.getId(), user); return new OwnedApp(app, definition, asOwner); } @@ -177,9 +177,10 @@ private static EventSubscription webhookAlert( return alert; } - private static void claim(final HttpClient client, final String path, final User user) { + /** An admin makes {@code user} the owner: apps and their definitions cannot be claimed. */ + private static void assignOwner(final String path, final User user) { final Map owner = Map.of("id", user.getId().toString(), "type", "user"); - patch(client, path, List.of(Map.of("op", "add", "path", "/owners", "value", List.of(owner)))); + patch(admin(), path, List.of(Map.of("op", "add", "path", "/owners", "value", List.of(owner)))); } private static List> plantedAlert(final String name, final String endpoint) { diff --git a/openmetadata-service/src/main/resources/json/data/policy/OrganizationPolicy.json b/openmetadata-service/src/main/resources/json/data/policy/OrganizationPolicy.json index 5036e370e015..971726d5ad2b 100644 --- a/openmetadata-service/src/main/resources/json/data/policy/OrganizationPolicy.json +++ b/openmetadata-service/src/main/resources/json/data/policy/OrganizationPolicy.json @@ -17,8 +17,13 @@ }, { "name": "OrganizationPolicy-NoOwner-Rule", - "description" : "Allow any one to set the owner of an entity that has no owner set.", - "resources" : ["all"], + "description" : "Allow anyone to set the owner of an unowned data asset discovered from a source system.", + "resources" : [ + "apiCollection", "apiEndpoint", "chart", "container", "dashboard", "dashboardDataModel", + "database", "databaseSchema", "directory", "file", "llmModel", "mcpServer", "metric", + "mlmodel", "pipeline", "query", "report", "searchIndex", "spreadsheet", "storedProcedure", + "table", "topic", "worksheet" + ], "operations": ["EditOwners"], "effect": "allow", "condition": "noOwner()" diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/migration/OrganizationPolicyClaimSqlMigrationTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/migration/OrganizationPolicyClaimSqlMigrationTest.java new file mode 100644 index 000000000000..93292a7e8817 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/migration/OrganizationPolicyClaimSqlMigrationTest.java @@ -0,0 +1,380 @@ +/* + * 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.service.migration; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.service.jdbi3.locator.ConnectionType; +import org.openmetadata.service.migration.utils.MigrationFile; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +/** + * Runs the shipped statement that gives {@code OrganizationPolicy-NoOwner-Rule} its list of data + * asset types, read from the post data migration with the runner's own parser, against stored + * policies on MySQL and PostgreSQL. A rule still reading as shipped gets the seed's resources and + * description and nothing else changes; every other shape is left as stored; a second run changes + * nothing. ADR:2026-12-02-only-data-assets-can-be-claimed-by-default + */ +@Testcontainers(disabledWithoutDocker = true) +class OrganizationPolicyClaimSqlMigrationTest { + private static final String VERSION = "2.1.2"; + private static final String PASSWORD = "claim-rule-test"; + private static final String DATABASE = "claim_rule_test"; + private static final String POLICY = "OrganizationPolicy"; + private static final String COPY = "OrganizationPolicyCopy"; + private static final String CLAIM_RULE = "OrganizationPolicy-NoOwner-Rule"; + private static final String SEED = "json/data/policy/OrganizationPolicy.json"; + private static final String MYSQL_DIALECT = "mysql"; + private static final String POSTGRES_DIALECT = "postgres"; + private static final JsonNodeFactory JSON = JsonNodeFactory.instance; + + @Container + static final GenericContainer MYSQL = + new GenericContainer<>(DockerImageName.parse("mysql:8.4.13")) + .withEnv("MYSQL_DATABASE", DATABASE) + .withEnv("MYSQL_ROOT_PASSWORD", PASSWORD) + .withExposedPorts(3306); + + @Container + static final GenericContainer POSTGRES = + new GenericContainer<>(DockerImageName.parse("postgres:15")) + .withEnv("POSTGRES_DB", DATABASE) + .withEnv("POSTGRES_PASSWORD", PASSWORD) + .withExposedPorts(5432); + + private record Shape(String description, String policyName, JsonNode rules, boolean narrowed) { + @Override + public String toString() { + return description; + } + } + + static Stream shapes() { + return Stream.of(MYSQL_DIALECT, POSTGRES_DIALECT) + .flatMap( + dialect -> Stream.concat(narrowed(), untouched()).map(s -> Arguments.of(dialect, s))); + } + + private static Stream narrowed() { + return Stream.of( + narrowed("seed form, seed order", rules(owner(), claim(), viewAll())), + narrowed("API form, sorted by name", rules(claimOn("All"), owner(), viewAll())), + narrowed("upper case", rules(owner(), claimOn("ALL"), viewAll())), + narrowed("mixed case, rule last", rules(owner(), viewAll(), claimOn("aLL"))), + narrowed("a deny rule between", rules(owner(), denyTables(), claim(), viewAll())), + narrowed("another rule edited", rules(viewAllOn("table"), claim())), + narrowed("only the claim rule", rules(claim())), + narrowed( + "description edited", rules(owner(), claimWith(r -> r.put("description", "Ours")))), + narrowed("description absent", rules(owner(), claimWith(r -> r.remove("description")))), + narrowed("an extra key on the rule", rules(claimWith(r -> r.put("note", "kept")))), + narrowed("a stray string next to the rule", rules(owner(), claim()).add("stray"))); + } + + private static Stream untouched() { + return Stream.of( + untouched( + "another condition", claimWith(r -> r.put("condition", "noOwner() && hasDomain()"))), + untouched("condition in other case", claimWith(r -> r.put("condition", "NoOwner()"))), + untouched( + "condition with a trailing space", claimWith(r -> r.put("condition", "noOwner() "))), + untouched("condition absent", claimWith(r -> r.remove("condition"))), + untouched("condition null", claimWith(r -> r.putNull("condition"))), + untouched("another resource", claimWith(r -> r.set("resources", strings("all", "table")))), + untouched("one named resource", claimWith(r -> r.set("resources", strings("table")))), + untouched("resource with a space", claimWith(r -> r.set("resources", strings("all ")))), + untouched("resources empty", claimWith(r -> r.set("resources", strings()))), + untouched("resources absent", claimWith(r -> r.remove("resources"))), + untouched("resources a string", claimWith(r -> r.put("resources", "all"))), + untouched("resources an object", claimWith(r -> r.set("resources", JSON.objectNode()))), + untouched( + "another operation", + claimWith(r -> r.set("operations", strings("EditOwners", "EditTags")))), + untouched( + "operation twice", + claimWith(r -> r.set("operations", strings("EditOwners", "EditOwners")))), + untouched("operation absent", claimWith(r -> r.remove("operations"))), + untouched("effect deny", claimWith(r -> r.put("effect", "deny"))), + untouched("effect in other case", claimWith(r -> r.put("effect", "Allow"))), + untouched("effect absent", claimWith(r -> r.remove("effect"))), + untouched("name in lower case", claimWith(r -> r.put("name", CLAIM_RULE.toLowerCase()))), + new Shape("rule missing", POLICY, rules(owner(), viewAll()), false), + new Shape("two rules of that name", POLICY, rules(claim(), owner(), claim()), false), + new Shape( + "two rules of that name, first customised", + POLICY, + rules(claimWith(r -> r.put("condition", "hasDomain()")), claim()), + false), + new Shape("rules empty", POLICY, rules(), false), + new Shape("rules absent", POLICY, null, false), + new Shape("rules null", POLICY, JSON.nullNode(), false), + new Shape("rules an object", POLICY, claim(), false), + new Shape("rules a string", POLICY, JSON.textNode("rules"), false), + new Shape("policy name in lower case", "organizationpolicy", rules(claim()), false), + new Shape("policy name in upper case", "ORGANIZATIONPOLICY", rules(claim()), false), + new Shape("policy name with a trailing space", POLICY + " ", rules(claim()), false), + new Shape("a copy of the policy", COPY, rules(owner(), claim(), viewAll()), false)); + } + + @ParameterizedTest(name = "{0}: {1}") + @MethodSource("shapes") + void narrowsOnlyAClaimRuleStillAsShipped(final String dialect, final Shape shape) { + try (Handle handle = open(dialect)) { + createPolicyTable(handle, dialect); + final JsonNode stored = insertPolicy(handle, dialect, shape.policyName(), shape.rules()); + final String statement = migrationStatement(dialect); + + final int firstRun = handle.execute(statement); + final JsonNode afterFirstRun = read(handle, dialect, stored); + final int secondRun = handle.execute(statement); + + assertEquals(shape.narrowed() ? 1 : 0, firstRun, "Rows changed by the first run"); + assertEquals(shape.narrowed() ? narrowedFrom(stored) : stored, afterFirstRun); + assertEquals(0, secondRun, "Rows changed by the second run"); + assertEquals(afterFirstRun, read(handle, dialect, stored)); + } + } + + /** The stored document with only the claim rule's resources and description taken from the seed. */ + private static JsonNode narrowedFrom(final JsonNode stored) { + final ObjectNode expected = stored.deepCopy(); + final JsonNode seedRule = seedClaimRule(); + for (JsonNode rule : expected.get("rules")) { + if (CLAIM_RULE.equals(rule.path("name").asText(null))) { + ((ObjectNode) rule).set("resources", seedRule.get("resources")); + ((ObjectNode) rule).set("description", seedRule.get("description")); + } + } + return expected; + } + + private static JsonNode seedClaimRule() { + try (InputStream seed = + OrganizationPolicyClaimSqlMigrationTest.class.getClassLoader().getResourceAsStream(SEED)) { + assertNotNull(seed, SEED + " is not on the classpath"); + for (JsonNode rule : + JsonUtils.readTree(new String(seed.readAllBytes(), StandardCharsets.UTF_8)) + .get("rules")) { + if (CLAIM_RULE.equals(rule.get("name").asText())) { + return rule; + } + } + throw new AssertionError(CLAIM_RULE + " is not seeded"); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static Shape narrowed(final String description, final ArrayNode rules) { + return new Shape(description, POLICY, rules, true); + } + + private static Shape untouched(final String description, final ObjectNode claimRule) { + return new Shape(description, POLICY, rules(owner(), claimRule, viewAll()), false); + } + + private static ArrayNode rules(final JsonNode... rules) { + final ArrayNode array = JSON.arrayNode(); + for (JsonNode rule : rules) { + array.add(rule); + } + return array; + } + + private static ArrayNode strings(final String... values) { + final ArrayNode array = JSON.arrayNode(); + for (String value : values) { + array.add(value); + } + return array; + } + + private static ObjectNode rule( + final String name, final String description, final String resource, final String operation) { + final ObjectNode rule = JSON.objectNode(); + rule.put("name", name); + rule.put("description", description); + rule.put("effect", "allow"); + rule.set("resources", strings(resource)); + rule.set("operations", strings(operation)); + return rule; + } + + /** The claim rule as releases before this change seed it. */ + private static ObjectNode claim() { + return claimOn("all"); + } + + private static ObjectNode claimOn(final String all) { + return rule( + CLAIM_RULE, + "Allow any one to set the owner of an entity that has no owner set.", + all, + "EditOwners") + .put("condition", "noOwner()"); + } + + private static ObjectNode claimWith(final Consumer change) { + final ObjectNode rule = claimOn("All"); + change.accept(rule); + return rule; + } + + private static ObjectNode owner() { + return rule( + "OrganizationPolicy-Owner-Rule", + "Allow all the operations on an entity for the owner.", + "all", + "All") + .put("condition", "isOwner()"); + } + + private static ObjectNode viewAll() { + return viewAllOn("all"); + } + + private static ObjectNode viewAllOn(final String resource) { + return rule( + "OrganizationPolicy-ViewAll-Rule", + "Allow all users to discover data assets.", + resource, + "ViewAll"); + } + + private static ObjectNode denyTables() { + return rule("OrganizationPolicy-DenyTables-Rule", "Deny deleting tables.", "table", "Delete") + .put("effect", "deny"); + } + + private static Handle open(final String dialect) { + return MYSQL_DIALECT.equals(dialect) + ? Jdbi.create( + "jdbc:mysql://%s:%d/%s?allowPublicKeyRetrieval=true&useSSL=false" + .formatted(MYSQL.getHost(), MYSQL.getMappedPort(3306), DATABASE), + "root", + PASSWORD) + .open() + : Jdbi.create( + "jdbc:postgresql://%s:%d/%s" + .formatted(POSTGRES.getHost(), POSTGRES.getMappedPort(5432), DATABASE), + "postgres", + PASSWORD) + .open(); + } + + private static void createPolicyTable(final Handle handle, final String dialect) { + handle.execute("DROP TABLE IF EXISTS policy_entity"); + handle.execute(POSTGRES_DIALECT.equals(dialect) ? POSTGRES_POLICY_TABLE : MYSQL_POLICY_TABLE); + } + + private static final String MYSQL_POLICY_TABLE = + """ + CREATE TABLE policy_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json ->> '$.id') STORED NOT NULL, + json JSON NOT NULL, + fqnHash VARCHAR(768) NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json ->> '$.name') NOT NULL, + PRIMARY KEY (id), + UNIQUE (fqnHash)) + """; + + private static final String POSTGRES_POLICY_TABLE = + """ + CREATE TABLE policy_entity ( + id VARCHAR(36) GENERATED ALWAYS AS (json ->> 'id') STORED NOT NULL, + json JSONB NOT NULL, + fqnHash VARCHAR(768) NOT NULL, + name VARCHAR(256) GENERATED ALWAYS AS (json ->> 'name') STORED NOT NULL, + PRIMARY KEY (id), + UNIQUE (fqnHash)) + """; + + private static JsonNode insertPolicy( + final Handle handle, final String dialect, final String name, final JsonNode rules) { + final ObjectNode policy = JSON.objectNode(); + policy.put("id", UUID.randomUUID().toString()); + policy.put("name", name); + policy.put("fullyQualifiedName", name); + policy.put("provider", "system"); + if (rules != null) { + policy.set("rules", rules); + } + final String value = POSTGRES_DIALECT.equals(dialect) ? "CAST(:json AS JSONB)" : ":json"; + handle + .createUpdate("INSERT INTO policy_entity (json, fqnHash) VALUES (" + value + ", :fqnHash)") + .bind("json", JsonUtils.pojoToJson(policy)) + .bind("fqnHash", UUID.randomUUID().toString()) + .execute(); + return policy; + } + + private static JsonNode read(final Handle handle, final String dialect, final JsonNode policy) { + final String text = + POSTGRES_DIALECT.equals(dialect) ? "CAST(json AS TEXT)" : "CAST(json AS CHAR)"; + final String json = + handle + .createQuery("SELECT " + text + " FROM policy_entity WHERE id = :id") + .bind("id", policy.get("id").asText()) + .mapTo(String.class) + .one(); + return JsonUtils.readTree(json); + } + + /** Parsed with the runner's own splitter from the shipped file, so it is what an upgrade runs. */ + private static String migrationStatement(final String dialect) { + final ConnectionType connectionType = + MYSQL_DIALECT.equals(dialect) ? ConnectionType.MYSQL : ConnectionType.POSTGRES; + final List statements = + MigrationFile.parseSQLFile(migrationFile(dialect).toFile(), connectionType).stream() + .filter(sql -> sql.contains(CLAIM_RULE)) + .toList(); + assertEquals(1, statements.size(), "Expected one statement for " + CLAIM_RULE); + return statements.get(0); + } + + private static Path migrationFile(final String dialect) { + Path current = Path.of("").toAbsolutePath(); + while (current != null && !Files.isDirectory(current.resolve("bootstrap/sql/migrations"))) { + current = current.getParent(); + } + assertNotNull(current, "Could not find the repository root"); + return current.resolve( + "bootstrap/sql/migrations/native/%s/%s/postDataMigrationSQLScript.sql" + .formatted(VERSION, dialect)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/security/policyevaluator/OrganizationPolicyDefaultsTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/security/policyevaluator/OrganizationPolicyDefaultsTest.java new file mode 100644 index 000000000000..050761b8d54b --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/security/policyevaluator/OrganizationPolicyDefaultsTest.java @@ -0,0 +1,283 @@ +/* + * 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.service.security.policyevaluator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.MissingNode; +import io.github.classgraph.ClassGraph; +import io.github.classgraph.Resource; +import io.github.classgraph.ScanResult; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.openmetadata.schema.entity.policies.Policy; +import org.openmetadata.schema.entity.policies.accessControl.Rule; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.utils.JsonUtils; + +/** + * Keeps the seeded claim rule in step with the entity types: it names the data assets discovered + * from a source system, a new type that lives in a service fails here until it is listed or named + * an exception, and no listed type holds access or credentials. + * ADR:2026-12-02-only-data-assets-can-be-claimed-by-default + */ +class OrganizationPolicyDefaultsTest { + private static final String SEED = "json/data/policy/OrganizationPolicy.json"; + private static final String SCHEMA_ROOT = "json/schema/"; + private static final String ENTITY_ROOT = SCHEMA_ROOT + "entity/"; + private static final String ENTITY_INTERFACE = "org.openmetadata.schema.EntityInterface"; + private static final String CLAIM_RULE = "OrganizationPolicy-NoOwner-Rule"; + + private static final List DATA_ASSETS = + List.of( + "apiCollection", + "apiEndpoint", + "chart", + "container", + "dashboard", + "dashboardDataModel", + "database", + "databaseSchema", + "directory", + "file", + "llmModel", + "mcpServer", + "metric", + "mlmodel", + "pipeline", + "query", + "report", + "searchIndex", + "spreadsheet", + "storedProcedure", + "table", + "topic", + "worksheet"); + + /** Types that live in a service but are not data discovered from the source system. */ + private static final Map NOT_CLAIMABLE = + Map.of("ingestionPipeline", "OpenMetadata's own job that reads from the service"); + + /** Fields that hold access or credentials: an item carrying one is not claimable. */ + private static final List ACCESS_FIELDS = + List.of( + "rules", + "policies", + "roles", + "defaultRoles", + "connection", + "authenticationMechanism", + "destinations", + "appConfiguration", + "privateConfiguration", + "sourceConfig", + "connectionConfig"); + + /** A listed type described by its own connection settings, which every read masks. */ + private static final Map ACCESS_FIELD_ALLOWED = + Map.of("mcpServer", "connectionConfig"); + + private static Map schemas; + private static Map entities; + private static Map entityPaths; + private static Rule claimRule; + + @BeforeAll + static void load() { + schemas = new TreeMap<>(); + try (ScanResult scan = new ClassGraph().acceptPaths(SCHEMA_ROOT).scan()) { + for (Resource resource : scan.getResourcesWithExtension("json")) { + schemas.put(resource.getPath(), read(resource)); + } + } + entities = new TreeMap<>(); + entityPaths = new TreeMap<>(); + schemas.forEach( + (path, schema) -> { + if (path.startsWith(ENTITY_ROOT) + && schema.path("javaInterfaces").toString().contains(ENTITY_INTERFACE)) { + assertNull(entities.put(typeOf(path), schema), "Two schemas for " + path); + entityPaths.put(typeOf(path), path); + } + }); + assertTrue(entities.size() > 50, "Expected the entity schemas on the classpath"); + claimRule = seededClaimRule(); + } + + @Test + void theClaimRuleNamesTheDataAssets() { + assertEquals(DATA_ASSETS, claimRule.getResources()); + assertEquals(Rule.Effect.ALLOW, claimRule.getEffect()); + assertEquals(List.of(MetadataOperation.EDIT_OWNERS), claimRule.getOperations()); + assertEquals("noOwner()", claimRule.getCondition()); + } + + @Test + void everyDataAssetIsAnEntityWithOwners() { + Set invalid = new TreeSet<>(); + for (String type : DATA_ASSETS) { + JsonNode schema = entities.get(type); + if (schema == null || !hasProperty(schema, "owners")) { + invalid.add(type); + } + } + assertEquals(Set.of(), invalid, "Listed types must be entity types with owners"); + } + + @Test + void everyOwnedTypeInAServiceIsListedOrNamedNotClaimable() { + Set undecided = new TreeSet<>(); + entities.forEach( + (type, schema) -> { + if (hasProperty(schema, "owners") + && hasProperty(schema, "service") + && !DATA_ASSETS.contains(type) + && !NOT_CLAIMABLE.containsKey(type)) { + undecided.add(type); + } + }); + assertEquals( + Set.of(), + undecided, + "Add each type to " + + CLAIM_RULE + + " in OrganizationPolicy.json and a migration, or to NOT_CLAIMABLE with a reason"); + } + + @Test + void noDataAssetHoldsAccessOrCredentials() { + ACCESS_FIELD_ALLOWED.forEach( + (type, field) -> + assertTrue( + hasProperty(entities.get(type), field), + type + " no longer has " + field + ": drop its exception")); + Map found = new TreeMap<>(); + for (String type : DATA_ASSETS) { + JsonNode schema = entities.getOrDefault(type, MissingNode.getInstance()); + ACCESS_FIELDS.stream() + .filter(field -> hasProperty(schema, field)) + .filter(field -> !field.equals(ACCESS_FIELD_ALLOWED.get(type))) + .forEach(field -> found.put(type, field)); + if (holdsPassword(schema, entityPaths.get(type))) { + found.put(type, "a password field"); + } + } + assertEquals(Map.of(), found, "A claimable type must not hold access or credentials"); + } + + /** Whether the schema, or any definition it refers to, has a field in the password format. */ + private static boolean holdsPassword(final JsonNode schema, final String path) { + Deque> pending = new ArrayDeque<>(); + Set visited = new HashSet<>(); + pending.push(Map.entry(path, schema)); + while (!pending.isEmpty()) { + Map.Entry next = pending.pop(); + JsonNode node = next.getValue(); + if ("password".equals(node.path("format").asText())) { + return true; + } + String ref = node.path("$ref").asText(""); + if (!ref.isEmpty() && visited.add(fileOf(next.getKey(), ref) + fragmentOf(ref))) { + pushReferenced(pending, fileOf(next.getKey(), ref), fragmentOf(ref)); + } + node.forEach(child -> pending.push(Map.entry(next.getKey(), child))); + } + return false; + } + + /** Queues the node a {@code $ref} points to: the fragment of the file, not the whole file. */ + private static void pushReferenced( + final Deque> pending, final String file, final String fragment) { + JsonNode node = schemas.get(file); + if (node == null) { + return; + } + for (String segment : fragment.split("/")) { + node = segment.isEmpty() ? node : node.path(segment); + } + if (!node.isMissingNode()) { + pending.push(Map.entry(file, node)); + } + } + + private static String fragmentOf(final String ref) { + return ref.contains("#") ? ref.substring(ref.indexOf('#') + 1) : ""; + } + + /** The classpath path of the file a {@code $ref} points to: the referring file for a local ref. */ + private static String fileOf(final String base, final String ref) { + String file = ref.contains("#") ? ref.substring(0, ref.indexOf('#')) : ref; + if (file.isEmpty()) { + return base; + } + Deque segments = new ArrayDeque<>(List.of(base.split("/"))); + segments.pollLast(); + for (String segment : file.split("/")) { + if ("..".equals(segment)) { + segments.pollLast(); + } else if (!".".equals(segment) && !segment.isEmpty()) { + segments.addLast(segment); + } + } + return String.join("/", segments); + } + + private static boolean hasProperty(final JsonNode schema, final String property) { + return schema.path("properties").has(property); + } + + private static String typeOf(final String path) { + return path.substring(path.lastIndexOf('/') + 1, path.length() - ".json".length()); + } + + private static JsonNode read(final Resource resource) { + try { + return JsonUtils.readTree(resource.getContentAsString()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private static Rule seededClaimRule() { + try (InputStream stream = + OrganizationPolicyDefaultsTest.class.getClassLoader().getResourceAsStream(SEED)) { + assertNotNull(stream, SEED + " is not on the classpath"); + Policy policy = + JsonUtils.readValue( + new String(stream.readAllBytes(), StandardCharsets.UTF_8), Policy.class); + return policy.getRules().stream() + .filter(rule -> CLAIM_RULE.equals(rule.getName())) + .findFirst() + .orElseThrow(() -> new AssertionError(CLAIM_RULE + " is missing from " + SEED)); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } +} diff --git a/openmetadata-ui/src/main/resources/ui/playwright/constant/permission.ts b/openmetadata-ui/src/main/resources/ui/playwright/constant/permission.ts index 5d1840ccea0c..4736bee18056 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/constant/permission.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/constant/permission.ts @@ -183,10 +183,34 @@ export const ORGANIZATION_POLICY_RULES: PolicyRulesType[] = [ { name: 'OrganizationPolicy-NoOwner-Rule', description: - 'Allow any one to set the owner of an entity that has no owner set.', + 'Allow anyone to set the owner of an unowned data asset discovered from a source system.', effect: 'allow', operations: ['EditOwners'], - resources: ['All'], + resources: [ + 'apiCollection', + 'apiEndpoint', + 'chart', + 'container', + 'dashboard', + 'dashboardDataModel', + 'database', + 'databaseSchema', + 'directory', + 'file', + 'llmModel', + 'mcpServer', + 'metric', + 'mlmodel', + 'pipeline', + 'query', + 'report', + 'searchIndex', + 'spreadsheet', + 'storedProcedure', + 'table', + 'topic', + 'worksheet', + ], condition: 'noOwner()', }, { diff --git a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Features/ContextCenterPermission.spec.ts b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Features/ContextCenterPermission.spec.ts index 50c6a6052a74..05016a02221c 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Features/ContextCenterPermission.spec.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Features/ContextCenterPermission.spec.ts @@ -211,8 +211,7 @@ test.describe('Context Center Permissions', () => { browser ); - // An article with no owner lets anyone set one (OrganizationPolicy-NoOwner-Rule), - // so own it to check that a user without EditOwners cannot change its owners. + // Own the article to check that a user without EditOwners cannot change its owners. const admin = await getLoggedInUser(apiContext); articleEntity = new KnowledgeCenterClass( { diff --git a/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/RightPanelPageObject.ts b/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/RightPanelPageObject.ts index b4d4ef32bc8a..1399cc8b4b5d 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/RightPanelPageObject.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/RightPanelPageObject.ts @@ -507,9 +507,9 @@ export class RightPanelPageObject { if (this.rolePermissions.canEditOwners) { await expect(this.panelEditOwners).toBeVisible(); } else { - // In OpenMetadata, if an entity has no owner, any user can claim it. - // Therefore, the edit-owners button will be visible even if the user - // lacks EditOwners permission, provided the entity is ownerless. + // Any user can claim a data asset that has no owner. Therefore, the + // edit-owners button will be visible even if the user lacks EditOwners + // permission, provided the data asset is ownerless. if (!isOwnerless) { await expect(this.panelEditOwners).not.toBeVisible(); } diff --git a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Teams.spec.ts b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Teams.spec.ts index f5b1b23bb2dd..15e756637c4b 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Teams.spec.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Teams.spec.ts @@ -1200,7 +1200,8 @@ test.describe('Teams Page with Data Consumer User', () => { dataConsumerPage.getByTestId('edit-team-name') ).not.toBeVisible(); await expect(dataConsumerPage.getByTestId('add-domain')).not.toBeVisible(); - await expect(dataConsumerPage.getByTestId('edit-owner')).toBeVisible(); + // Only data assets can be claimed, so an unowned team offers no owner edit. + await expect(dataConsumerPage.getByTestId('edit-owner')).not.toBeVisible(); await expect(dataConsumerPage.getByTestId('edit-email')).not.toBeVisible(); await expect( dataConsumerPage.getByTestId('edit-team-subscription') @@ -1377,7 +1378,8 @@ test.describe('Teams Page action as Owner of Team', () => { await waitForAllLoadersToDisappear(ownerUserPage); - await expect(ownerUserPage.getByTestId('edit-owner')).toBeVisible(); + // Only data assets can be claimed, so an unowned team offers no owner edit. + await expect(ownerUserPage.getByTestId('edit-owner')).not.toBeVisible(); await expect(ownerUserPage.getByTestId('manage-button')).not.toBeVisible();