Skip to content

Fixes #38241: Allocate a fresh secret id when another list element still references the default id - #38497

Open
iamkiayun wants to merge 11 commits into
open-metadata:mainfrom
iamkiayun:fix/38241-list-secret-reference-allocation
Open

iamkiayun wants to merge 11 commits into
open-metadata:mainfrom
iamkiayun:fix/38241-list-secret-reference-allocation

Conversation

@iamkiayun

@iamkiayun iamkiayun commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #38241

Summary

When a list element (such as an MCP server in McpConnection.servers) is renamed while its credential stays masked, or shifts position after an earlier position-keyed element is deleted, its stored secret: reference still points at its old id. Adding a new element under that old name or position previously overwrote (or, when cleared, deleted) the secret the renamed or shifted element still referenced.

Instead of reading or moving secrets in the vault, this fix decides whether a list element's secret id may be written or deleted strictly from the references held by the locked stored entity and the incoming request:

  • Reference-based allocation (SecretsManager): Before encrypting password fields on an external secrets manager, ReferenceScope collects every secret: reference in both the locked stored config and the incoming config, compared via canonicalSecretName (handling Azure case-insensitivity and AWS/SSM ARNs).
    • A plaintext write inside a collection reuses a fresh id already held by that exact slot, or writes to its default id, only when no other slot in the saved or incoming config references it.
    • Otherwise it allocates a fresh base32-suffixed id (<defaultId><sep><13-char base32>, with a compact hashed fallback under the entity root when a provider's max secret name length would be exceeded). Soft-deleted name conflicts (such as Azure Key Vault 409) also fall back to a fresh id.
    • Checking the locked stored config prevents a save that later fails in the database from overwriting a secret still referenced by the committed entity.
    • Clearing a list element's secret never deletes an id still referenced by another slot or a reference outside the element's own id.
    • Plaintext values are validated against the reserved "null" placeholder before any vault writes or deletes run.
  • Repository wiring (ServiceEntityRepository, IngestionPipelineRepository): Pass the row-locked stored entity already loaded in writeWithSecretOwnership to encryptServiceConnectionConfig / encryptIngestionPipeline across single, versioned, and bulk writes.
  • Ownership & cleanup (SecretMapOwnership, SecretsManager.SecretInventory): Record the actual secret id written for each plaintext slot (including fresh ids) and recognize fresh ids in storedSecretName, so hard delete removes every owned secret while leaving user-supplied external references untouched. SecretMapOwnership.clean also compares references by canonicalSecretName.
  • Decision record: Added v4 amendment and test guards to docs/decisions/2026-11-11-mcp-service-server-names-are-unique-and-masks-need-a-stored-value.md.

Verification

  • Unit tests (openmetadata-service): 592/592 passed (0 failures, 0 errors, 0 skipped), including:
    • SecretMapEntriesExternalStoreTest (31/31): rename + reuse (later save and same save in both element orders), rename back after a key change, swap names + edit one/both keys + clear one key, delete position-keyed element (unnamed & duplicate names, same save and later save) + fresh-id reuse + hard-delete cleanup.
    • ListSecretReferenceAllocationTest (10/10): failed DB save after swap/edit, failed batch updateMany, direct 4-arg call without original + deleteSecretsFromServiceConnectionConfig, Azure Key Vault (- separator, case-insensitivity, 409 soft-delete, 127-char max-length compact fallback), AWS ARN spelling, GCP _ separator, Kubernetes 253-char compact fallback, DB secrets manager, prepare/approval path, refused "null" pre-validation, clearing safety, and user-supplied external references.
    • Provider & repository suites: AWSSecretsManagerLocalStackTest (7/7), AWSSSMSecretsManagerLocalStackTest (6/6), AzureKVSecretsManagerTest (5/5), GCPSecretsManagerTest (14/14), KubernetesSecretsManagerTest (21/21), OwnedSecretsTest (32/32), ServiceEntitySecretsTest (18/18), PasswordEntityMaskerTest (40/40), IngestionPipelineRepositoryTest (83/83).
  • Integration tests (openmetadata-integration-tests, MySQL + Elasticsearch):
    • SecretsManagerNullSecretIT: 35/35 passed (including new end-to-end renamedMcpServerKeepsItsApiKeyWhenOldNameIsReusedAndSwapped).
    • McpServiceResourceIT: 170 ran, 0 failed (25 skipped by base-class flags).
    • SecretsManagerUpdateSoftDeletedIT: 1/1 passed.
  • Checks: mvn spotless:check, python3 scripts/harness/check_decision_records.py, and python3 .github/scripts/plan_local_java_tests.py --base upstream/main --check-branch all passed.

RetriggerView in GreptileConfidence Score: 4/5

Do not merge until fresh-ID reuse and clearing preserve user-managed secrets.

Findings

  1. P1 User-managed secrets can be changed ▶
  2. P2 Failed saves leave unused secrets ▶

Summary

The PR protects list credentials when names or positions are reused:

  • List credentials get separate secret IDs when an old ID is still in use.
  • Hard deletes clean up fresh secrets without deleting outside references.

Two gaps remain: suffixed user references can be mistaken for owned secrets, and failed saves leave newly allocated IDs outside cleanup.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Lock stored entity] --> B[Collect saved and incoming references]
  B --> C{Another slot uses the default ID?}
  C -->|Yes| D[Allocate fresh ID]
  C -->|No| E[Use default or saved fresh ID]
  D --> F[Write secret to vault]
  E --> F
  F --> G[Write entity to database]
  G --> H[Record actual owned IDs]
  H --> I[Commit and clean unused owned secrets]
