Skip to content

fix: keep user credentials out of change events and version history - #36237

Closed
manerow wants to merge 6 commits into
mainfrom
fix/qr7d-mask-user-secrets
Closed

manerow wants to merge 6 commits into
mainfrom
fix/qr7d-mask-user-secrets

Conversation

@manerow

@manerow manerow commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Describe your changes:

A user's authenticationMechanism holds their password hash, or a bot's token. It was copied into places other users can read:

  • Change events. Every alert sends the event's entity to its destination, and GET /v1/events returns it; an admin's PUT /v1/users on a bot stores its decrypted JWT.
  • Version history. GET /v1/users/{id}/versions, /versions/{v} and /v1/users/history return old versions as stored, to anyone who may view a user.

authenticationMechanism was not marked "mask": true, and some writers skipped masking altogether (for example UserUtil, at every startup).

This PR:

  • Marks authenticationMechanism with "mask": true inside its definition in user.json. Beside a $ref the generator ignores it.
  • Masks every change event in one place, ChangeEventDAO.insert and insertBatch, through the new ChangeEventMasking. The raw SQL methods are renamed insertMaskedRow(s). Callers do not change.
  • Version history leaves out every field the schema marks secret as a whole (today only authenticationMechanism), when stored and on every read, older rows included. A field that only holds secrets inside, such as a service connection, stays; its resource masks them per caller. MaskedFields reads the schema flag for events and history alike.
  • When one user's edits in a session are merged, the previous version is read back with the current hidden fields, so the merged change does not report a credential change.

Stored users are unchanged, so logins and bot tokens work.

Migration (2.0.7)

Plain SQL in the 2.0.7 postDataMigrationSQLScript.sql, with fixed names, removes authenticationMechanism from stored user change events, the audit log, alert delivery records and user versions. SQL in 2.0.7 also runs on a database already at a 2.1.0 build, which skips 2.0.7 Java steps. No Java involved.

Type of change:

  • Bug fix

Tests:

Unit tests

  • ChangeEventMaskingTest: a bot's token leaves an event, whether its entity is an object or a string.
  • MaskedFieldsTest: users hide their credentials as a whole; services keep their connection.

Backend integration tests

  • UserSecretsIT:
    • a bot update is stored without the token (GET /v1/events);
    • a non-admin user reads the bot's versions, latest version and history and sees no token;
    • two quick edits to the bot do not report a credential change.
  • All three fail on main and pass here, on MySQL and Postgres.

Also checked by upgrading a real 2.0.6 database (MySQL and Postgres) through migrate: the same result as the earlier Java version, row for row; a second run changes nothing; a database already at 2.1.0 is cleaned too. Logins and bot tokens still work.

Ingestion integration tests

  • Not applicable.

Playwright (UI) tests

  • Not applicable.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • I have commented on my code, particularly in hard-to-understand areas.
  • I have added tests (unit / integration) and listed them above.
  • I have added a test that covers the exact scenario we are fixing.

RetriggerView in GreptileConfidence Score: 4/5

The upgrade cleanup is addressed, but the two outstanding test requirements must be satisfied before merging.

Findings

  1. P2 Tests share the same bot ▶
  2. P2 Field name bypasses required convention ▶

Summary

The PR keeps user credentials out of new change events and user version history.

  • Change events no longer store schema-marked secret fields.
  • User version history leaves whole secret fields out of every version.

Reviews (5) · Last reviewed commit: "fix: run the user secrets cleanup as pla..." · Reviewed by Greptile

@manerow
manerow requested a review from a team as a code owner October 26, 2026 10:33
@manerow
manerow requested a review from pmbrull October 26, 2026 10:33
@manerow manerow added safe to test Add this label to run secure Github workflows on PRs backend labels Oct 26, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.


private static User updateBot(TestNamespace ns) {
HttpClient admin = SdkClients.adminClient().getHttpClient();
User bot = admin.execute(HttpMethod.GET, "/v1/users/name/" + BOT, null, User.class);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Tests share the same bot

Both tests update the shared ingestion-bot, while integration tests run concurrently. storedEventOf selects an event using only that bot's ID, so it can check the other test's update instead of its own. The Java guide requires TestNamespace to isolate test data. Create a separate bot for each test and use its ID throughout. This requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Comment on lines +40 to +54
int versions = handle.createUpdate(removeFromVersionsSql(connectionType)).execute();
LOG.info("Removed {} from {} user versions", AUTH_MECHANISM_FIELD, versions);
}

private static String removeFromVersionsSql(ConnectionType connectionType) {
return switch (connectionType) {
case MYSQL -> "UPDATE entity_extension"
+ " SET json = JSON_REMOVE(json, '$.authenticationMechanism')"
+ " WHERE extension LIKE 'user.version.%'"
+ " AND JSON_CONTAINS_PATH(json, 'one', '$.authenticationMechanism')";
case POSTGRES -> "UPDATE entity_extension SET json = json - 'authenticationMechanism'"
+ " WHERE extension LIKE 'user.version.%'"
+ " AND json -> 'authenticationMechanism' IS NOT NULL";
};
}

