Skip to content

fix(mcp): read prompts/get token from header - #36531

Merged
Vishnuujain merged 1 commit into
mainfrom
mcp-prompt-token
Oct 29, 2026
Merged

Vishnuujain merged 1 commit into
mainfrom
mcp-prompt-token

Conversation

@Vishnuujain

Copy link
Copy Markdown
Contributor

Describe your changes:

Fixes #36528

  • prompts/get read the caller's token from the request arguments instead of the Authorization header, so every call failed with "Not Authorized! Invalid token." even with a valid PAT, while tools/call worked with the same token.
  • Broke in Upgrade Mcp to 0.11.2 #23049, which moved tools to the header-based request context but not prompts. Prompts now resolve the caller from the same header context as tools, and a token sent inside the arguments is ignored.

Type of change:

  • Bug fix

High-level design:

N/A, small bug fix.

Tests:

Use cases covered

  • prompts/get with a PAT in the Authorization header returns the prompt.
  • A token sent inside the prompt arguments does not decide the caller; the header does.

Unit tests

  • McpServerRequestContextTest#promptAuthenticatesWithTheHeaderNotTheArguments (new): fails on main because the body token is used, passes with the fix. The existing prompt tests now pass the token in the transport context, not the arguments.
  • mvn -pl openmetadata-mcp test -Dtest=McpServerRequestContextTest: 11 passed.

Backend integration tests

  • McpIntegrationIT#testMcpPromptsGet (new). The MCP IT helpers no longer put an Authorization entry into tool arguments; no server code reads it.
  • Compiled locally, not run yet.

Ingestion integration tests

N/A, no ingestion changes.

Playwright (UI) tests

N/A, no UI changes.

Manual testing performed

  1. Local server, admin PAT, curl to /mcp.
  2. Before the fix: tools/call search_metadata and prompts/list worked, prompts/get search_metadata returned -32603 Not Authorized! Invalid token.
  3. After the fix: prompts/get returns the prompt with the header alone, a junk Authorization inside arguments is ignored, and a bad header token still gets 401.

UI screen recording:

N/A, backend only.

Checklist:

  • I have read the CONTRIBUTING document.

  • My PR title is Fixes <issue-number>: <short explanation>

  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.

  • I have commented on my code, particularly in hard-to-understand areas.

  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed.

  • For a UI feature or feature task: as part of PR creation, I ran the PR build in Docker with sample data and embedded a verified GitHub-hosted recording plus build/health evidence above (or explained why this requirement is not applicable).

  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

  • Self-review: I reviewed the final diff against REVIEW.md (the pr-checklist skill runs it) and fixed every 🔴 finding, or answered it on the line below.
    Reviewed 7ea981f: no 🔴. The one 🟡 (the prompt test did not prove which token was used) is fixed: a body token now throws in the test.

  • Decision check: no record needed, this restores the header-based caller lookup tools already use.

  • I have added a test that covers the exact scenario we are fixing.

@github-actions github-actions Bot added the safe to test Add this label to run secure Github workflows on PRs label Oct 29, 2026
@gitar-bot

gitar-bot Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved

🔴 High risk · Moving prompts/get identity resolution from arguments to transport headers changes authentication; header-context errors could authorize the wrong caller or reject valid requests.

Fixes prompts/get to resolve the caller's token from the Authorization header instead of the request arguments, matching how tools/call already authenticates. Prompts now use the same header-based request context as tools, and a token inside the arguments is ignored. No issues found.

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

@Vishnuujain
Vishnuujain marked this pull request as ready for review October 29, 2026 09:10
@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.

@Vishnuujain Vishnuujain self-assigned this Oct 29, 2026
@Vishnuujain Vishnuujain added the To release Will cherry-pick this PR into the release branch label Oct 29, 2026
@Vishnuujain
Vishnuujain enabled auto-merge October 29, 2026 09:16
@Vishnuujain
Vishnuujain disabled auto-merge October 29, 2026 09:38
@Vishnuujain
Vishnuujain added this pull request to the merge queue Oct 29, 2026
Merged via the queue into main with commit 3c67c82 Oct 29, 2026
149 of 151 checks passed
@Vishnuujain
Vishnuujain deleted the mcp-prompt-token branch October 29, 2026 14:38
@github-actions

Copy link
Copy Markdown
Contributor

🤖 Backport to 2.1 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@github-actions

Copy link
Copy Markdown
Contributor

🤖 Backport to 2.0 is under way. It is built from openmetadata-collate, which holds the credentials needed to open a PR here, and it will comment again with the result — nothing is needed from you unless it reports otherwise.

@gh-bot-collate

Copy link
Copy Markdown

🤖 Backport to 2.0 failed. The conflict could not be resolved, so this change is not on that branch. Resolver run.

@gh-bot-collate

Copy link
Copy Markdown

🤖 Backport to 2.1 opened as #36567 (clean cherry-pick). It merges itself once the checks pass.

harshach added a commit that referenced this pull request Oct 29, 2026
…erifier docs

- The verifier's decision record says MCP access tokens are stored and that
  checkValidationsForToken looks them up, and that prompt callbacks, like tool
  callbacks, check the token in the request's Authorization header (#36531).
- Amend the per-request cleanup record: the personal access token loader it
  names is gone, and the verifier reads outside the request entity cache.
- OmCredential.NotStored and the checkValidationsForToken Javadoc name the MCP
  access token lookup and the rule that a provider token never signs in to a bot.
- Every minted token gets its jti in one place; the MCP branch adds only
  client_id.
- MintedTokensAreRecognizedTest mints the MCP access token with a client id, as
  issueAccessToken does, and describes the self-service case as a token minted
  before generateToken became bot-only.
- McpServerUnconfirmedTokenTest sends the prompt caller's token in the header.
Vishnuujain added a commit that referenced this pull request Oct 29, 2026
(cherry picked from commit 3c67c82)

Co-authored-by: Vishnu Jain <[email protected]>
harshach added a commit that referenced this pull request Oct 30, 2026
…erifier docs

- The verifier's decision record says MCP access tokens are stored and that
  checkValidationsForToken looks them up, and that prompt callbacks, like tool
  callbacks, check the token in the request's Authorization header (#36531).
- Amend the per-request cleanup record: the personal access token loader it
  names is gone, and the verifier reads outside the request entity cache.
- OmCredential.NotStored and the checkValidationsForToken Javadoc name the MCP
  access token lookup and the rule that a provider token never signs in to a bot.
- Every minted token gets its jti in one place; the MCP branch adds only
  client_id.
- MintedTokensAreRecognizedTest mints the MCP access token with a client id, as
  issueAccessToken does, and describes the self-service case as a token minted
  before generateToken became bot-only.