Loading

Reviews (1) · Last reviewed commit: "Fixes #38241: Allocate a fresh secret id..." · Reviewed by Greptile


Summary by Gitar

  • Shared credential retention:
    • Keeps credentials referenced by other services, pipelines, or workflows until the last reference is released
    • Defers cleanup of retired workflow credentials to post-commit retry passes
  • Fresh secret staging:
    • Stages replacements for committed fresh list-secret ids and discards them on failed saves
    • Adds SharedSecretReferences and workflow ownership wiring for bulk and hard-delete paths
  • Rollback cleanup:
    • Deletes fresh secrets created inside a transaction that later rolls back

This will update automatically on new commits.

…st element still references the default id
@iamkiayun
iamkiayun requested a review from a team as a code owner November 23, 2026 13:51
@iamkiayun
iamkiayun requested a review from TeddyCr November 23, 2026 13:51
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

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

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.

Comment on lines +1355 to +1358
if (savedOwnRef != null
&& manager.isFreshIdFor(savedOwnRef, defaultSecretId, root)
&& !isReferencedByOther(savedOwnRef, defaultSecretId)) {
return savedOwnRef;

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.

P1 User-managed secrets can be changed

isFreshIdFor treats a name’s shape as proof that OpenMetadata created it. For example, save alpha.apiKey as a user-supplied reference to its default ID plus /abcdefghijklm. A later plaintext replacement reuses and overwrites that external secret; clearing the field deletes it. Neither path checks the recorded ownership, even though the original reference was never recorded as owned.

Require recorded ownership before reusing or deleting a suffixed reference.

Comment on lines +690 to +691
String targetId = scope.selectWriteSecretId(defaultSecretId);
String storedRef = storeWithFreshFallback(fieldName, targetId, defaultSecretId, value, scope);

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 Failed saves leave unused secrets

A fresh secret written before a failed database save is never tracked for cleanup. write.accept runs before recordWrite, and rollback only restores the entity in memory. Each retry allocates a new random suffix, so later saves cannot recover these IDs, and hard delete cannot find them. Failed saves can therefore leave credentials in the vault indefinitely, adding storage costs and manual cleanup.

Track newly created IDs outside the rolled-back ownership write, or remove them on failure without touching committed references.

Knowledge Base Used: Metadata entity lifecycle

@TeddyCr
TeddyCr requested review from manerow and mohityadav766 and removed request for TeddyCr November 25, 2026 22:21

@pmbrull pmbrull left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for tracking down the secret ID collision.

  • 🔴 Stage replacements for committed fresh IDs. A later edit can reuse a slot’s fresh ID and overwrite its vault value before the entity save commits. If the save fails, the committed config still points to that ID with the changed value. The rollback hook only cleans up newly allocated IDs. Write the replacement under a new ID and retire the prior ID after commit when it has no remaining references. Add a regression that rejects the second save and checks both the committed reference and its original vault value. ID reuse, Vault write, Rollback hook.
  • 🔴 Clean up owned secrets when a renamed item is cleared. Renaming retains the fresh ID. A later clear checks the ID against the new slot name, so it misses post-commit cleanup and leaves the secret in the vault until hard delete. Use recorded ownership and remaining references to schedule cleanup after commit. Extend the rename test to clear the secret and verify its removal. Clear path.

@pmbrull pmbrull left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

❌ Changes needed · 1 🔴 · 0 🟡

Blockers ❌ 1 🔴
Nits ✅ none
Tests ❌ gaps in shared-reference cleanup coverage across configs
Cross-repo ✅ checked the ingestion secret resolver
Trade-off ✅ none
Auto-approved ➖ changes needed

Thanks for addressing the previous review. The new tests cover preserving the committed credential when a replacement fails and cleaning up a renamed entry after it is cleared.

  • 🔴 SecretMapOwnership.java:202 — Post-commit cleanup only checks references recorded under the owning root. Another persisted service or pipeline config can still use the same credential when the owner rotates or clears it. Delete the key only when all persisted references have been removed. Add a regression that reads the credential through a second config after the owner changes.

A maintainer also needs to add #38241 to Shipping and rerun the metadata check. Metadata check details

What I checked

Reviewed the changes since the previous review, including fresh-key allocation, rollback, post-commit cleanup, and resolution of stored secret references in ingestion. The follow-up integration tests pin the earlier findings within one service. I read the Java tests. The current check results do not show a Java test run for this commit.

claude-verdict {"sha":"2fc20743b9c902f798c87555b37d43cf90969bf5","recommendation":"request_changes","blocking":1,"nits_to_fix":0,"human_decision":false,"tradeoff":"none","cross_repo":"checked","tests_ok":false}

for (var iterator = scalars.iterator(); iterator.hasNext(); ) {
String name = iterator.next();
if (generatedNames.contains(manager.canonicalSecretName(name))) {
state.owned().add(name);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🔴 Moving generated IDs into post-commit cleanup makes an ordinary credential edit eligible to delete the old key. The cleanup at line 222 only sees references in the owning root, so an independent config that still uses the credential loses it. Retire a key only after confirming the last persisted reference is gone. Add a regression that keeps reading through a second config after the owner rotates or clears the credential.

@pmbrull

pmbrull commented Nov 27, 2026

Copy link
Copy Markdown
Member

I ran the list-secret scenarios against a real Kubernetes secrets manager: the suite server switched to a K3s-backed KubernetesSecretsManager, with every assertion reading the Kubernetes Secret directly. The #38241 scenarios pass on this branch. One Kubernetes-only case still breaks, and part of it is new in this PR.

Problem. sanitizeForK8s cuts every secret id at 253 characters (truncation). Once a service name plus a server name passes roughly 220 characters, two servers whose names start the same way get the same default id. Allocation and the ownership ledger both key list slots by that id, so the two servers collapse into one slot:

  • 🔴 Secrets orphaned after hard delete (new in this PR). The inventory keeps one reference per slot (referencesBySlot), and recordWrite maps the written slots back through it (writtenSecretsFor, recordWrite), so the ledger records the sibling's name instead of the one written. With servers named "x".repeat(240) + "one" and "x".repeat(240) + "two", rotating the first key and hard-deleting the service leaves two Secrets in Kubernetes, one of them holding the rotated-away key. The same steps on main leave none.
  • 🔴 One server's key overwrites its sibling's. If the first server is created without a key, adding one later writes into the secret the second server references, because hasOtherReferrer treats a referrer in the same slot as itself (same-slot check). Both servers then resolve to one key, and clearing either one would delete the other's secret the same way.

Proposed fix (A + B). Neither part needs a migration: the ledger stores secret names, never slots, and slots only exist in memory during a write.

  • A. Refuse colliding list slots before any vault write. This is the list counterpart of rejectCollidingEntrySecretIds, which already refuses map entries that share an id. validateIncomingSecretValues runs before anything is written (call), and there two elements that resolve to the same id show up as the same slot visited twice. If either of them carries a plaintext value or is being cleared, return 400 asking to shorten one of the names. A save in which every colliding element keeps its masked value or passes its reference through stays accepted, so services saved before this rule remain editable.
  • B. Record the ids actually written. Extend WriteContext.freshCreated into a record of every name the write stored, default ids included, and have recordWrite use it instead of re-deriving names from the slot-keyed inventory. The ledger then no longer depends on slots being unique, which also covers any collision that A doesn't catch.

Hashing the overflow in sanitizeForK8s instead of cutting it would also fix this, and would cover two services whose names collide too. It changes existing secret ids, though, and for service names over about 236 characters it changes the ledger namespace, so I'd leave it for a follow-up issue rather than this PR.

Tests. Please add tests that pin this down, for example in ListSecretReferenceAllocationTest next to kubernetesLongServerNameUsesCompactFreshIdWithoutTruncatingSuffix, which already builds a Kubernetes manager:

  • Creating, and updating, an MCP service whose two servers resolve to the same Kubernetes secret id is refused with 400, and no secret is written or deleted.
  • The same service saved with both colliding keys masked is still accepted.
  • recordWrite records every name a write stored even when two slots share an id, so a later hard delete leaves no secret behind.

@gitar-bot

gitar-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 🔴 High risk 2 closed / 2 findings

Changing secret allocation and cross-entity cleanup could overwrite or delete vault credentials still referenced by persisted services, pipelines, or workflows.

Adds fresh secret id allocation for list elements whose default id is still referenced by another slot, along with shared credential retention and rollback cleanup for owned secrets. Resolved the ADR omission of the compact fresh-id format and the per-deletion scan across all service, pipeline and workflow tables. No open issues found.

✅ 2 closed
✅ Quality: ADR v4 omits the compact fresh-id format and the 8-attempt budget

📄 openmetadata-service/src/main/java/org/openmetadata/service/secrets/SecretsManager.java:544 📄 openmetadata-service/src/main/java/org/openmetadata/service/secrets/SecretsManager.java:705-714 📄 openmetadata-service/src/main/java/org/openmetadata/service/secrets/SecretsManager.java:1263-1265 📄 openmetadata-service/src/main/java/org/openmetadata/service/secrets/SecretsManager.java:1409-1423 📄 docs/decisions/2026-11-11-mcp-service-server-names-are-unique-and-masks-need-a-stored-value.md:68-73
The v4 amendment records the fresh id format <defaultId><sep><13-char base32> but describes the long-name fallback only as "a hashed fallback under the entity root". The code fixes it to <root><sep>f<first 16 hex of sha256(canonical default id)><sep><suffix>, and isFreshIdFor/storedSecretName must keep recognising exactly that shape. If a later change alters the tag, hard delete stops treating existing compact ids as owned, and those vault secrets are orphaned. The PR also adds MAX_FRESH_ID_ATTEMPTS = 8, a retry budget picked by judgment. It caps how many soft-deleted names (Azure 409) one write steps past, each costing one rate-limited vault write, before the save fails. The amendment records neither value.

The record could state: "A list element's fresh id that would exceed the provider limit is <entity root><sep>f<16 hex chars of SHA-256 of the canonical default id><sep><13-char base32 suffix>; this format is persisted and must stay recognisable for deletion. A write retries on a fresh id at most 8 times after a reserved-name refusal before failing."

✅ Performance: Each vault deletion scans every service, pipeline and workflow table

📄 openmetadata-service/src/main/java/org/openmetadata/service/secrets/SharedSecretReferences.java:54-68 📄 openmetadata-service/src/main/java/org/openmetadata/service/secrets/SecretMapOwnership.java:338-352
cleanOwned calls references.unreferenced(removed) whenever it is about to delete a credential. The scan only stops early once every candidate has been found in some row. In the normal case the removed key really is unreferenced, so findIn reads all rows of all 13 service tables, ingestion_pipeline_entity and the workflow table. It deserializes each row and builds a secretInventory for it, which for workflows also runs a ClassConverter.

The scan runs while the process-wide SecretMapOwnership lock is held, so every secret write on any service, pipeline or workflow waits behind it. Test-connection workflows pile up over time, which makes it worse.

The cost also multiplies. cleanNamespace runs one full scan per entry in cleanupRoots plus one for the root itself. A recovery pass can call cleanDeletedWorkflow for up to 100 markers, each with its own scan, and a marker that keeps failing repeats its scan on every later service write.

Suggested fix: collect the removal candidates across all roots in one cleanNamespace or recovery pass and run a single unreferenced call for the whole set. Longer term, keep a persisted reverse index from canonical key to referring config, maintained in recordWrite/removeOwner, so the scan is only a fallback for legacy rows (for example, behind a one-time migration flag) and not something every deletion pays for.

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

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A renamed list element's secret is overwritten when a new element reuses its old name

2 participants