@gitar-bot gitar-bot Bot Oct 26, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Quality: Version cleanup is one unbatched UPDATE over all of entity_extension

removeFromVersionsSql runs a single UPDATE entity_extension ... WHERE extension LIKE 'user.version.%' statement. The primary key is (id, extension), so a LIKE on the second column cannot use the index. The statement scans the version and extension rows of every entity type in the tenant.

This contradicts the Accepted record ADR:2026-10-09-data-migration-backfills-walk-ids-in-batches. That record requires a backfill on a table not bounded by an indexed predicate to walk keyset pages of 500 ids that commit separately. It exists because a whole-table statement on a roughly 115k-table tenant was killed by the database on every attempt. Under runOnce, the same kill would block the 2.1.0 upgrade.

Fix: walk the ids of user entities in pages (for example with IdBatches.fold over user_entity ids), add id IN (<ids>) to the UPDATE, and keep the JSON_CONTAINS_PATH / IS NOT NULL predicate so the step can resume. The alternative is a record that supersedes the ADR.

Restrict each UPDATE to a page of user ids, using the existing IdBatches helper (adapt to its signature).:

case MYSQL -> "UPDATE entity_extension"
    + " SET json = JSON_REMOVE(json, '$.authenticationMechanism')"
    + " WHERE id IN (<ids>) AND extension LIKE 'user.version.%'"
    + " AND JSON_CONTAINS_PATH(json, 'one', '$.authenticationMechanism')";
case POSTGRES -> "UPDATE entity_extension SET json = json - 'authenticationMechanism'"
    + " WHERE id IN (<ids>) AND extension LIKE 'user.version.%'"
    + " AND json -> 'authenticationMechanism' IS NOT NULL";

Was this helpful? React with 👍 / 👎

.flatMap(List::stream)
.map(FieldChange::getName)
.toList();
assertTrue(changed.contains("description"), "The merged change must hold the edits");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Field name bypasses required convention

The new assertion uses changed.contains("description"), but the Java guide forbids raw string literals in .contains() calls. Use a named constant for the field. This repository requirement must be satisfied before merging.

Context Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@gitar-bot

gitar-bot Bot commented Oct 26, 2026

Copy link
Copy Markdown
Code Review ⚠️ Changes requested 2 closed / 3 findings

🔴 High risk · Central masking and historical cleanup alter credential exposure in events and versions; a defect could disclose bot tokens or password hashes.

Keeps user credentials out of change events and version history by masking authenticationMechanism and hiding it from stored versions, with a 2.0.7 migration to clean existing data. Changes requested: the version cleanup in UserSecretsHistoryRemoval runs as one unbatched UPDATE over all of entity_extension, which contradicts the accepted batching ADR and risks being killed on large tenants during the upgrade.

  • removeFromVersionsSql in UserSecretsHistoryRemoval.java should walk user entity ids in keyset pages and commit each page separately, with id IN (...) added to the UPDATE
  • Alternatively, a new decision record must supersede the batching ADR
⚠️ Quality: Version cleanup is one unbatched UPDATE over all of entity_extension

📄 openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/UserSecretsHistoryRemoval.java:40-54

removeFromVersionsSql runs a single UPDATE entity_extension ... WHERE extension LIKE 'user.version.%' statement. The primary key is (id, extension), so a LIKE on the second column cannot use the index. The statement scans the version and extension rows of every entity type in the tenant.

This contradicts the Accepted record ADR:2026-10-09-data-migration-backfills-walk-ids-in-batches. That record requires a backfill on a table not bounded by an indexed predicate to walk keyset pages of 500 ids that commit separately. It exists because a whole-table statement on a roughly 115k-table tenant was killed by the database on every attempt. Under runOnce, the same kill would block the 2.1.0 upgrade.

Fix: walk the ids of user entities in pages (for example with IdBatches.fold over user_entity ids), add id IN (<ids>) to the UPDATE, and keep the JSON_CONTAINS_PATH / IS NOT NULL predicate so the step can resume. The alternative is a record that supersedes the ADR.

Restrict each UPDATE to a page of user ids, using the existing IdBatches helper (adapt to its signature).
case MYSQL -> "UPDATE entity_extension"
    + " SET json = JSON_REMOVE(json, '$.authenticationMechanism')"
    + " WHERE id IN (<ids>) AND extension LIKE 'user.version.%'"
    + " AND JSON_CONTAINS_PATH(json, 'one', '$.authenticationMechanism')";
case POSTGRES -> "UPDATE entity_extension SET json = json - 'authenticationMechanism'"
    + " WHERE id IN (<ids>) AND extension LIKE 'user.version.%'"
    + " AND json -> 'authenticationMechanism' IS NOT NULL";