- McpServerUnconfirmedTokenTest sends the prompt caller's token in the header.
harshach added a commit that referenced this pull request Oct 30, 2026
…r credential cache (#36217)

* Add a unique jti to every minted token and remove the unused impersonation token generator

* Add credential contract types

* Add credential check microbenchmark harness and legacy baseline

* Add the database credential source and its index migration

* Compare credential stamps by elapsed difference

System.nanoTime readings are meaningful only as differences, and a stamp can cross Long.MAX_VALUE. VerifiedCredentials.reconfirmedAt and VerifiedCredentials.newer now order stamps by the sign of their difference instead of by magnitude. The new test stamps either side of Long.MAX_VALUE.

* Add the credential check decision and token classification

CheckDecision is the hot-path policy as a pure function of the cache entry, the clock reading, the token digest and the two durations, so the staleness bound is tested as a table at the maxStaleness and missRefreshMinAge boundaries. A load that completes outside the bound answers LOAD_STALE rather than REJECT, because an unconfirmed read is not a confirmed revocation.

OmCredential classifies a signature-verified token into Stored, NotStored or Unrecognized from the signing key and the isBot and tokenType claims. The classification is total, so no claim combination skips the stored-token check. CredentialVerificationConfig.policy() hands the decision its two durations.

* Add the credential verifier with its cache, single-flight reads and sweep

CredentialVerifier is one server's view of which stored credentials are current. Every cache entry carries the clock reading taken before the database read that produced it. require() trusts an entry only while that stamp is within maxStaleness, and a merge never lets an older stamp replace a newer one, so a revocation committed at T is honored by every check that begins at or after T + maxStaleness.

A request-thread read is single-flight per subject, joinable only while its stamp is within missRefreshMinAge, and bounded by a permit semaphore and the load timeout. A read that fails, times out or gets no permit answers CredentialUnavailableException, which is not AuthenticationException. The sweep re-confirms each batch of cached subjects with one fingerprint query, re-reads only the subjects whose fingerprint moved, and installs through computeIfPresent so it can never create or revive an entry. CredentialMetrics resolves every counter the hot path touches once, in its constructor.

The tests run a real verifier over an in-memory source and a hand-moved clock. They assert what a caller observes and count statements where the contract is about database load.

* Add the process-wide credential verifier holder

Credentials.verifier() is what the authentication filter checks tokens against. Before a verifier is installed, every Stored check answers CredentialUnavailableException through a verifier whose source has no database, never "unchecked".

Credentials.changed(principal) re-reads the subject on the calling thread once the surrounding PostCommitActionQueue scope commits, so a server is read-your-writes. nudgeFromPeer queues a peer's hint for the sweep thread. awaitPropagation blocks for maxStaleness plus a margin, which the staleness bound makes sufficient for every server.

* Tell the credential verifier about every credential write

* Announce credential changes to other servers

* Build, start and health-check one credential verifier at startup

* Test the credential verifier on one server

Out-of-band database writes, two verifiers converging on the same
database, the MCP transport, a hot path with no I/O, and a database
outage.

* Benchmark the legacy credential check against the verifier, interleaved

* Tidy credential comments and test names

* Test that bot and PAT requests add no Redis round trip and survive Redis being down

Register both Redis-lane classes with the isolated and global-state test lists, and
let scale tests under tests/security/scale run in the scale-it profile.

* Measure credential verification: request latency, sweep cost and cache memory

CredentialAuthBenchIT times bot, PAT and session-token requests at 1, 16 and 64
concurrency with a cold-start cell; CredentialSweepCostIT and CredentialMemoryIT
read an in-process verifier's sweep and heap cost. Meters are read by name so the
request benchmark also runs against a build without the verifier.

* Compare per-request credential costs with a margin and prove the sweep cells ran

The hot-path, Redis round-trip and Redis-down tests require a bot or PAT
request to cost less than one statement or Redis call per ten requests
more than the control request. A cost paid on every request fails that
ten times over; a cache refresh or a server-wide call that lands during
either phase does not.

The request benchmark decides whether the server has a verifier by class
name, so a renamed or unregistered meter fails its proof checks. The
sweep benchmark fails when a cell shows no sweep, no deep verify, or a
cached-subjects gauge that differs from the principals it warmed. The
scale helper test carries the scale tag, so the scale-it profile runs it.

* Run a second server in its own JVM for cross-server credential tests

Add ForkedServerNode, a server in a separate JVM that shares the suite's
database, search and Redis, signs and decrypts with the suite's keys, and
exposes its own credential meters. Add the cross-server revocation,
propagation-wait and ops-CLI tests, the propagation latency benchmark and
the two-server token creation burst, and register them in the multi-node
and scale lanes in place of the in-JVM Redis revocation test.

* Measure the unknown-token window from the last full read

A cache entry now carries two stamps: the trust stamp that sweep
reconfirmations move, and the stamp of the full read that produced its
record, which only a full read moves. Staleness still uses the trust
stamp, so the revocation bound is unchanged. The window in which a
token the entry lacks is answered without a read is measured from the
full-read stamp, because a reconfirmation proves the record current but
reads nothing new. A token created on a peer right after a
reconfirmation is therefore read and accepted on first use, and the
cap of one reload per missRefreshMinAge per subject holds because every
reload is a full read.

* Confirm swept entries in place instead of rewriting them

A sweep reconfirmation now advances the entry's trust stamp in place
with a compare-and-set that only ever moves it forward, and the sweep
reads entries through the cache's quiet view. A reconfirmation is
therefore neither a cache write nor an access, so the cache's
frequency, recency and idle expiry reflect requests alone and a
principal nobody presents cannot keep a newcomer from being admitted.
Only a changed record is written. The full-read stamp stays immutable
per full read, and the hot path still allocates nothing beyond the
presented token's digest.

* Convert credential subjects on their own and reconfirm before a deep read

The database source converts each subject of a full read on its own. A
subject whose rows cannot be converted, because a decrypt or a stored
JSON value fails, is logged once with its principal and left out of the
result; a statement failure still throws. The verifier treats a subject
missing from a result as unconfirmed: it installs nothing for it, a
request-thread read answers "cannot confirm" under the new
subject_read_failed cause, and the left-out subjects are counted.

The deep verify runs after each batch's fingerprint reconfirmation and
reads the batch in full with every decrypt forced. A deep read that
fails leaves the batch trusted by its fingerprints and health
untouched, and the pass is retried after min(deepVerifyInterval, 1 min).
One stamp holds that decision, because a batch now fails only on a
statement failure, so the whole pass is what to retry. A full read wins
a stamp tie against a confirmation at the same instant, since the
confirmation can move the existing stamp to exactly the read's instant
and the read saw the rows.

* Read the clock after the credential cache lookup

A check now looks up its principal's entry first and reads the clock
after, so the age it measures belongs to the later of the two moments
and errs on the older side.

* Run request-thread credential reads on a bounded pool within loadTimeout

A check that misses or finds a stale entry starts or joins one read of
its principal and waits for it on a future, within loadTimeout of the
check's first clock read. The check that started the read waits the
same way as one that joined it. A read that outlives every waiter
finishes on its pool thread and installs under the newer-wins rule.

- Reads run on a pool of daemon platform threads, maxConcurrentRequestReads
  wide, with a bounded queue. A read that gets no slot, at once or within
  a waiter's budget, answers 503 with cause no_permit, and a queued read
  whose waiter gives up is withdrawn from the queue.
- At most one request read per principal is in flight, and a check joins
  it whatever its age. When the joined read lacks the presented token and
  its full read began more than missRefreshMinAge before the check, the
  check joins or starts one newer read within the same budget, and
  answers 503 when none fits.
- A check that registers a new read first decides again on the cached
  entry, so checks that arrive while a read installs cost no second read.
- A read is stamped after it is registered and before it waits for a
  slot, and it leaves the registry before its future completes, so a
  check that reads again never rejoins a finished read.
- A throwable of any kind from the source fails the read's future, so
  its waiters answer 503 at once, and the read counts as outcome=error.

* Let a post-commit credential refresh supersede older reads

refreshNow and nudge reads register in the in-flight registry the way a
check's read does, replacing the read they find there and marking it
superseded, and they take their stamp after registering. A superseded
read keeps its waiters, who decide on its result, but no new check can
join it, and it never creates a cache entry, though it may still replace
an older one under the newer-wins rule. Sweep and deep-verify reads
never create an entry either.

So once refreshNow has registered, no read registered before it can
create the subject's entry, even after the entry the refresh installs is
evicted or idles out, and every read registered later is stamped after
the write committed.

refreshNow and the nudge drain look for a read in flight before they
look in the cache. A read leaves the registry only after its install or
once superseded, and a superseded read creates nothing, so a subject
found in neither has no read left that could create its entry.

Checks that arrive while a refresh or nudge read runs join it instead
of starting their own.

* Schedule at most one credential nudge drain at a time

A nudge schedules a drain on the sweep thread only when it flips a
pending flag from false to true, and the drain clears the flag before it
takes the queued subjects, so a nudge queued after that schedules the
next drain. While the sweep thread is busy, nudges then add subjects to
the bounded nudge set instead of tasks to the executor's queue.

* Publish the credential sweep scheduler through one atomic reference

start creates a scheduler and publishes it with a compare-and-set
before it schedules the sweeps; a call that finds a scheduler already
published shuts its own down unused. stop takes the published scheduler
with getAndSet(null) and shuts it down, so every scheduler is shut down
by exactly one stop. A stop that takes the scheduler before its start
has scheduled on it leaves the schedule rejected, and nothing runs.

Concurrent start and stop calls therefore never throw, and a final stop
leaves no sweep thread running.

* Pin credential stamp placement and single flight in tests

- The fake source can run a hook inside its next fingerprint statement
  or full read, after the statement has seen the rows. Two tests revoke
  alice and move the clock 3 s inside a sweep's fingerprint statement
  and inside its full re-read, then check her 2 s + 1 ns later with the
  database down: the entry is trusted from before the statement, so the
  check cannot confirm.
- joinedLoadIsTrustedOnlyUntilItsOwnStampAges releases the read only
  once all 100 checks wait on it, and still sees one read.
- slowLoadThatStartedBeforeRevocationCannotExtendTrust moves the clock
  1 ms between the nudge and the slow read's install, so the two stamps
  differ and the outcome does not rest on how a tie is broken.
- The refresh tests gain a sweep re-read held in the source past the
  refresh: it replaces entries but never creates one, so it cannot
  recreate the entry the refresh installed once that entry idles out.
- Tests that stage a read across several steps give checks a 4 s
  loadTimeout, since checks wait for reads in real time.

* Describe how a withdrawn credential read answers its waiters

A read still queued when any of its waiters runs out of budget is
withdrawn, and every waiter of it then answers no_permit, a joiner with
budget left included. The withdrawal's Javadoc states this, and the
in-flight registry's Javadoc names failure as the other way a read
leaves the registry.

* Carry the retry hint on a credential that cannot be confirmed

CredentialUnavailableException now carries retryAfterSeconds, set
where the verifier builds it (the sweep interval, rounded up) and by
an interrupted awaitPropagation. The REST, WebSocket and MCP edges can
answer 503 with Retry-After without reaching into the static holder.
The unused message-only constructor is gone.

* Check stored tokens through the verifier at every entry point

JwtFilter.authenticate verifies the signature, resolves the token's
own identity, classifies it with OmCredential and asks the installed
CredentialVerifier to confirm a stored bot JWT or personal access
token. filter(), validateJwtAndGetClaims and getCatalogSecurityContext
all go through it. An impersonated request is checked against the bot
that presented the token, before the swap to the target. An
OpenMetadata-signed token of a kind OpenMetadata does not issue is
rejected as an unrecognized token type. The bot and personal access
token messages keep their text.

verifySignatureOnly checks signature, expiry and issuer alone, for the
startup bot token check, the JWKS status step and the test-login dry
run, which grant no access. The public four-argument
checkValidationsForToken keeps its signature and no longer reads
impersonatedBy, so SocketAddressFilter's impersonation helper goes.

JwtFilterTest runs over a real verifier with an in-memory source and
tokens minted by JWTTokenGenerator.

* Answer a token that cannot be confirmed with 503 and Retry-After

A CredentialUnavailableException now reaches each transport as a
retryable answer rather than a rejection:

- REST: CredentialUnavailableExceptionMapper returns 503 with
  Retry-After and the ErrorMessage body the generic mapper writes.
- WebSocket handshake: SocketAddressFilter refuses the upgrade with
  503 and Retry-After.
- MCP transport: 503 with Retry-After and JSON-RPC code -32003, with
  no WWW-Authenticate challenge, since the token is not invalid.
  Retry-After joins the CORS exposed headers.
- MCP tool and prompt callbacks: an McpError with code -32003, so the
  caller reads a retryable condition.

Every body carries CredentialUnavailableException.CLIENT_MESSAGE. The
exception's own message names the principal and stays in the debug
log.

* Benchmark the credential check through the filter as the server builds it

CredentialCheckBenchmark moves to the credentials test package and
measures only the verifier: rs256Verify, credentialSubjectOf and the
verifierHit cells stay. The new authenticateEndToEnd cells install a
fixture verifier, build JwtFilter with the server's constructor and
time validateJwtAndGetClaims for a bot JWT and a personal access
token: signature, identity, classification and the stored-credential
check together, with no database. Each cell still fails if a timed
call reads on the request thread.

* Keep the four-argument JwtFilter test constructor

Other distributions' tests build the filter through the package-
private (JwkProvider, principal claims, principal domain, enforce)
constructor. It stays, and reads the installed verifier as the
production constructor does. OpenMetadata's own tests pass a verifier
supplier through the five-argument form.

* Remove the per-request token cache now that the verifier answers

The verifier is the only stored-credential check, so its predecessor
goes:

- CredentialTokenState and its test are deleted, with
  CacheKeys.credentialMutationLock. credentialState stays for the
  announcer's key cleanup.
- The seven UserResource token writes are plain repository calls; the
  repository hints refresh the verifier after commit.
- UserRepository no longer overrides beginDeleteLifecycle, and
  postRestore sends only the Credentials.changed hint.
- BotTokenCache keeps getToken and EMPTY_STRING, which read the stored
  JWT directly. UserTokenCache keeps a deprecated invalidateToken that
  calls Credentials.changed. Both stay because other distributions call
  them.
- JwtFilter.IMPERSONATED_USER_CLAIM is gone: nothing mints or reads it.
- The Redis requirement line leaves conf/openmetadata.yaml, and a
  UserResourceIT comment names the stored-credential check.

* Recognize every token the server mints

Mint a token with each issuing call the server makes, with the
arguments its call site passes, and check it through JwtFilter. Every
one is accepted. Bot, self-service and personal access tokens are read
back from what the server stores; session, login, refresh and MCP
OAuth access tokens never reach a stored-credential read.

* Drop an inaccurate comment on the rejection messages

Only one integration test matches one of the messages, and the
constants explain themselves.

* Test patched, self-service and unrecognized tokens over HTTP

A PATCH that replaces a bot's JWT leaves only the new token valid on
the next request. A regular user's own generated token works at once
and stops working once the user is soft-deleted. A token signed with
the server key in a claim combination no issuing call produces gets
401 from REST, with the unrecognized-token message, and from the MCP
transport.

* Record that a per-server verifier checks stored tokens

Each server answers bot and personal access token checks from memory
and confirms them against the database within maxStaleness. A check
it cannot confirm answers 503 with Retry-After, and Redis only speeds
up convergence between servers.

* Test the answers BotTokenCache.getToken gives

Other distributions read a bot's stored token through it. It returns
the decrypted token, an empty string when the bot has no token or does
not exist, and null when the bot cannot be read.

* Tighten the new token tests

Move the patch and token builders of the HTTP token tests into
helpers, and name the table the minted-token test guards.

* Expect both legacy credential keys gone after a revoke

A new server never writes credential:bot:* or credential:pat:*, so the
announcer's delete leaves both absent and the test can say so exactly.

* Classify a token type that is not text as unknown

OpenMetadata writes the tokenType claim as text. OmCredential.classify
reads a present value of any other JSON type as a token type of no issued
kind, so an OpenMetadata-signed token carrying one is rejected as an
unrecognized token type.

* Keep credential verification out of the liveness health check

The admin /healthcheck runs every registered health check and is the
liveness probe target, which must not depend on the database (see
OpenMetadataServerHealthCheck). The credential verifier's check turned
unhealthy whenever no sweep completed within maxStaleness, so a database
outage would fail liveness on every server and restart them.

Drop the check. The gauge om.credential.sweep.last.complete.age.seconds
carries the same signal for alerting, and the tests now assert on it.

* Fail a credential read's registration when it cannot start

A check registers its read before it hands the read to the request-read
pool. When that hand-off throws, as it does when the pool cannot create a
thread, the check fails the registration before the throwable propagates,
so the next check of the subject starts a read of its own.

A refresh or nudge read registers its subjects inside the try that guards
the read, and fails every registration it made on any throwable.

A package-private constructor takes the thread factory of the read pool,
and the existing constructor delegates to it.

* Keep a credential sweep pass going when a batch throws an Error

The sweep's per-batch guards catch any throwable, as the read itself and
the scheduled pass do: the reconfirmation of a batch, its deep read, and
the refresh or nudge read. An Error from one subject's read, such as a
stack overflow inside its decrypt, then fails only that batch. Every later
batch is still reconfirmed, a batch whose deep read failed still counts
toward a complete pass, and a failed deep pass is retried after
min(deepVerifyInterval, 1 min), as it is for an exception.

The fake credential source gains a per-subject Error mode.

* Back off credential reads of a subject whose read produced no record

After a full read produces no record for a subject, because the source
left the subject out, the read threw, or it got no pool slot, a check of
that subject that needs a read answers unavailable without one until
missRefreshMinAge after that read's stamp. A read that produces a record
ends the window, even when it installs nothing. Every read path counts:
check, refresh, nudge, sweep and deep reads.

The window runs from the read's stamp, taken before its statement, so a
write at T that makes the subject readable is accepted by the first check
at or after T + missRefreshMinAge. The stamps sit in a Caffeine cache on
the verifier's ticker, bounded by maxSubjects and expiring after
missRefreshMinAge. The cache-hit path is unchanged.

These answers count under om.credential.unavailable with cause backoff.
A subject the source leaves out is warned about once per window, and the
database source logs the cause at DEBUG. The LOAD_UNKNOWN_TOKEN and
CredentialSource Javadoc describe the reload bound and the logging.

* Give four credential verifier tests a one-second loadTimeout

These tests need one pool read to finish within loadTimeout in real
time. A one-second budget keeps a garbage-collection pause or a loaded
machine from turning that read into a timeout. The tests assert outcomes
and statement counts, never how long a check waited.

* Describe the credential read pool, drain count and extra reads

The scheduleDrain Javadoc says at most two drains wait on the sweep
thread: one queued before a sweep pass and one queued after that pass's
own drain cleared the pending flag.

The maxConcurrentRequestReads comment says these reads run on the read
pool and a request thread only waits for its read.

The in-flight read Javadoc says that once a refresh or nudge has
superseded a read and finished, a check can start one more pool read of
the subject while the superseded one still runs, so the write rate bounds
these extra reads.

* Run CredentialLegacyKeyShimIT in the multi-node lane

It is tagged multi-node, so the parallel lane skips it, but no isolated
lane listed it. List it beside the other credential multi-node suites.

* Correct the verifier startup, PAT cleanup and propagation comments

The startup Javadoc describes the verifier as the stored-token check it
is. The migration comment says which rows the cleanup removes, and the
propagation benchmark's Javadoc says what it times.

* Name the impersonation test after the check it asserts

* Assert the MCP transport's 503 while the database is paused

During the outage, an MCP initialize with the bot or PAT token gets 503
with Retry-After and no WWW-Authenticate challenge, the answer REST gives.
CredentialFixtures gains the MCP initialize call.

* Reword the legacy-key test Javadoc and mark the impersonation design historical

The design document still describes generateImpersonationToken and
IMPERSONATED_USER_CLAIM, which no longer exist.

* Wait for credential propagation against the monotonic clock

Credentials.awaitPropagation sleeps again until System.nanoTime passes its
deadline, since Thread.sleep does not promise to sleep the whole time. Without
an installed verifier the wait has no bound, so it answers 503, the way an
uninstalled verifier answers a check.

* Add waitForPropagation to the two token revoke endpoints

PUT /v1/users/revokeToken and PUT /v1/users/security/token/revoke take a
waitForPropagation query parameter, false by default. When it is true, the
call responds only after the write has committed and the verifier's
maxStaleness plus a 50 ms margin has passed. By then every server rejects
the revoked token. The call takes about credentialVerification.maxStaleness
(5 seconds by default) longer.

When the server cannot finish the wait, the call answers 503 with
Retry-After. The write has committed by then, and a repeated call answers
200 and waits again.

* Return a verified provider token's claims without resolving its principal

validateJwtAndGetClaims resolved the principal before the stored-credential
check, so a provider token that carries none of the configured principal
claims failed there with 401. Callers that map the principal themselves,
such as Collate's bearer-token resolver, receive the claims again and keep
answering that case themselves. The principal is now resolved only for a
bot JWT or a personal access token, the two kinds the check reads.

* Treat a provider token that claims to be a PAT as unrecognized

OmCredential now classifies a token that the identity provider signed with
tokenType PERSONAL_ACCESS as unrecognized, as it already does for one that
claims isBot. Such a token gets 401, as it does on main.
SsoOidcPublicBearerIT (OP-16) covers this.

* Announce a deleted user's credential change from the delete lifecycle

Deleting a bot soft-deletes its user through bulkSoftDeleteSubtree, which
runs beginDeleteLifecycle but not postDelete. The change is now announced
when the delete lifecycle closes. Every delete path runs it, so the server
that deleted the bot rejects its user's token on the next request.
UserResourceIT.test_deleteBotEntity_rejectsContainedUsersBotToken covers it.

* Send the bot token request with the expiry's JSON value

CredentialFixtures.botToken sent JWTTokenExpiry as Seven, which is the Java
constant name. The JSON value is 7, so the request failed with 400, and
every test that minted a bot token through the fixture errored before its
first assertion. The body is now serialized from GenerateTokenRequest.

* Remove a token-rotation test comment that no longer holds

Every minted token carries a random jti, so two tokens minted in the same
second already differ.

* Assert that a PATCH leaves a user's authentication mechanism unchanged

UserRepository.restorePatchAttributes puts the stored authentication
mechanism back before the update, so PATCH /v1/users/{id} never changes a
user's token. test_patchBotAuthMechanism_revokesOldToken expected the
patch to replace it. The test, now test_patchBotAuthMechanism_isIgnored,
asserts that the stored digests are unchanged, that the stored token still
signs in, and that the token the patch carried gets 401.
UserRepositoryUnitTest applies the same patch operation and pins the
restore.

* Expect the verifier class in the scale helper test

CredentialMeters.verifierPresent decides by class name, so it is true in
this build before any meter registers. The test asserted false for an
empty registry and failed every run.

* Give the ops-command test's bot a Bot entity

regenerate-bot-tokens regenerates the token of each Bot entity's user.
CredentialFixtures.createBot creates only a bot user, so the command left
the test's token as it was and the test failed at its first assertion.
The test now creates a Bot entity for its user before it mints the token.

* Back off repeated reads only for reads a check started

A sweep, deep, refresh or nudge read covers a batch or runs for a writer, so a failure there says nothing about one subject's own read. Only check reads open a window now; the warning about a subject the source left out keeps its once-per-window pacing through its own window.

* Withdraw a timed-out read's registration even when recording it fails

The registration is failed in a finally, so an Error thrown while the meter or the backoff is recorded cannot leave later checks of the subject joining a read that never runs.

* Test that read backoff windows run from the read's stamp

Cover a read that throws late, a read withdrawn for want of a slot, and stamps on either side of the ticker wrap.

* Report why a subject's stored credentials could not be converted

The source returns the cause of each subject it leaves out, and the once-per-window warning carries its message.

* Name the sweep age gauge and its alert threshold for operators

The credentialVerification comment block and the decision record say to alert when the gauge passes maxStaleness and what a check does then. The sweepOnce Javadoc now says an Error for one subject also fails its batch.

* Cap concurrent propagation waits at eight per process

A wait holds its request for about maxStaleness. A call that finds all eight permits taken answers 503 with the verifier's Retry-After; the write has committed, and a repeat is harmless.

* Record the waitForPropagation parameter and its limit

The decision record gains a bullet for the parameter, its wait bound, the eight-permit cap and why an interrupted or refused wait answers 503.

* Retry a deep pass at the retry interval when it leaves a subject out

* Count decrypts and reuses from the records a read installs

* Record the verifier limits, the entry points and the propagation bound

* Shorten the rollout note in the verifier decision record

The sentence before it already says which maxStaleness applies during a
rollout that changes it.

* Test that a deep pass installs what it converts and passes deleted principals

* Test at the verifier that only a check's read backs a subject off

* Create a withdrawn read's exception before withdrawing it

* Match the verifier's comments and decision record to its backoff, gauge and wait rules

* Decrypt on every read that can overlap a deep pass

* Record which reads reuse a decrypted digest

* Create the user_tokens index before the ontology tables, under its own statement names

* Drop the cleanup of Redis credential keys that no release writes

Credentials publishes the peer nudge itself. The key helper, the unconfirmed-write filter and their tests served only those keys.

* Name digest-only token storage as the verifier's next step

* Reflow the deep-verify bullet and name deleted users in the record Javadoc

* Test that a refresh started inside a deep pass decrypts

* Say where a check's read runs and what fails a sweep batch in the verifier texts

* Assert that warm credential requests start no credential read

* Pin first-use acceptance and retry transient unavailability in the convergence test

* Cover rotation, soft delete and the nudge in the two-process test

* Tighten the config, outage and scale-helper tests

* Test that invalidateToken makes the next check reject a removed token

* Fix the Postgres plan read and tighten the credential test waits

- CredentialSourceTestSupport reads Postgres EXPLAIN rows by position.
  Jdbi lowercases map keys, so a lookup of "QUERY PLAN" found nothing.
- UserTokenCacheTest asserts that the hint reads the user again once.
- The convergence IT gives a first use 5 s, longer than loadTimeout,
  and says why it waits after it stops the sweeps.
- The two-process IT takes missRefreshMinAge from the config defaults.
- checkReads replaces checkStartedReads: a read is counted when it
  finishes.
- Comment lines are wrapped at 100 columns.

* Mark a subject the deep read cannot convert as unconfirmed

A subject that a deep read leaves out keeps its cache entry, marked
unconfirmed at the read's stamp. No check is answered from that entry.
Its next check reads the subject and answers by that read, or 503 while
the subject does not convert, with the usual backoff. A matching
fingerprint does not move an unconfirmed entry's stamp, and its record
is offered to no decrypt reuse. Installs stay newer-wins by stamp. A
read stamped before the deep read cannot replace the entry and a read
stamped after it can, and the deep read leaves an entry that a later
read installed as it is.

A subject left out does not fail the deep pass. The retry after
min(deepVerifyInterval, 1 min) is scheduled only when a batch's
reconfirmation or deep read throws.

* Count only this test's sweep threads and replace only the yaml block

The two sweep-thread tests count only the threads named
om-credential-verifier that appear after a snapshot taken before their
verifier starts, so a verifier that another test in the JVM still runs
does not count.

shippedWithBlock replaces only the credentialVerification block's own
lines, up to the next top-level key, so a key that follows the block in
conf/openmetadata.yaml stays in the parsed config.

* State the unconfirmed rule and the deep retry rule in the verifier texts

The sweepOnce and deepReadQuietly Javadocs, the deep-verify warning,
the CredentialSource.read Javadoc and the decision record say that a
subject the deep read leaves out is unconfirmed, that its checks read
it again and answer 503 until a read converts it, and that the deep
pass is retried after min(deepVerifyInterval, 1 min) only when a
batch's reconfirmation or deep read throws.

* Record that a bot answers 503 while its secret cannot be decrypted

Consequences now say that from the next deep pass on, a bot whose secret
the secrets manager cannot decrypt answers 503 until a read decrypts it,
and that its checks inside the backoff window count as cause=backoff.

* Warn about a principal whose credentials cannot be converted once a minute

The warning window ran from each failure and lasted the 500 ms backoff, so
a principal left out at every backoff window was logged with a stack trace
on every read. The window now starts at the warning and lasts one minute,
and a read that converts the principal still ends it.

* State the read cost of an unconvertible bot and which read unconfirms

The decision record now counts the sweep decrypts of a bot whose stored
rows changed, says that a hanging decrypt holds a request-read thread, and
gives the warning rate. The CredentialSource and CheckDecision Javadocs say
that only the deep verify's read unconfirms a subject.

* Pin the warning window's ordering and wrap rules and state its rate exactly

ReadBackoffTest covers a warning stamped before the open window that
finishes later, and a window opened just before the ticker wraps. The
decision record says that a decrypt that hangs during the deep read holds
the sweep thread, and that the warning rate is per principal.

* Defer tokens a recent read lacks and spread the deep verify over passes

Four changes to the credential verifier, from review:

- A check of a token that the principal's last full read lacks, while
  that read is younger than missRefreshMinAge, now answers 503 with
  Retry-After (cause=deferred) instead of 401. A token created on
  another server is then accepted on the retry. The check still answers
  401 when the entry shows the token withdrawn: a read lacked it
  although a check presented it before that read began, or an earlier
  read held it and the read began after that one finished. A counter
  taken around each read's statement orders the reads, and an entry
  keeps at most 8 withdrawn digests.
- Each sweep pass reconfirms every batch first, then continues the deep
  verify at 10 principals per read. It starts another read only while
  the pass has run less than maxStaleness minus twice sweepInterval, so
  slow decrypts delay the deep verify instead of the reconfirmations.
- An interrupt while a check waits for its read answers 503 under
  cause=interrupted instead of counting as a read timeout.
- JwtFilter.checkValidationsForToken runs the stored-credential check on
  the token it is given, from that token's own claims.

The decision record states each rule. test_patchBotAuthMechanism_isIgnored
now waits past a 503 for the 401.

* Order withdrawn digests newest first and check prefixed tokens once

Four changes from the review of 057db89:
- An entry lists its withdrawn digests newest first, starting with the
  one its own read shows withdrawn. A check whose read finds more than 8
  tokens gone then still answers 401 for the token it presented, not 503.
- SocketAddressFilter.validatePrefixedTokenRequest verifies the signature
  with verifySignatureOnly and leaves the stored-credential check to
  checkValidationsForToken. A WebSocket handshake or an MCP HTTP request
  now counts one check in om.credential.checks instead of two.
- A test covers a deep verify whose first read throws while the later
  passes succeed. It is retried a minute after it began.
- The decision record and the sweep Javadoc include the reconfirm time in
  the deep-verify timing, and say when the next deep pass begins after a
  long one. The record also covers a withdrawn token that comes back when
  a deleted principal is restored.

* Say that MCP tool and prompt calls are checked again by their callbacks

The message of bd9aeb7 says an MCP HTTP request now counts one
check. The transport does check each request once, but a tool or prompt
call is checked again by its callback, through getCatalogSecurityContext,
so it counts two checks instead of three. The decision record now says
so.

The record and the sweep Javadoc also count nudge drains on the sweep
thread in the deep-verify timing, and name the deep budget rather than
its default. The Javadoc now says when the next deep pass begins after
a long one.

* State when the deep budget keeps entries fresh and what a prompt checks

The decision record and the sweep Javadoc gave the age between two
reconfirmations as a sum that left out the next pass's own drain. They
now say why the deep budget is maxStaleness minus twice sweepInterval,
which conditions keep entries within maxStaleness, and that checks of an
entry past it read the database.

A prompt call's callback checks the token in the prompt's Authorization
argument, as it did before this branch. The record now says so instead
of grouping prompt calls with tool calls.

The record also says a deep read covers at most 10 principals, and that
the next deep pass begins with the first sweep pass that starts once its
interval has passed.

* Break down an entry's age between sweeps instead of stating a condition

The decision record and the sweep Javadoc listed conditions that keep
entries within maxStaleness, but one nudge drain still holding the sweep
thread when the next pass is due could age an entry past it with every
condition met. They now give an entry's age at its next reconfirmation
as the sum of the work between the two, say what the deep budget alone
keeps within maxStaleness, and say that the next check of an older entry
reads it again.

They also say that a sweep pass makes deep reads only while a deep pass
has principals left.

The sweepInterval validation message no longer says that the
half-of-maxStaleness rule absorbs a missed sweep, which holds only while
passes are short. Exactly half stays accepted.

* Say where the sweep thread decrypts and whose age the breakdown bounds

The decision record said a slow decrypt delays only the deep pass. A
sweep or nudge re-read that cannot reuse the last decrypt, as for a bot
whose stored secret changed, also decrypts on the sweep thread, so a
slow decrypt there delays reconfirmations too. The record now names all
three places, and says the deep budget limits how many deep reads a pass
starts, not how long one takes.

The age breakdown in the record and the sweep Javadoc is an upper bound
for an entry the pass reconfirmed. An entry the pass did not reconfirm,
such as one in a failed batch, can be older. Both now say so.

* Describe decrypt reuse, failed batches and the sweep schedule exactly

From the review of ee62509:
- A sweep or nudge re-read reuses a decrypt only from a confirmed entry
  whose read saw the same stored mechanism and updatedAt, so any change
  to a bot's user row decrypts again, not only a changed secret.
- While the secrets manager cannot decrypt a bot's secret, the bot
  answers 503 from its next deep read, or sooner once its user row
  changes.
- A failed batch leaves to age out only the entries it did not
  reconfirm. Its matched entries are reconfirmed before the re-read of
  the changed ones.
- The age bound covers an entry that still holds the stamp its batch
  took in the pass.
- A sweep pass starts sweepInterval after the previous one ends, not
  every sweepInterval.
- The DEEP_CHUNK_SIZE Javadoc says how far past the budget a pass's
  deep reads can end.

Only the decision record, Javadoc comments and a configuration comment
change.

* State by rule when a bot answers 503, and fix four wording slips

From the review of c26d72d:
- While the secrets manager cannot decrypt a bot's secret, every read
  that must decrypt it fails, so any check of the bot that cannot be
  answered from memory answers 503. That includes a server's first
  check of a bot it holds no entry for. The record now says so instead
  of listing when the 503s start, a list that left that case out.
- A sweep pass is due sweepInterval after the previous one ends. The
  first runs at once, and a nudge drain can delay one.
- Decrypt reuse is keyed on the stored mechanism and updatedAt, not on
  the whole user row.
- An entry is too old to answer from once its last read or
  reconfirmation is older than maxStaleness, whatever the gauge shows.
- A deep read takes fewer subjects when batchSize is smaller.

The reconfirmAll Javadoc, the failed-batch log message, the
CredentialRecord Javadoc and the sweepInterval comment in
openmetadata.yaml get the matching corrections.

* Narrow three sentences and drop a claim about updatedAt

From the review of 0ccf370:
- The reconfirmAll Javadoc said a failing batch leaves the other
  batches' entries reconfirmed. Another batch can hold an entry whose
  re-read cannot convert it, so the Javadoc now says only that a failing
  batch does not stop the rest from reconfirming.
- The decision record no longer says that writes to a bot user through
  the API change its updatedAt, since some writes keep it. The
  decrypt-reuse rule beside it already names the stored mechanism and
  updatedAt.
- While the secrets manager cannot decrypt a bot's secret, a check that
  waits on a read that must decrypt, or on the backoff after one,
  answers 503. A check that joins a nudge read able to reuse the last
  decrypt can still get an answer, so the record no longer says that
  every check it cannot answer from memory answers 503.
- A stale entry's checks need a read and answer 503 when the verifier
  cannot confirm within loadTimeout, in the record and in
  openmetadata.yaml.
- The sweepInterval comment in openmetadata.yaml now says a pass is due
  that long after the previous one ends, which the message of
  0ccf370 said it already did.

* Build main's allowed-domain filter tests with the test verifier

Two JwtFilterTest cases from main call the seven-argument test constructor, which this branch
extends with the verifier supplier.

* Describe main's stored MCP tokens and header-checked prompts in the verifier docs

- The verifier's decision record says MCP access tokens are stored and that
  checkValidationsForToken looks them up, and that prompt callbacks, like tool
  callbacks, check the token in the request's Authorization header (#36531).
- Amend the per-request cleanup record: the personal access token loader it
  names is gone, and the verifier reads outside the request entity cache.
- OmCredential.NotStored and the checkValidationsForToken Javadoc name the MCP
  access token lookup and the rule that a provider token never signs in to a bot.
- Every minted token gets its jti in one place; the MCP branch adds only
  client_id.
- MintedTokensAreRecognizedTest mints the MCP access token with a client id, as
  issueAccessToken does, and describes the self-service case as a token minted
  before generateToken became bot-only.
- McpServerUnconfirmedTokenTest sends the prompt caller's token in the header.

* Scope the bot-account rule to the legacy claim flow and name what a callback repeats

- The checkValidationsForToken Javadoc says the rule that a provider token never
  signs in to a bot account belongs to the legacy claim flow, where the code
  applies it.
- The decision record says an MCP tool or prompt callback repeats the
  stored-credential check, and that classify reads no client_id, which is why
  an MCP access token is NotStored like a login token.
- MintedTokensAreRecognizedTest names what it runs: the stored-credential check
  through validateJwtAndGetClaims, and reads back only what is kept for the
  verifier.

* Remove two token tests for a call #36156 made bot-only

Since #36156, POST /users/generateToken mints tokens for bot users only, and
main's test_generateToken_forOwnRegularAccount_forbidden covers that rule.
UserResourceIT.test_selfGeneratedToken_lifecycle called it for a regular
user, so it now gets 403, and MintedTokensAreRecognizedTest had a row for the
same call. Both are removed. test_deleteBotUser_rejectsBotToken and
test_deleteUser_rejectsPersonalAccessToken still cover account deletion.

* Answer an unconfirmed push-feed upgrade with 503 and Retry-After

#36143 authenticates WebSocket upgrades in the upgrade creator, which
the servlet filter chain never reaches. A CredentialUnavailableException
thrown there escaped the creator, and Jetty answered the upgrade with
500. The upgrade now answers 503 with Retry-After, as the servlet path
and the REST and MCP entry points do, and stops the negotiation.

authenticateUpgrade becomes package-private and static, so
OpenMetadataApplicationPushFeedUpgradeTest can register it on an
embedded Jetty server and open the upgrade with the JDK's WebSocket
client. The authenticate Javadoc now lists
CredentialUnavailableException.

* Bound the push-feed upgrade test's handshake at 10 s

The JDK's HttpClient.close() waits for an open handshake, so a server
that accepted the connection and never answered would hold the test,
and the build, until the server closed it. connectTimeout fails the
handshake after 10 s instead, and the 20 s get bound stays above it.

The per-server verifier's decision record names the test in its Guard.

* Test the push-feed upgrade's 401 and 403 answers

OpenMetadataApplicationPushFeedUpgradeTest now also opens upgrades that
authenticate rejects with a HandshakeRejectedException or an
AuthenticationException, and checks the status the client receives.
With the 503 case, each rejection that authenticateUpgrade answers is
tested at the upgrade layer.
manerow pushed a commit that referenced this pull request Oct 30, 2026
…r credential cache (#36217)

* Add a unique jti to every minted token and remove the unused impersonation token generator

* Add credential contract types

* Add credential check microbenchmark harness and legacy baseline

* Add the database credential source and its index migration

* Compare credential stamps by elapsed difference

System.nanoTime readings are meaningful only as differences, and a stamp can cross Long.MAX_VALUE. VerifiedCredentials.reconfirmedAt and VerifiedCredentials.newer now order stamps by the sign of their difference instead of by magnitude. The new test stamps either side of Long.MAX_VALUE.

* Add the credential check decision and token classification

CheckDecision is the hot-path policy as a pure function of the cache entry, the clock reading, the token digest and the two durations, so the staleness bound is tested as a table at the maxStaleness and missRefreshMinAge boundaries. A load that completes outside the bound answers LOAD_STALE rather than REJECT, because an unconfirmed read is not a confirmed revocation.

OmCredential classifies a signature-verified token into Stored, NotStored or Unrecognized from the signing key and the isBot and tokenType claims. The classification is total, so no claim combination skips the stored-token check. CredentialVerificationConfig.policy() hands the decision its two durations.

* Add the credential verifier with its cache, single-flight reads and sweep

CredentialVerifier is one server's view of which stored credentials are current. Every cache entry carries the clock reading taken before the database read that produced it. require() trusts an entry only while that stamp is within maxStaleness, and a merge never lets an older stamp replace a newer one, so a revocation committed at T is honored by every check that begins at or after T + maxStaleness.

A request-thread read is single-flight per subject, joinable only while its stamp is within missRefreshMinAge, and bounded by a permit semaphore and the load timeout. A read that fails, times out or gets no permit answers CredentialUnavailableException, which is not AuthenticationException. The sweep re-confirms each batch of cached subjects with one fingerprint query, re-reads only the subjects whose fingerprint moved, and installs through computeIfPresent so it can never create or revive an entry. CredentialMetrics resolves every counter the hot path touches once, in its constructor.

The tests run a real verifier over an in-memory source and a hand-moved clock. They assert what a caller observes and count statements where the contract is about database load.

* Add the process-wide credential verifier holder

Credentials.verifier() is what the authentication filter checks tokens against. Before a verifier is installed, every Stored check answers CredentialUnavailableException through a verifier whose source has no database, never "unchecked".

Credentials.changed(principal) re-reads the subject on the calling thread once the surrounding PostCommitActionQueue scope commits, so a server is read-your-writes. nudgeFromPeer queues a peer's hint for the sweep thread. awaitPropagation blocks for maxStaleness plus a margin, which the staleness bound makes sufficient for every server.

* Tell the credential verifier about every credential write

* Announce credential changes to other servers

* Build, start and health-check one credential verifier at startup

* Test the credential verifier on one server

Out-of-band database writes, two verifiers converging on the same
database, the MCP transport, a hot path with no I/O, and a database
outage.

* Benchmark the legacy credential check against the verifier, interleaved

* Tidy credential comments and test names

* Test that bot and PAT requests add no Redis round trip and survive Redis being down

Register both Redis-lane classes with the isolated and global-state test lists, and
let scale tests under tests/security/scale run in the scale-it profile.

* Measure credential verification: request latency, sweep cost and cache memory

CredentialAuthBenchIT times bot, PAT and session-token requests at 1, 16 and 64
concurrency with a cold-start cell; CredentialSweepCostIT and CredentialMemoryIT
read an in-process verifier's sweep and heap cost. Meters are read by name so the
request benchmark also runs against a build without the verifier.

* Compare per-request credential costs with a margin and prove the sweep cells ran

The hot-path, Redis round-trip and Redis-down tests require a bot or PAT
request to cost less than one statement or Redis call per ten requests
more than the control request. A cost paid on every request fails that
ten times over; a cache refresh or a server-wide call that lands during
either phase does not.

The request benchmark decides whether the server has a verifier by class
name, so a renamed or unregistered meter fails its proof checks. The
sweep benchmark fails when a cell shows no sweep, no deep verify, or a
cached-subjects gauge that differs from the principals it warmed. The
scale helper test carries the scale tag, so the scale-it profile runs it.

* Run a second server in its own JVM for cross-server credential tests

Add ForkedServerNode, a server in a separate JVM that shares the suite's
database, search and Redis, signs and decrypts with the suite's keys, and
exposes its own credential meters. Add the cross-server revocation,
propagation-wait and ops-CLI tests, the propagation latency benchmark and
the two-server token creation burst, and register them in the multi-node
and scale lanes in place of the in-JVM Redis revocation test.

* Measure the unknown-token window from the last full read

A cache entry now carries two stamps: the trust stamp that sweep
reconfirmations move, and the stamp of the full read that produced its
record, which only a full read moves. Staleness still uses the trust
stamp, so the revocation bound is unchanged. The window in which a
token the entry lacks is answered without a read is measured from the
full-read stamp, because a reconfirmation proves the record current but
reads nothing new. A token created on a peer right after a
reconfirmation is therefore read and accepted on first use, and the
cap of one reload per missRefreshMinAge per subject holds because every
reload is a full read.

* Confirm swept entries in place instead of rewriting them

A sweep reconfirmation now advances the entry's trust stamp in place
with a compare-and-set that only ever moves it forward, and the sweep
reads entries through the cache's quiet view. A reconfirmation is
therefore neither a cache write nor an access, so the cache's
frequency, recency and idle expiry reflect requests alone and a
principal nobody presents cannot keep a newcomer from being admitted.
Only a changed record is written. The full-read stamp stays immutable
per full read, and the hot path still allocates nothing beyond the
presented token's digest.

* Convert credential subjects on their own and reconfirm before a deep read

The database source converts each subject of a full read on its own. A
subject whose rows cannot be converted, because a decrypt or a stored
JSON value fails, is logged once with its principal and left out of the
result; a statement failure still throws. The verifier treats a subject
missing from a result as unconfirmed: it installs nothing for it, a
request-thread read answers "cannot confirm" under the new
subject_read_failed cause, and the left-out subjects are counted.

The deep verify runs after each batch's fingerprint reconfirmation and
reads the batch in full with every decrypt forced. A deep read that
fails leaves the batch trusted by its fingerprints and health
untouched, and the pass is retried after min(deepVerifyInterval, 1 min).
One stamp holds that decision, because a batch now fails only on a
statement failure, so the whole pass is what to retry. A full read wins
a stamp tie against a confirmation at the same instant, since the
confirmation can move the existing stamp to exactly the read's instant
and the read saw the rows.

* Read the clock after the credential cache lookup

A check now looks up its principal's entry first and reads the clock
after, so the age it measures belongs to the later of the two moments
and errs on the older side.

* Run request-thread credential reads on a bounded pool within loadTimeout

A check that misses or finds a stale entry starts or joins one read of
its principal and waits for it on a future, within loadTimeout of the
check's first clock read. The check that started the read waits the
same way as one that joined it. A read that outlives every waiter
finishes on its pool thread and installs under the newer-wins rule.

- Reads run on a pool of daemon platform threads, maxConcurrentRequestReads
  wide, with a bounded queue. A read that gets no slot, at once or within
  a waiter's budget, answers 503 with cause no_permit, and a queued read
  whose waiter gives up is withdrawn from the queue.
- At most one request read per principal is in flight, and a check joins
  it whatever its age. When the joined read lacks the presented token and
  its full read began more than missRefreshMinAge before the check, the
  check joins or starts one newer read within the same budget, and
  answers 503 when none fits.
- A check that registers a new read first decides again on the cached
  entry, so checks that arrive while a read installs cost no second read.
- A read is stamped after it is registered and before it waits for a
  slot, and it leaves the registry before its future completes, so a
  check that reads again never rejoins a finished read.
- A throwable of any kind from the source fails the read's future, so
  its waiters answer 503 at once, and the read counts as outcome=error.

* Let a post-commit credential refresh supersede older reads

refreshNow and nudge reads register in the in-flight registry the way a
check's read does, replacing the read they find there and marking it
superseded, and they take their stamp after registering. A superseded
read keeps its waiters, who decide on its result, but no new check can
join it, and it never creates a cache entry, though it may still replace
an older one under the newer-wins rule. Sweep and deep-verify reads
never create an entry either.

So once refreshNow has registered, no read registered before it can
create the subject's entry, even after the entry the refresh installs is
evicted or idles out, and every read registered later is stamped after
the write committed.

refreshNow and the nudge drain look for a read in flight before they
look in the cache. A read leaves the registry only after its install or
once superseded, and a superseded read creates nothing, so a subject
found in neither has no read left that could create its entry.

Checks that arrive while a refresh or nudge read runs join it instead
of starting their own.

* Schedule at most one credential nudge drain at a time

A nudge schedules a drain on the sweep thread only when it flips a
pending flag from false to true, and the drain clears the flag before it
takes the queued subjects, so a nudge queued after that schedules the
next drain. While the sweep thread is busy, nudges then add subjects to
the bounded nudge set instead of tasks to the executor's queue.

* Publish the credential sweep scheduler through one atomic reference

start creates a scheduler and publishes it with a compare-and-set
before it schedules the sweeps; a call that finds a scheduler already
published shuts its own down unused. stop takes the published scheduler
with getAndSet(null) and shuts it down, so every scheduler is shut down
by exactly one stop. A stop that takes the scheduler before its start
has scheduled on it leaves the schedule rejected, and nothing runs.

Concurrent start and stop calls therefore never throw, and a final stop
leaves no sweep thread running.

* Pin credential stamp placement and single flight in tests

- The fake source can run a hook inside its next fingerprint statement
  or full read, after the statement has seen the rows. Two tests revoke
  alice and move the clock 3 s inside a sweep's fingerprint statement
  and inside its full re-read, then check her 2 s + 1 ns later with the
  database down: the entry is trusted from before the statement, so the
  check cannot confirm.
- joinedLoadIsTrustedOnlyUntilItsOwnStampAges releases the read only
  once all 100 checks wait on it, and still sees one read.
- slowLoadThatStartedBeforeRevocationCannotExtendTrust moves the clock
  1 ms between the nudge and the slow read's install, so the two stamps
  differ and the outcome does not rest on how a tie is broken.
- The refresh tests gain a sweep re-read held in the source past the
  refresh: it replaces entries but never creates one, so it cannot
  recreate the entry the refresh installed once that entry idles out.
- Tests that stage a read across several steps give checks a 4 s
  loadTimeout, since checks wait for reads in real time.

* Describe how a withdrawn credential read answers its waiters

A read still queued when any of its waiters runs out of budget is
withdrawn, and every waiter of it then answers no_permit, a joiner with
budget left included. The withdrawal's Javadoc states this, and the
in-flight registry's Javadoc names failure as the other way a read
leaves the registry.

* Carry the retry hint on a credential that cannot be confirmed

CredentialUnavailableException now carries retryAfterSeconds, set
where the verifier builds it (the sweep interval, rounded up) and by
an interrupted awaitPropagation. The REST, WebSocket and MCP edges can
answer 503 with Retry-After without reaching into the static holder.
The unused message-only constructor is gone.

* Check stored tokens through the verifier at every entry point

JwtFilter.authenticate verifies the signature, resolves the token's
own identity, classifies it with OmCredential and asks the installed
CredentialVerifier to confirm a stored bot JWT or personal access
token. filter(), validateJwtAndGetClaims and getCatalogSecurityContext
all go through it. An impersonated request is checked against the bot
that presented the token, before the swap to the target. An
OpenMetadata-signed token of a kind OpenMetadata does not issue is
rejected as an unrecognized token type. The bot and personal access
token messages keep their text.

verifySignatureOnly checks signature, expiry and issuer alone, for the
startup bot token check, the JWKS status step and the test-login dry
run, which grant no access. The public four-argument
checkValidationsForToken keeps its signature and no longer reads
impersonatedBy, so SocketAddressFilter's impersonation helper goes.

JwtFilterTest runs over a real verifier with an in-memory source and
tokens minted by JWTTokenGenerator.

* Answer a token that cannot be confirmed with 503 and Retry-After

A CredentialUnavailableException now reaches each transport as a
retryable answer rather than a rejection:

- REST: CredentialUnavailableExceptionMapper returns 503 with
  Retry-After and the ErrorMessage body the generic mapper writes.
- WebSocket handshake: SocketAddressFilter refuses the upgrade with
  503 and Retry-After.
- MCP transport: 503 with Retry-After and JSON-RPC code -32003, with
  no WWW-Authenticate challenge, since the token is not invalid.
  Retry-After joins the CORS exposed headers.
- MCP tool and prompt callbacks: an McpError with code -32003, so the
  caller reads a retryable condition.

Every body carries CredentialUnavailableException.CLIENT_MESSAGE. The
exception's own message names the principal and stays in the debug
log.

* Benchmark the credential check through the filter as the server builds it

CredentialCheckBenchmark moves to the credentials test package and
measures only the verifier: rs256Verify, credentialSubjectOf and the
verifierHit cells stay. The new authenticateEndToEnd cells install a
fixture verifier, build JwtFilter with the server's constructor and
time validateJwtAndGetClaims for a bot JWT and a personal access
token: signature, identity, classification and the stored-credential
check together, with no database. Each cell still fails if a timed
call reads on the request thread.

* Keep the four-argument JwtFilter test constructor

Other distributions' tests build the filter through the package-
private (JwkProvider, principal claims, principal domain, enforce)
constructor. It stays, and reads the installed verifier as the
production constructor does. OpenMetadata's own tests pass a verifier
supplier through the five-argument form.

* Remove the per-request token cache now that the verifier answers

The verifier is the only stored-credential check, so its predecessor
goes:

- CredentialTokenState and its test are deleted, with
  CacheKeys.credentialMutationLock. credentialState stays for the
  announcer's key cleanup.
- The seven UserResource token writes are plain repository calls; the
  repository hints refresh the verifier after commit.
- UserRepository no longer overrides beginDeleteLifecycle, and
  postRestore sends only the Credentials.changed hint.
- BotTokenCache keeps getToken and EMPTY_STRING, which read the stored
  JWT directly. UserTokenCache keeps a deprecated invalidateToken that
  calls Credentials.changed. Both stay because other distributions call
  them.
- JwtFilter.IMPERSONATED_USER_CLAIM is gone: nothing mints or reads it.
- The Redis requirement line leaves conf/openmetadata.yaml, and a
  UserResourceIT comment names the stored-credential check.

* Recognize every token the server mints

Mint a token with each issuing call the server makes, with the
arguments its call site passes, and check it through JwtFilter. Every
one is accepted. Bot, self-service and personal access tokens are read
back from what the server stores; session, login, refresh and MCP
OAuth access tokens never reach a stored-credential read.

* Drop an inaccurate comment on the rejection messages

Only one integration test matches one of the messages, and the
constants explain themselves.

* Test patched, self-service and unrecognized tokens over HTTP

A PATCH that replaces a bot's JWT leaves only the new token valid on
the next request. A regular user's own generated token works at once
and stops working once the user is soft-deleted. A token signed with
the server key in a claim combination no issuing call produces gets
401 from REST, with the unrecognized-token message, and from the MCP
transport.

* Record that a per-server verifier checks stored tokens

Each server answers bot and personal access token checks from memory
and confirms them against the database within maxStaleness. A check
it cannot confirm answers 503 with Retry-After, and Redis only speeds
up convergence between servers.

* Test the answers BotTokenCache.getToken gives

Other distributions read a bot's stored token through it. It returns
the decrypted token, an empty string when the bot has no token or does
not exist, and null when the bot cannot be read.

* Tighten the new token tests

Move the patch and token builders of the HTTP token tests into
helpers, and name the table the minted-token test guards.

* Expect both legacy credential keys gone after a revoke

A new server never writes credential:bot:* or credential:pat:*, so the
announcer's delete leaves both absent and the test can say so exactly.

* Classify a token type that is not text as unknown

OpenMetadata writes the tokenType claim as text. OmCredential.classify
reads a present value of any other JSON type as a token type of no issued
kind, so an OpenMetadata-signed token carrying one is rejected as an
unrecognized token type.

* Keep credential verification out of the liveness health check

The admin /healthcheck runs every registered health check and is the
liveness probe target, which must not depend on the database (see
OpenMetadataServerHealthCheck). The credential verifier's check turned
unhealthy whenever no sweep completed within maxStaleness, so a database
outage would fail liveness on every server and restart them.

Drop the check. The gauge om.credential.sweep.last.complete.age.seconds
carries the same signal for alerting, and the tests now assert on it.

* Fail a credential read's registration when it cannot start

A check registers its read before it hands the read to the request-read
pool. When that hand-off throws, as it does when the pool cannot create a
thread, the check fails the registration before the throwable propagates,
so the next check of the subject starts a read of its own.

A refresh or nudge read registers its subjects inside the try that guards
the read, and fails every registration it made on any throwable.

A package-private constructor takes the thread factory of the read pool,
and the existing constructor delegates to it.

* Keep a credential sweep pass going when a batch throws an Error

The sweep's per-batch guards catch any throwable, as the read itself and
the scheduled pass do: the reconfirmation of a batch, its deep read, and
the refresh or nudge read. An Error from one subject's read, such as a
stack overflow inside its decrypt, then fails only that batch. Every later
batch is still reconfirmed, a batch whose deep read failed still counts
toward a complete pass, and a failed deep pass is retried after
min(deepVerifyInterval, 1 min), as it is for an exception.

The fake credential source gains a per-subject Error mode.

* Back off credential reads of a subject whose read produced no record

After a full read produces no record for a subject, because the source
left the subject out, the read threw, or it got no pool slot, a check of
that subject that needs a read answers unavailable without one until
missRefreshMinAge after that read's stamp. A read that produces a record
ends the window, even when it installs nothing. Every read path counts:
check, refresh, nudge, sweep and deep reads.

The window runs from the read's stamp, taken before its statement, so a
write at T that makes the subject readable is accepted by the first check
at or after T + missRefreshMinAge. The stamps sit in a Caffeine cache on
the verifier's ticker, bounded by maxSubjects and expiring after
missRefreshMinAge. The cache-hit path is unchanged.

These answers count under om.credential.unavailable with cause backoff.
A subject the source leaves out is warned about once per window, and the
database source logs the cause at DEBUG. The LOAD_UNKNOWN_TOKEN and
CredentialSource Javadoc describe the reload bound and the logging.

* Give four credential verifier tests a one-second loadTimeout

These tests need one pool read to finish within loadTimeout in real
time. A one-second budget keeps a garbage-collection pause or a loaded
machine from turning that read into a timeout. The tests assert outcomes
and statement counts, never how long a check waited.

* Describe the credential read pool, drain count and extra reads

The scheduleDrain Javadoc says at most two drains wait on the sweep
thread: one queued before a sweep pass and one queued after that pass's
own drain cleared the pending flag.

The maxConcurrentRequestReads comment says these reads run on the read
pool and a request thread only waits for its read.

The in-flight read Javadoc says that once a refresh or nudge has
superseded a read and finished, a check can start one more pool read of
the subject while the superseded one still runs, so the write rate bounds
these extra reads.

* Run CredentialLegacyKeyShimIT in the multi-node lane

It is tagged multi-node, so the parallel lane skips it, but no isolated
lane listed it. List it beside the other credential multi-node suites.

* Correct the verifier startup, PAT cleanup and propagation comments

The startup Javadoc describes the verifier as the stored-token check it
is. The migration comment says which rows the cleanup removes, and the
propagation benchmark's Javadoc says what it times.

* Name the impersonation test after the check it asserts

* Assert the MCP transport's 503 while the database is paused

During the outage, an MCP initialize with the bot or PAT token gets 503
with Retry-After and no WWW-Authenticate challenge, the answer REST gives.
CredentialFixtures gains the MCP initialize call.

* Reword the legacy-key test Javadoc and mark the impersonation design historical

The design document still describes generateImpersonationToken and
IMPERSONATED_USER_CLAIM, which no longer exist.

* Wait for credential propagation against the monotonic clock

Credentials.awaitPropagation sleeps again until System.nanoTime passes its
deadline, since Thread.sleep does not promise to sleep the whole time. Without
an installed verifier the wait has no bound, so it answers 503, the way an
uninstalled verifier answers a check.

* Add waitForPropagation to the two token revoke endpoints

PUT /v1/users/revokeToken and PUT /v1/users/security/token/revoke take a
waitForPropagation query parameter, false by default. When it is true, the
call responds only after the write has committed and the verifier's
maxStaleness plus a 50 ms margin has passed. By then every server rejects
the revoked token. The call takes about credentialVerification.maxStaleness
(5 seconds by default) longer.

When the server cannot finish the wait, the call answers 503 with
Retry-After. The write has committed by then, and a repeated call answers
200 and waits again.

* Return a verified provider token's claims without resolving its principal

validateJwtAndGetClaims resolved the principal before the stored-credential
check, so a provider token that carries none of the configured principal
claims failed there with 401. Callers that map the principal themselves,
such as Collate's bearer-token resolver, receive the claims again and keep
answering that case themselves. The principal is now resolved only for a
bot JWT or a personal access token, the two kinds the check reads.

* Treat a provider token that claims to be a PAT as unrecognized

OmCredential now classifies a token that the identity provider signed with
tokenType PERSONAL_ACCESS as unrecognized, as it already does for one that
claims isBot. Such a token gets 401, as it does on main.
SsoOidcPublicBearerIT (OP-16) covers this.

* Announce a deleted user's credential change from the delete lifecycle

Deleting a bot soft-deletes its user through bulkSoftDeleteSubtree, which
runs beginDeleteLifecycle but not postDelete. The change is now announced
when the delete lifecycle closes. Every delete path runs it, so the server
that deleted the bot rejects its user's token on the next request.
UserResourceIT.test_deleteBotEntity_rejectsContainedUsersBotToken covers it.

* Send the bot token request with the expiry's JSON value

CredentialFixtures.botToken sent JWTTokenExpiry as Seven, which is the Java
constant name. The JSON value is 7, so the request failed with 400, and
every test that minted a bot token through the fixture errored before its
first assertion. The body is now serialized from GenerateTokenRequest.

* Remove a token-rotation test comment that no longer holds

Every minted token carries a random jti, so two tokens minted in the same
second already differ.

* Assert that a PATCH leaves a user's authentication mechanism unchanged

UserRepository.restorePatchAttributes puts the stored authentication
mechanism back before the update, so PATCH /v1/users/{id} never changes a
user's token. test_patchBotAuthMechanism_revokesOldToken expected the
patch to replace it. The test, now test_patchBotAuthMechanism_isIgnored,
asserts that the stored digests are unchanged, that the stored token still
signs in, and that the token the patch carried gets 401.
UserRepositoryUnitTest applies the same patch operation and pins the
restore.

* Expect the verifier class in the scale helper test

CredentialMeters.verifierPresent decides by class name, so it is true in
this build before any meter registers. The test asserted false for an
empty registry and failed every run.

* Give the ops-command test's bot a Bot entity

regenerate-bot-tokens regenerates the token of each Bot entity's user.
CredentialFixtures.createBot creates only a bot user, so the command left
the test's token as it was and the test failed at its first assertion.
The test now creates a Bot entity for its user before it mints the token.

* Back off repeated reads only for reads a check started

A sweep, deep, refresh or nudge read covers a batch or runs for a writer, so a failure there says nothing about one subject's own read. Only check reads open a window now; the warning about a subject the source left out keeps its once-per-window pacing through its own window.

* Withdraw a timed-out read's registration even when recording it fails

The registration is failed in a finally, so an Error thrown while the meter or the backoff is recorded cannot leave later checks of the subject joining a read that never runs.

* Test that read backoff windows run from the read's stamp

Cover a read that throws late, a read withdrawn for want of a slot, and stamps on either side of the ticker wrap.

* Report why a subject's stored credentials could not be converted

The source returns the cause of each subject it leaves out, and the once-per-window warning carries its message.

* Name the sweep age gauge and its alert threshold for operators

The credentialVerification comment block and the decision record say to alert when the gauge passes maxStaleness and what a check does then. The sweepOnce Javadoc now says an Error for one subject also fails its batch.

* Cap concurrent propagation waits at eight per process

A wait holds its request for about maxStaleness. A call that finds all eight permits taken answers 503 with the verifier's Retry-After; the write has committed, and a repeat is harmless.

* Record the waitForPropagation parameter and its limit

The decision record gains a bullet for the parameter, its wait bound, the eight-permit cap and why an interrupted or refused wait answers 503.

* Retry a deep pass at the retry interval when it leaves a subject out

* Count decrypts and reuses from the records a read installs

* Record the verifier limits, the entry points and the propagation bound

* Shorten the rollout note in the verifier decision record

The sentence before it already says which maxStaleness applies during a
rollout that changes it.

* Test that a deep pass installs what it converts and passes deleted principals

* Test at the verifier that only a check's read backs a subject off

* Create a withdrawn read's exception before withdrawing it

* Match the verifier's comments and decision record to its backoff, gauge and wait rules

* Decrypt on every read that can overlap a deep pass

* Record which reads reuse a decrypted digest

* Create the user_tokens index before the ontology tables, under its own statement names

* Drop the cleanup of Redis credential keys that no release writes

Credentials publishes the peer nudge itself. The key helper, the unconfirmed-write filter and their tests served only those keys.

* Name digest-only token storage as the verifier's next step

* Reflow the deep-verify bullet and name deleted users in the record Javadoc

* Test that a refresh started inside a deep pass decrypts

* Say where a check's read runs and what fails a sweep batch in the verifier texts

* Assert that warm credential requests start no credential read

* Pin first-use acceptance and retry transient unavailability in the convergence test

* Cover rotation, soft delete and the nudge in the two-process test

* Tighten the config, outage and scale-helper tests

* Test that invalidateToken makes the next check reject a removed token

* Fix the Postgres plan read and tighten the credential test waits

- CredentialSourceTestSupport reads Postgres EXPLAIN rows by position.
  Jdbi lowercases map keys, so a lookup of "QUERY PLAN" found nothing.
- UserTokenCacheTest asserts that the hint reads the user again once.
- The convergence IT gives a first use 5 s, longer than loadTimeout,
  and says why it waits after it stops the sweeps.
- The two-process IT takes missRefreshMinAge from the config defaults.
- checkReads replaces checkStartedReads: a read is counted when it
  finishes.
- Comment lines are wrapped at 100 columns.

* Mark a subject the deep read cannot convert as unconfirmed

A subject that a deep read leaves out keeps its cache entry, marked
unconfirmed at the read's stamp. No check is answered from that entry.
Its next check reads the subject and answers by that read, or 503 while
the subject does not convert, with the usual backoff. A matching
fingerprint does not move an unconfirmed entry's stamp, and its record
is offered to no decrypt reuse. Installs stay newer-wins by stamp. A
read stamped before the deep read cannot replace the entry and a read
stamped after it can, and the deep read leaves an entry that a later
read installed as it is.

A subject left out does not fail the deep pass. The retry after
min(deepVerifyInterval, 1 min) is scheduled only when a batch's
reconfirmation or deep read throws.

* Count only this test's sweep threads and replace only the yaml block

The two sweep-thread tests count only the threads named
om-credential-verifier that appear after a snapshot taken before their
verifier starts, so a verifier that another test in the JVM still runs
does not count.

shippedWithBlock replaces only the credentialVerification block's own
lines, up to the next top-level key, so a key that follows the block in
conf/openmetadata.yaml stays in the parsed config.

* State the unconfirmed rule and the deep retry rule in the verifier texts

The sweepOnce and deepReadQuietly Javadocs, the deep-verify warning,
the CredentialSource.read Javadoc and the decision record say that a
subject the deep read leaves out is unconfirmed, that its checks read
it again and answer 503 until a read converts it, and that the deep
pass is retried after min(deepVerifyInterval, 1 min) only when a
batch's reconfirmation or deep read throws.

* Record that a bot answers 503 while its secret cannot be decrypted

Consequences now say that from the next deep pass on, a bot whose secret
the secrets manager cannot decrypt answers 503 until a read decrypts it,
and that its checks inside the backoff window count as cause=backoff.

* Warn about a principal whose credentials cannot be converted once a minute

The warning window ran from each failure and lasted the 500 ms backoff, so
a principal left out at every backoff window was logged with a stack trace
on every read. The window now starts at the warning and lasts one minute,
and a read that converts the principal still ends it.

* State the read cost of an unconvertible bot and which read unconfirms

The decision record now counts the sweep decrypts of a bot whose stored
rows changed, says that a hanging decrypt holds a request-read thread, and
gives the warning rate. The CredentialSource and CheckDecision Javadocs say
that only the deep verify's read unconfirms a subject.

* Pin the warning window's ordering and wrap rules and state its rate exactly

ReadBackoffTest covers a warning stamped before the open window that
finishes later, and a window opened just before the ticker wraps. The
decision record says that a decrypt that hangs during the deep read holds
the sweep thread, and that the warning rate is per principal.

* Defer tokens a recent read lacks and spread the deep verify over passes

Four changes to the credential verifier, from review:

- A check of a token that the principal's last full read lacks, while
  that read is younger than missRefreshMinAge, now answers 503 with
  Retry-After (cause=deferred) instead of 401. A token created on
  another server is then accepted on the retry. The check still answers
  401 when the entry shows the token withdrawn: a read lacked it
  although a check presented it before that read began, or an earlier
  read held it and the read began after that one finished. A counter
  taken around each read's statement orders the reads, and an entry
  keeps at most 8 withdrawn digests.
- Each sweep pass reconfirms every batch first, then continues the deep
  verify at 10 principals per read. It starts another read only while
  the pass has run less than maxStaleness minus twice sweepInterval, so
  slow decrypts delay the deep verify instead of the reconfirmations.
- An interrupt while a check waits for its read answers 503 under
  cause=interrupted instead of counting as a read timeout.
- JwtFilter.checkValidationsForToken runs the stored-credential check on
  the token it is given, from that token's own claims.

The decision record states each rule. test_patchBotAuthMechanism_isIgnored
now waits past a 503 for the 401.

* Order withdrawn digests newest first and check prefixed tokens once

Four changes from the review of 057db89:
- An entry lists its withdrawn digests newest first, starting with the
  one its own read shows withdrawn. A check whose read finds more than 8
  tokens gone then still answers 401 for the token it presented, not 503.
- SocketAddressFilter.validatePrefixedTokenRequest verifies the signature
  with verifySignatureOnly and leaves the stored-credential check to
  checkValidationsForToken. A WebSocket handshake or an MCP HTTP request
  now counts one check in om.credential.checks instead of two.
- A test covers a deep verify whose first read throws while the later
  passes succeed. It is retried a minute after it began.
- The decision record and the sweep Javadoc include the reconfirm time in
  the deep-verify timing, and say when the next deep pass begins after a
  long one. The record also covers a withdrawn token that comes back when
  a deleted principal is restored.

* Say that MCP tool and prompt calls are checked again by their callbacks

The message of bd9aeb7 says an MCP HTTP request now counts one
check. The transport does check each request once, but a tool or prompt
call is checked again by its callback, through getCatalogSecurityContext,
so it counts two checks instead of three. The decision record now says
so.

The record and the sweep Javadoc also count nudge drains on the sweep
thread in the deep-verify timing, and name the deep budget rather than
its default. The Javadoc now says when the next deep pass begins after
a long one.

* State when the deep budget keeps entries fresh and what a prompt checks

The decision record and the sweep Javadoc gave the age between two
reconfirmations as a sum that left out the next pass's own drain. They
now say why the deep budget is maxStaleness minus twice sweepInterval,
which conditions keep entries within maxStaleness, and that checks of an
entry past it read the database.

A prompt call's callback checks the token in the prompt's Authorization
argument, as it did before this branch. The record now says so instead
of grouping prompt calls with tool calls.

The record also says a deep read covers at most 10 principals, and that
the next deep pass begins with the first sweep pass that starts once its
interval has passed.

* Break down an entry's age between sweeps instead of stating a condition

The decision record and the sweep Javadoc listed conditions that keep
entries within maxStaleness, but one nudge drain still holding the sweep
thread when the next pass is due could age an entry past it with every
condition met. They now give an entry's age at its next reconfirmation
as the sum of the work between the two, say what the deep budget alone
keeps within maxStaleness, and say that the next check of an older entry
reads it again.

They also say that a sweep pass makes deep reads only while a deep pass
has principals left.

The sweepInterval validation message no longer says that the
half-of-maxStaleness rule absorbs a missed sweep, which holds only while
passes are short. Exactly half stays accepted.

* Say where the sweep thread decrypts and whose age the breakdown bounds

The decision record said a slow decrypt delays only the deep pass. A
sweep or nudge re-read that cannot reuse the last decrypt, as for a bot
whose stored secret changed, also decrypts on the sweep thread, so a
slow decrypt there delays reconfirmations too. The record now names all
three places, and says the deep budget limits how many deep reads a pass
starts, not how long one takes.

The age breakdown in the record and the sweep Javadoc is an upper bound
for an entry the pass reconfirmed. An entry the pass did not reconfirm,
such as one in a failed batch, can be older. Both now say so.

* Describe decrypt reuse, failed batches and the sweep schedule exactly

From the review of ee62509:
- A sweep or nudge re-read reuses a decrypt only from a confirmed entry
  whose read saw the same stored mechanism and updatedAt, so any change
  to a bot's user row decrypts again, not only a changed secret.
- While the secrets manager cannot decrypt a bot's secret, the bot
  answers 503 from its next deep read, or sooner once its user row
  changes.
- A failed batch leaves to age out only the entries it did not
  reconfirm. Its matched entries are reconfirmed before the re-read of
  the changed ones.
- The age bound covers an entry that still holds the stamp its batch
  took in the pass.
- A sweep pass starts sweepInterval after the previous one ends, not
  every sweepInterval.
- The DEEP_CHUNK_SIZE Javadoc says how far past the budget a pass's
  deep reads can end.

Only the decision record, Javadoc comments and a configuration comment
change.

* State by rule when a bot answers 503, and fix four wording slips

From the review of c26d72d:
- While the secrets manager cannot decrypt a bot's secret, every read
  that must decrypt it fails, so any check of the bot that cannot be
  answered from memory answers 503. That includes a server's first
  check of a bot it holds no entry for. The record now says so instead
  of listing when the 503s start, a list that left that case out.
- A sweep pass is due sweepInterval after the previous one ends. The
  first runs at once, and a nudge drain can delay one.
- Decrypt reuse is keyed on the stored mechanism and updatedAt, not on
  the whole user row.
- An entry is too old to answer from once its last read or
  reconfirmation is older than maxStaleness, whatever the gauge shows.
- A deep read takes fewer subjects when batchSize is smaller.

The reconfirmAll Javadoc, the failed-batch log message, the
CredentialRecord Javadoc and the sweepInterval comment in
openmetadata.yaml get the matching corrections.

* Narrow three sentences and drop a claim about updatedAt

From the review of 0ccf370:
- The reconfirmAll Javadoc said a failing batch leaves the other
  batches' entries reconfirmed. Another batch can hold an entry whose
  re-read cannot convert it, so the Javadoc now says only that a failing
  batch does not stop the rest from reconfirming.
- The decision record no longer says that writes to a bot user through
  the API change its updatedAt, since some writes keep it. The
  decrypt-reuse rule beside it already names the stored mechanism and
  updatedAt.
- While the secrets manager cannot decrypt a bot's secret, a check that
  waits on a read that must decrypt, or on the backoff after one,
  answers 503. A check that joins a nudge read able to reuse the last
  decrypt can still get an answer, so the record no longer says that
  every check it cannot answer from memory answers 503.
- A stale entry's checks need a read and answer 503 when the verifier
  cannot confirm within loadTimeout, in the record and in
  openmetadata.yaml.
- The sweepInterval comment in openmetadata.yaml now says a pass is due
  that long after the previous one ends, which the message of
  0ccf370 said it already did.

* Build main's allowed-domain filter tests with the test verifier

Two JwtFilterTest cases from main call the seven-argument test constructor, which this branch
extends with the verifier supplier.

* Describe main's stored MCP tokens and header-checked prompts in the verifier docs

- The verifier's decision record says MCP access tokens are stored and that
  checkValidationsForToken looks them up, and that prompt callbacks, like tool
  callbacks, check the token in the request's Authorization header (#36531).
- Amend the per-request cleanup record: the personal access token loader it
  names is gone, and the verifier reads outside the request entity cache.
- OmCredential.NotStored and the checkValidationsForToken Javadoc name the MCP
  access token lookup and the rule that a provider token never signs in to a bot.
- Every minted token gets its jti in one place; the MCP branch adds only
  client_id.
- MintedTokensAreRecognizedTest mints the MCP access token with a client id, as
  issueAccessToken does, and describes the self-service case as a token minted
  before generateToken became bot-only.
- McpServerUnconfirmedTokenTest sends the prompt caller's token in the header.

* Scope the bot-account rule to the legacy claim flow and name what a callback repeats

- The checkValidationsForToken Javadoc says the rule that a provider token never
  signs in to a bot account belongs to the legacy claim flow, where the code
  applies it.
- The decision record says an MCP tool or prompt callback repeats the
  stored-credential check, and that classify reads no client_id, which is why
  an MCP access token is NotStored like a login token.
- MintedTokensAreRecognizedTest names what it runs: the stored-credential check
  through validateJwtAndGetClaims, and reads back only what is kept for the
  verifier.

* Remove two token tests for a call #36156 made bot-only

Since #36156, POST /users/generateToken mints tokens for bot users only, and
main's test_generateToken_forOwnRegularAccount_forbidden covers that rule.
UserResourceIT.test_selfGeneratedToken_lifecycle called it for a regular
user, so it now gets 403, and MintedTokensAreRecognizedTest had a row for the
same call. Both are removed. test_deleteBotUser_rejectsBotToken and
test_deleteUser_rejectsPersonalAccessToken still cover account deletion.

* Answer an unconfirmed push-feed upgrade with 503 and Retry-After

#36143 authenticates WebSocket upgrades in the upgrade creator, which
the servlet filter chain never reaches. A CredentialUnavailableException
thrown there escaped the creator, and Jetty answered the upgrade with
500. The upgrade now answers 503 with Retry-After, as the servlet path
and the REST and MCP entry points do, and stops the negotiation.

authenticateUpgrade becomes package-private and static, so
OpenMetadataApplicationPushFeedUpgradeTest can register it on an
embedded Jetty server and open the upgrade with the JDK's WebSocket
client. The authenticate Javadoc now lists
CredentialUnavailableException.

* Bound the push-feed upgrade test's handshake at 10 s

The JDK's HttpClient.close() waits for an open handshake, so a server
that accepted the connection and never answered would hold the test,
and the build, until the server closed it. connectTimeout fails the
handshake after 10 s instead, and the 20 s get bound stays above it.

The per-server verifier's decision record names the test in its Guard.

* Test the push-feed upgrade's 401 and 403 answers

OpenMetadataApplicationPushFeedUpgradeTest now also opens upgrades that
authenticate rejects with a HandshakeRejectedException or an
AuthenticationException, and checks the status the client receives.
With the 503 case, each rejection that authenticateUpgrade answers is
tested at the upgrade layer.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

safe to test Add this label to run secure Github workflows on PRs To release Will cherry-pick this PR into the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP prompts/get fails with "Not Authorized" for a valid token

2 participants