From 9a13cfba497c57621ee2362bd920cf5b7fcf66a1 Mon Sep 17 00:00:00 2001 From: harshsoni2024 Date: Tue, 8 Sep 2026 16:56:57 +0530 Subject: [PATCH 1/2] fix(service): stop the ingestion bot blanking a user-curated displayName On 1.13, EntityRepository.EntityUpdater.updateDisplayName() is a bare recordChange(). IngestionBotPolicy's DisplayName-Deny rule exists and is identical to main's, but never fires: a PUT authorizes with the coarse EDIT_ALL operation, which does not intersect a field-level deny. So an ingestion-bot PUT carrying displayName=null silently clears a displayName a user curated in the UI. This is most visible with Snowflake tag ingestion, where the sink writes tags via a plain per-entity PUT (write_classification_and_tag -> metadata.create_or_update) with no displayName in the CreateTag payload. The pipeline's overrideMetadata flag is unrelated and does not affect it - reproduced with the flag both true and false. main/2.0 are unaffected because of two commits that are not on 1.13: #28155 (f49e46438d1) introduced the guard along with the server-side EntityUpdater.overrideMetadata field, and #28676 (eac204ed830) made it policy-aware so the SCIM bot is not blocked. Neither cherry-picks cleanly: they reference overrideMetadata, which does not exist anywhere in 1.13's Java. Port the policy-aware guard by hand, keying displayName preservation on the updating bot actually being DENIED EditDisplayName. Bots the policy allows - notably SCIM, whose ScimBotPolicy has no DisplayName-Deny - still update it. One deliberate divergence from main: the condition keeps operation.isPut(). main can drop it because bulk overrideMetadata=true is its force-sync escape hatch; 1.13 has no such path. Its only escape hatch is the ingestion-side override_metadata PATCH built in topology_runner.create_patch_request, which puts displayName back into the payload via RESTRICT_UPDATE_LIST. Dropping isPut() here would make the server silently revert those PATCHes. Tests (BaseEntityIT, adapted from #28676 - the originals lean on putAs / hasField / invoke helpers that do not exist on 1.13, so those are added): test_singleEntityPut_ingestionBot_preservesUserDisplayName PUTs displayName=null as the ingestion bot, matching the tag-ingestion shape exactly; test_singleEntityPut_displayNameAllowedBot_updatesDisplayName provisions a bot with no DisplayName-Deny and asserts it can still update, guarding against re-breaking SCIM sync (#21879). Co-Authored-By: Claude Opus 5 (1M context) --- .../openmetadata/it/tests/BaseEntityIT.java | 214 ++++++++++++++++++ .../service/jdbi3/EntityRepository.java | 43 +++- 2 files changed, 256 insertions(+), 1 deletion(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java index 7b0d34b5c3f5..69a2300b02ad 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/BaseEntityIT.java @@ -25,6 +25,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.auth.JwtAuthProvider; import org.openmetadata.it.bootstrap.SharedEntities; import org.openmetadata.it.util.EntityValidation; import org.openmetadata.it.util.SdkClients; @@ -33,10 +34,21 @@ import org.openmetadata.it.util.UpdateType; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.domains.CreateDataProduct; +import org.openmetadata.schema.api.policies.CreatePolicy; +import org.openmetadata.schema.api.teams.CreateRole; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.auth.JWTAuthMechanism; +import org.openmetadata.schema.auth.JWTTokenExpiry; import org.openmetadata.schema.entity.domains.DataProduct; +import org.openmetadata.schema.entity.policies.Policy; +import org.openmetadata.schema.entity.policies.accessControl.Rule; +import org.openmetadata.schema.entity.teams.AuthenticationMechanism; +import org.openmetadata.schema.entity.teams.Role; +import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.type.ApiStatus; import org.openmetadata.schema.type.ChangeDescription; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.api.BulkOperationResult; import org.openmetadata.schema.type.api.BulkResponse; @@ -46,6 +58,9 @@ import org.openmetadata.sdk.exceptions.InvalidRequestException; import org.openmetadata.sdk.fluent.Users; import org.openmetadata.sdk.network.HttpMethod; +import org.openmetadata.sdk.services.policies.PolicyService; +import org.openmetadata.sdk.services.teams.RoleService; +import org.openmetadata.sdk.services.teams.UserService; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.EntityRepository; import org.openmetadata.service.util.TestUtils; @@ -4753,6 +4768,205 @@ protected List createBulkRequests(TestNamespace ns, String prefix, int count) return requests; } + /** + * Test: A bot whose policy DENIES {@code EditDisplayName} (the ingestion bot, via + * {@code IngestionBotPolicy}/{@code DefaultBotPolicy}) must NOT overwrite a user-curated + * {@code displayName} through a single-entity PUT. + * + *

A per-entity PUT authorizes with the coarse {@code EDIT_ALL} operation, which does not + * intersect the field-level {@code EditDisplayName} deny - so the bot reaches the repository, + * where {@code EntityRepository#updateDisplayName} re-applies that field-level deny and preserves + * the user value. This is the regression guard for tag ingestion blanking a curated displayName: + * the connector PUTs a CreateTag whose displayName is null. + */ + @Test + void test_singleEntityPut_ingestionBot_preservesUserDisplayName(TestNamespace ns) { + if (!supportsBulkAPI) return; + + K request = createRequest(ns.prefix("put_denydn_"), ns); + if (!hasSetter(request, "setDisplayName", String.class)) return; + T created = createEntity(request); + String fqn = created.getFullyQualifiedName(); + + String userDisplayName = "User Curated Display Name"; + T entity = getEntityByName(fqn); + entity.setDisplayName(userDisplayName); + patchEntity(entity.getId().toString(), entity); + + setFieldViaReflection(request, "setDisplayName", String.class, null); + HttpResponse response = putAs(request, getBotToken()); + assertTrue( + response.statusCode() == 200 || response.statusCode() == 201, + "Bot single-entity PUT should be authorized via EDIT_ALL: " + + response.statusCode() + + " " + + response.body()); + + T result = getEntityByName(fqn); + assertEquals( + userDisplayName, + result.getDisplayName(), + "Ingestion bot (EditDisplayName denied) must NOT blank a user displayName via PUT: " + fqn); + } + + /** + * Test: A bot whose policy does NOT deny {@code EditDisplayName} (modeling the SCIM bot, whose + * {@code ScimBotPolicy} carries no {@code DisplayName-Deny}) CAN still update {@code displayName} + * through a single-entity PUT. + * + *

Contrast with {@link #test_singleEntityPut_ingestionBot_preservesUserDisplayName}: the + * difference is purely the bot's policy, which is exactly what the in-code guard keys on. Without + * this, the guard would re-break SCIM displayName sync (#21879). + */ + @Test + void test_singleEntityPut_displayNameAllowedBot_updatesDisplayName(TestNamespace ns) { + if (!supportsBulkAPI) return; + + K request = createRequest(ns.prefix("put_allowdn_"), ns); + if (!hasSetter(request, "setDisplayName", String.class)) return; + T created = createEntity(request); + String fqn = created.getFullyQualifiedName(); + + String userDisplayName = "User Curated Display Name"; + T entity = getEntityByName(fqn); + entity.setDisplayName(userDisplayName); + patchEntity(entity.getId().toString(), entity); + + String botDisplayName = "SCIM-like Bot Display Name"; + setFieldViaReflection(request, "setDisplayName", String.class, botDisplayName); + HttpResponse response = putAs(request, displayNameAllowedBotToken()); + assertTrue( + response.statusCode() == 200 || response.statusCode() == 201, + "Allowed-bot single-entity PUT should succeed: " + + response.statusCode() + + " " + + response.body()); + + T result = getEntityByName(fqn); + assertEquals( + botDisplayName, + result.getDisplayName(), + "Bot allowed EditDisplayName (SCIM-like) must update displayName via PUT: " + fqn); + } + + /** Whether this entity's create request exposes {@code setterName}, so the test can skip. */ + private boolean hasSetter(K createRequest, String setterName, Class paramType) { + try { + createRequest.getClass().getMethod(setterName, paramType); + return true; + } catch (NoSuchMethodException e) { + return false; + } + } + + /** + * Single-entity createOrUpdate (PUT) over raw HTTP using the given bearer token. The SDK fluent + * clients always authenticate as admin, so the raw call is how a test drives a per-entity PUT as + * a specific bot identity. + */ + protected HttpResponse putAs(K request, String token) { + try { + String url = SdkClients.getServerUrl() + getResourcePath(); + if (url.endsWith("/")) { + url = url.substring(0, url.length() - 1); + } + java.net.http.HttpRequest httpRequest = + java.net.http.HttpRequest.newBuilder() + .uri(java.net.URI.create(url)) + .header("Authorization", "Bearer " + token) + .header("Content-Type", "application/json") + .PUT(java.net.http.HttpRequest.BodyPublishers.ofString(JsonUtils.pojoToJson(request))) + .build(); + return java.net.http.HttpClient.newHttpClient() + .send(httpRequest, HttpResponse.BodyHandlers.ofString()); + } catch (Exception e) { + throw new RuntimeException("Single-entity PUT failed: " + e.getMessage(), e); + } + } + + // Lazily provisioned (once per session) bot whose policy allows EditAll and does NOT deny + // EditDisplayName, modeling the SCIM bot. API-created bots are force-assigned DefaultBotRole + // (which denies EditDisplayName), so that role is stripped via a raw JSON-Patch after creation. + private static volatile String displayNameAllowedBotToken; + + protected static synchronized String displayNameAllowedBotToken() { + if (displayNameAllowedBotToken == null) { + displayNameAllowedBotToken = provisionDisplayNameAllowedBot(); + } + return displayNameAllowedBotToken; + } + + private static String provisionDisplayNameAllowedBot() { + try { + OpenMetadataClient admin = SdkClients.adminClient(); + String suffix = UUID.randomUUID().toString().substring(0, 8); + Policy policy = + new PolicyService(admin.getHttpClient()) + .create( + new CreatePolicy() + .withName("displayNameAllowedBotPolicy_" + suffix) + .withRules( + List.of( + new Rule() + .withName("AllowEditAll") + .withResources(List.of("All")) + .withOperations( + List.of( + MetadataOperation.EDIT_ALL, + MetadataOperation.VIEW_ALL, + MetadataOperation.CREATE)) + .withEffect(Rule.Effect.ALLOW)))); + Role role = + new RoleService(admin.getHttpClient()) + .create( + new CreateRole() + .withName("displayNameAllowedBotRole_" + suffix) + .withPolicies(List.of(policy.getName()))); + String email = "displayname-allowed-bot-" + suffix + "@open-metadata.org"; + User bot = + new UserService(admin.getHttpClient()) + .create( + new CreateUser() + .withName("displayname-allowed-bot-" + suffix) + .withEmail(email) + .withIsBot(true) + .withAuthenticationMechanism( + new AuthenticationMechanism() + .withAuthType(AuthenticationMechanism.AuthType.JWT) + .withConfig( + new JWTAuthMechanism() + .withJWTTokenExpiry(JWTTokenExpiry.Unlimited))) + .withRoles(List.of(role.getId()))); + stripDefaultBotRole(bot.getId().toString(), role.getId().toString()); + return JwtAuthProvider.tokenFor(email, email, new String[] {role.getName()}, 86400); + } catch (Exception e) { + throw new RuntimeException( + "Failed to provision displayName-allowed bot: " + e.getMessage(), e); + } + } + + // Replace the bot's roles (auto-assigned DefaultBotRole + the custom role) with ONLY the custom + // role via a raw JSON-Patch, so its effective policy no longer denies EditDisplayName. + private static void stripDefaultBotRole(String botId, String roleId) throws Exception { + String patch = + "[{\"op\":\"replace\",\"path\":\"/roles\",\"value\":[{\"id\":\"" + + roleId + + "\",\"type\":\"role\"}]}]"; + java.net.http.HttpRequest req = + java.net.http.HttpRequest.newBuilder() + .uri(java.net.URI.create(SdkClients.getServerUrl() + "/v1/users/" + botId)) + .header("Authorization", "Bearer " + SdkClients.getAdminToken()) + .header("Content-Type", "application/json-patch+json") + .method("PATCH", java.net.http.HttpRequest.BodyPublishers.ofString(patch)) + .build(); + HttpResponse resp = + java.net.http.HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString()); + if (resp.statusCode() != 200) { + throw new IllegalStateException( + "Failed to strip DefaultBotRole: " + resp.statusCode() + " " + resp.body()); + } + } + private String getBotToken() { return org.openmetadata.it.auth.JwtAuthProvider.tokenFor( "ingestion-bot@open-metadata.org", diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java index 6e631a36ff1c..3e8c489b1251 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java @@ -201,8 +201,11 @@ import org.openmetadata.schema.type.FieldChange; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.LifeCycle; +import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.Permission; import org.openmetadata.schema.type.ProviderType; import org.openmetadata.schema.type.Relationship; +import org.openmetadata.schema.type.ResourcePermission; import org.openmetadata.schema.type.SuggestionType; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.TagLabelMetadata; @@ -257,6 +260,7 @@ import org.openmetadata.service.search.SearchResultListMapper; import org.openmetadata.service.search.SearchSortFilter; import org.openmetadata.service.security.AuthorizationException; +import org.openmetadata.service.security.policyevaluator.PolicyEvaluator; import org.openmetadata.service.security.policyevaluator.SubjectContext; import org.openmetadata.service.util.EntityETag; import org.openmetadata.service.util.EntityFieldUtils; @@ -8579,7 +8583,23 @@ && isNullOrEmptyChangeDescription(changeDescription) } private void updateDisplayName() { - recordChange(FIELD_DISPLAY_NAME, original.getDisplayName(), updated.getDisplayName()); + // A bot whose policy denies EditDisplayName (e.g. the ingestion bot via DefaultBotPolicy / + // IngestionBotPolicy) must not clobber a user-curated displayName. A PUT authorizes with the + // coarse EDIT_ALL operation, which does not intersect that field-level deny, so re-apply it + // here. Bots the policy allows - for example the SCIM bot syncing identity attributes through + // the repository - fall through and update it. PATCH is left to the policy layer, so a + // deliberate force-sync (the ingestion override_metadata PATCH) still gets through. + boolean preserveUserDisplayName = + operation.isPut() + && updatedByBot() + && !nullOrEmpty(original.getDisplayName()) + && !Objects.equals(original.getDisplayName(), updated.getDisplayName()) + && updatingBotDeniedOperation(MetadataOperation.EDIT_DISPLAY_NAME); + if (preserveUserDisplayName) { + updated.setDisplayName(original.getDisplayName()); + } else { + recordChange(FIELD_DISPLAY_NAME, original.getDisplayName(), updated.getDisplayName()); + } } private void updateEntityStatus(boolean consolidatingChanges) { @@ -9784,6 +9804,27 @@ public final boolean updatedByBot() { return Boolean.TRUE.equals(updatingUser.getIsBot()); } + /** + * Whether the bot performing this update is denied {@code operation} by policy. A PUT + * authorizes with the coarse EDIT_ALL operation, which does not intersect a field-level deny + * (e.g. DisplayName-Deny on the ingestion bot), so callers re-apply the field-level check here. + * Returns false for users the policy does not explicitly deny (including the SCIM bot). + */ + private boolean updatingBotDeniedOperation(MetadataOperation operation) { + boolean denied = false; + if (updatingUser != null) { + SubjectContext subjectContext = SubjectContext.getSubjectContext(updatingUser.getName()); + ResourcePermission permission = PolicyEvaluator.getPermission(subjectContext, entityType); + denied = + permission.getPermissions().stream() + .anyMatch( + p -> + operation.equals(p.getOperation()) + && Permission.Access.DENY.equals(p.getAccess())); + } + return denied; + } + @VisibleForTesting public static void setSessionTimeout(long timeout) { sessionTimeoutMillis = timeout; From 5af4e8b6bc20747f62f9a64fd98246f90b9c74c9 Mon Sep 17 00:00:00 2001 From: harshsoni2024 Date: Tue, 8 Sep 2026 17:05:55 +0530 Subject: [PATCH 2/2] refactor(service): rename shadowing parameter in updatingBotDeniedOperation Addresses review on #32955. The helper's parameter was named `operation`, shadowing EntityUpdater's own `operation` field - a PUT/PATCH `Operation`, not a `MetadataOperation`. The two appear five lines apart, since updateDisplayName() calls `operation.isPut()` on the field just above, so a reader scanning the helper can easily misread which one is in scope. Rename the parameter to `metadataOperation` and note in the javadoc why it is not called `operation`, so the name does not drift back. Behavior is unchanged: the lambda already bound to the parameter, as the innermost scope wins. Note this diverges by one identifier from upstream eac204ed830, which has the same shadowing on main. Co-Authored-By: Claude Opus 5 (1M context) --- .../org/openmetadata/service/jdbi3/EntityRepository.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java index 3e8c489b1251..36a064102dda 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java @@ -9805,12 +9805,15 @@ public final boolean updatedByBot() { } /** - * Whether the bot performing this update is denied {@code operation} by policy. A PUT + * Whether the bot performing this update is denied {@code metadataOperation} by policy. A PUT * authorizes with the coarse EDIT_ALL operation, which does not intersect a field-level deny * (e.g. DisplayName-Deny on the ingestion bot), so callers re-apply the field-level check here. * Returns false for users the policy does not explicitly deny (including the SCIM bot). + * + *

The parameter is deliberately not named {@code operation}: that would shadow this + * updater's own {@code operation} field, which holds the PUT/PATCH {@link Operation}. */ - private boolean updatingBotDeniedOperation(MetadataOperation operation) { + private boolean updatingBotDeniedOperation(MetadataOperation metadataOperation) { boolean denied = false; if (updatingUser != null) { SubjectContext subjectContext = SubjectContext.getSubjectContext(updatingUser.getName()); @@ -9819,7 +9822,7 @@ private boolean updatingBotDeniedOperation(MetadataOperation operation) { permission.getPermissions().stream() .anyMatch( p -> - operation.equals(p.getOperation()) + metadataOperation.equals(p.getOperation()) && Permission.Access.DENY.equals(p.getAccess())); } return denied;