✅ 2 closed
✅ Bug: Consolidated user edits now record a spurious authenticationMechanism add

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:6453-6467 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/UserRepository.java:347-351
After this change, versions are stored without authenticationMechanism (serializeForVersionHistory). EntityUpdater.revert() still rebuilds previous from that version JSON (getPreviousVersion, EntityRepository.java:12500-12511) and sets original = previous. In the final consolidation pass, UserUpdater.updateAuthenticationMechanism therefore sees a null original and a non-null updated value, and calls recordChange("authenticationMechanism", null, "new-encrypted-value").

The effect: when the same updater edits a basic-auth user or a bot twice inside the session window, the consolidated version and its change event list a field that never changed. An edit that nets to zero can no longer collapse to no change. Before this PR, the previous version still carried the mechanism, so this did not happen.

Fix: when rebuilding the previous version, copy the hidden fields back in from original.

✅ Quality: No record states the masking rules for change events and version history

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/AccessControlDAOs.java:1161-1175 📄 openmetadata-service/src/main/java/org/openmetadata/service/events/ChangeEventMasking.java:36-50 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:6457-6463 📄 openmetadata-spec/src/main/resources/json/schema/entity/teams/user.json:18
This PR sets rules that every future writer and repository has to follow, and nothing in docs/decisions/ states them. The only nearby record, 2026-10-20-mcp-responses-mask-stored-credentials, covers MCP responses only.

The rules come from the description:

  • "Masking is applied in ChangeEventDAO.insert and insertBatch, so every writer is covered ... raw SQL methods are renamed insertMaskedRow(s) to avoid accidental use"
  • "Hidden fields are left out when a version is stored and on every read of versions and history, including older rows"
  • "authenticationMechanism is marked "mask": true on its definition ... because the generator ignores the flag beside a $ref"

There is also a contract change: a stored user change event's entity is now always a masked JSON string, not an object.

A record would say: "Every change event is stored through ChangeEventDAO.insert/insertBatch, which drops each field its entity schema marks mask: true and stores the entity as a JSON string. A repository's getFieldsHiddenFromHistory() fields are neither stored in nor returned from any version or history read. mask on a $ref'd type goes on its definition." Without it, a new credential-bearing entity or a direct insertMaskedRow caller has no rule to follow.

🤖 Prompt for agents
Code Review: Keeps user credentials out of change events and version history by masking `authenticationMechanism` and hiding it from stored versions, with a 2.0.7 migration to clean existing data. Changes requested: the version cleanup in `UserSecretsHistoryRemoval` runs as one unbatched UPDATE over all of `entity_extension`, which contradicts the accepted batching ADR and risks being killed on large tenants during the upgrade.
  
  - `removeFromVersionsSql` in `UserSecretsHistoryRemoval.java` should walk user entity ids in keyset pages and commit each page separately, with `id IN (...)` added to the UPDATE
  - Alternatively, a new decision record must supersede the batching ADR

1. ⚠️ Quality: Version cleanup is one unbatched UPDATE over all of entity_extension
   Files: openmetadata-service/src/main/java/org/openmetadata/service/migration/utils/v210/UserSecretsHistoryRemoval.java:40-54

   `removeFromVersionsSql` runs a single `UPDATE entity_extension ... WHERE extension LIKE 'user.version.%'` statement. The primary key is `(id, extension)`, so a `LIKE` on the second column cannot use the index. The statement scans the version and extension rows of every entity type in the tenant.
   
   This contradicts the Accepted record [ADR:2026-10-09-data-migration-backfills-walk-ids-in-batches](docs/decisions/2026-10-09-data-migration-backfills-walk-ids-in-batches.md). That record requires a backfill on a table not bounded by an indexed predicate to walk keyset pages of 500 ids that commit separately. It exists because a whole-table statement on a roughly 115k-table tenant was killed by the database on every attempt. Under `runOnce`, the same kill would block the 2.1.0 upgrade.
   
   Fix: walk the ids of user entities in pages (for example with `IdBatches.fold` over `user_entity` ids), add `id IN (<ids>)` to the UPDATE, and keep the `JSON_CONTAINS_PATH` / `IS NOT NULL` predicate so the step can resume. The alternative is a record that supersedes the ADR.

   Fix (Restrict each UPDATE to a page of user ids, using the existing IdBatches helper (adapt to its signature).):
   case MYSQL -> "UPDATE entity_extension"
       + " SET json = JSON_REMOVE(json, '$.authenticationMechanism')"
       + " WHERE id IN (<ids>) AND extension LIKE 'user.version.%'"
       + " AND JSON_CONTAINS_PATH(json, 'one', '$.authenticationMechanism')";
   case POSTGRES -> "UPDATE entity_extension SET json = json - 'authenticationMechanism'"
       + " WHERE id IN (<ids>) AND extension LIKE 'user.version.%'"
       + " AND json -> 'authenticationMechanism' IS NOT NULL";

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

@manerow

manerow commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

Replaced by PR #36251, which combines this change with its companion fix in one PR.

@manerow manerow closed this Oct 26, 2026
@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant