Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-api): fence mcp-server grant and dcr reads by the live CR uid (R3-H4)

Diego Zacarias524a72e28047
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index cb2c2fbf4..0a6faf059 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.667",
+ "version": "0.1.668",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.667",
+ "version": "0.1.668",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index a96510aea..b552ba4c6 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.667",
+ "version": "0.1.668",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index f52ac4464..136263fa8 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -135,7 +135,8 @@ export interface OAuthClientDecl {
}
export interface RecipeWithOAuthClients {
- metadata?: { name?: string; namespace?: string }
+ /** `uid` is set for an McpServer owner: the installation its grants are sealed with. */
+ metadata?: { name?: string; namespace?: string; uid?: string }
spec?: { oauthClients?: OAuthClientDecl[] }
}
@@ -185,9 +186,10 @@ export interface McpServerOAuthSubject {
grantScope: 'user' | 'context'
contextRef?: string
/**
- * metadata.uid of the McpServer CR, sealing any grant this consent writes to the
- * exact installation (R3-H5). Present when the reader read a live CR; absent for
- * the authorize-url minting paths that never persist a grant.
+ * metadata.uid of the McpServer CR the subject was read from. The callback seals
+ * the grant it writes with it and fences the DCR credential read by it; the
+ * authorize-url mint carries it too but never persists a grant. Absent only when
+ * the CR carried no uid.
*/
crUid?: string
}
@@ -570,7 +572,7 @@ async function handleMcpOAuthCallback(
const exchanged = await exchangeAuthCode(
subject.decl,
subject.namespace,
- claims.mcpServerName,
+ { name: claims.mcpServerName, crUid: subject.crUid },
input,
deps
)
@@ -649,8 +651,8 @@ type ExchangeAuthCodeResult =
async function exchangeAuthCode(
decl: OAuthClientDecl,
secretNamespace: string,
- /** mcp-server name (grant/dynamic-client coordinate); undefined for the recipe lane. */
- serverName: string | undefined,
+ /** mcp-server owner (dynamic-client coordinate + installation); undefined for the recipe lane. */
+ owner: RemoteCredentialOwner | undefined,
input: CallbackInput,
deps: CallbackDeps
): Promise<ExchangeAuthCodeResult> {
@@ -658,14 +660,14 @@ async function exchangeAuthCode(
// (DEC-17), public token client, credentials per `secretSource`. Byte-identical
// baked path is below (unchanged).
if (decl.remote) {
- return exchangeRemoteAuthCode(decl, secretNamespace, serverName, input, deps)
+ return exchangeRemoteAuthCode(decl, secretNamespace, owner, input, deps)
}
// Generic self-hosted lane (`source:'generic'`): knob-configured request over
// the same IP-pinned POST (DEC-17). Credentials per `secretSource` (public or
// k8s-secret). Baked path is below (unchanged).
if (decl.generic) {
- return exchangeGenericAuthCode(decl, secretNamespace, serverName, input, deps)
+ return exchangeGenericAuthCode(decl, secretNamespace, owner, input, deps)
}
// Baked/recipe lane. clientIdRef is always present here (remote is the only
@@ -760,13 +762,13 @@ async function exchangeAuthCode(
async function exchangeRemoteAuthCode(
decl: OAuthClientDecl,
secretNamespace: string,
- serverName: string | undefined,
+ owner: RemoteCredentialOwner | undefined,
input: CallbackInput,
deps: CallbackDeps
): Promise<ExchangeAuthCodeResult> {
// `decl.remote` presence is the branch guard in the caller.
const remote = decl.remote as RemoteClientRouting
- const credResult = await resolveRemoteClientCredential(decl, secretNamespace, serverName, deps)
+ const credResult = await resolveRemoteClientCredential(decl, secretNamespace, owner, deps)
if (!credResult.ok) return { kind: 'secret_missing', secret: credResult.secret }
// PKCE (DEC-1 / §6 #3): the remote lane is ALWAYS S256 — re-derive the verifier
@@ -820,13 +822,13 @@ async function exchangeRemoteAuthCode(
async function exchangeGenericAuthCode(
decl: OAuthClientDecl,
secretNamespace: string,
- serverName: string | undefined,
+ owner: RemoteCredentialOwner | undefined,
input: CallbackInput,
deps: CallbackDeps
): Promise<ExchangeAuthCodeResult> {
// `decl.generic` presence is the branch guard in the caller.
const generic = decl.generic as GenericClientRouting
- const credResult = await resolveRemoteClientCredential(decl, secretNamespace, serverName, deps)
+ const credResult = await resolveRemoteClientCredential(decl, secretNamespace, owner, deps)
if (!credResult.ok) return { kind: 'secret_missing', secret: credResult.secret }
const adapter = buildAdapterFromConfig(generic)
@@ -889,17 +891,31 @@ export type RemoteCredentialResult =
| { ok: true; cred: RemoteClientCredential }
| { ok: false; secret: string }
+/** The McpServer whose `dynamic_clients` row holds a DCR client's credentials. */
+export interface RemoteCredentialOwner {
+ /** McpServer name — the `dynamic_clients` coordinate. */
+ name: string
+ /** metadata.uid of the live CR; undefined when the reader saw none. */
+ crUid: string | undefined
+}
+
/**
* Resolve the remote client's `(clientId, clientSecret)` from the `secretSource`
* discriminator (DEC-18) — the SINGLE place the three remote secret sources are
* read, shared by the exchange (here) and the refresh (`tokenHelper.ts`) so the
* two never drift (D4). Never logs or returns secret material on the error path
- * (names only). `serverName` is the `dynamic_clients` coordinate (DCR only).
+ * (names only). `owner` locates the `dynamic_clients` row (DCR only).
+ *
+ * A DCR row is used only when it is not yet bound (`cr_uid` NULL — pending
+ * between the CR create and the bind, or legacy) or bound to `owner.crUid`. A row
+ * bound to another uid belongs to a gone installation of the same name and is
+ * treated as absent. The check lives here rather than in `getDynamicClient`
+ * because the install saga must still see every row to classify and reclaim it.
*/
export async function resolveRemoteClientCredential(
decl: OAuthClientDecl,
secretNamespace: string,
- serverName: string | undefined,
+ owner: RemoteCredentialOwner | undefined,
deps: { db: DbClient; encryptionKey: Buffer; secretReader: SecretReader }
): Promise<RemoteCredentialResult> {
const source = decl.secretSource
@@ -910,14 +926,16 @@ export async function resolveRemoteClientCredential(
return { ok: true, cred: { clientId: decl.id } }
}
if (source.kind === 'dcr-store') {
- if (!serverName) return { ok: false, secret: `dynamic_clients/${decl.id}` }
+ if (!owner) return { ok: false, secret: `dynamic_clients/${decl.id}` }
const row = await getDynamicClient(deps.db, deps.encryptionKey, {
serverNamespace: secretNamespace,
- serverName,
+ serverName: owner.name,
})
- if (!row) return { ok: false, secret: `dynamic_clients/${serverName}` }
+ if (!row || (row.crUid !== undefined && row.crUid !== owner.crUid)) {
+ return { ok: false, secret: `dynamic_clients/${owner.name}` }
+ }
if (!row.clientSecret) {
- return { ok: false, secret: `dynamic_clients/${serverName}/client_secret` }
+ return { ok: false, secret: `dynamic_clients/${owner.name}/client_secret` }
}
return { ok: true, cred: { clientId: row.clientId, clientSecret: row.clientSecret } }
}
diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.ts
index 67dc697a4..f957da27b 100644
--- a/control-api/src/oauth/mcpServerOAuthSpec.ts
+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts
@@ -52,6 +52,7 @@ export interface McpServerOAuthDecl {
/** Minimal structural shape needed to resolve a server's OAuth grant coordinate. */
export interface McpServerOAuthSpecInput {
+ metadata?: { uid?: unknown }
spec?: {
oauth?: McpServerOAuthDecl
// `spec.contextRef` is REQUIRED + singular on the CRD ("the context this
@@ -68,10 +69,25 @@ export interface ResolvedServerOAuth {
grantScope: GrantScope
/** Authoritative Context of the server (spec.contextRef); undefined if absent. */
contextRef?: string
+ /**
+ * metadata.uid of the CR this resolution was read from — the installation
+ * identity grant reads are fenced by. Undefined when the object carried none.
+ */
+ crUid?: string
}
/**
- * Derive `{ oauthClientId, grantScope, contextRef }` from a McpServer's
+ * The apiserver's `metadata.uid` of a McpServer, or undefined when absent or not
+ * a non-empty string. Never defaulted: an unknown identity must not match a
+ * sealed grant.
+ */
+export function readCrUid(server: McpServerOAuthSpecInput): string | undefined {
+ const uid = server.metadata?.uid
+ return typeof uid === 'string' && uid.length > 0 ? uid : undefined
+}
+
+/**
+ * Derive `{ oauthClientId, grantScope, contextRef, crUid }` from a McpServer's
* `spec.oauth`. Returns null when the server carries no usable OAuth id, so
* callers fail closed. `grantScope` defaults to `'user'` for anything other
* than the explicit `'context'` sentinel (U1: immutable per server, CEL-guarded).
@@ -84,7 +100,7 @@ export function resolveServerOAuth(server: McpServerOAuthSpecInput): ResolvedSer
typeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0
? server.spec.contextRef
: undefined
- return { oauthClientId: oauth.id, grantScope, contextRef }
+ return { oauthClientId: oauth.id, grantScope, contextRef, crUid: readCrUid(server) }
}
/** The coordinates the caller supplies to derive an mcp-server grant key. */
@@ -114,6 +130,11 @@ export interface McpServerGrantKeyCoords {
*
* It intentionally does NOT read the token or touch the DB — it only maps a
* resolved OAuth declaration + coordinates to a key.
+ *
+ * A missing `crUid` never yields null: the key is still built and the store
+ * treats an mcp-server key without a uid as matching no row. Returning null here
+ * would push the grant-existence sweep into its fail-open branch (`exists:true`),
+ * so a revoked token cached in mcp-host would never be evicted.
*/
export function buildMcpServerGrantKey(
resolved: ResolvedServerOAuth,
@@ -130,6 +151,7 @@ export function buildMcpServerGrantKey(
recipeName: coords.mcpServerName,
contextId: resolved.contextRef,
oauthClientId: resolved.oauthClientId,
+ crUid: resolved.crUid,
}
}
if (typeof coords.userId !== 'string' || coords.userId.length === 0) return null
@@ -140,6 +162,7 @@ export function buildMcpServerGrantKey(
recipeName: coords.mcpServerName,
userId: coords.userId,
oauthClientId: resolved.oauthClientId,
+ crUid: resolved.crUid,
}
}
@@ -161,6 +184,8 @@ export interface ResolvedServerOAuthSubject {
grantScope: GrantScope
/** Authoritative Context (spec.contextRef); undefined if absent. */
contextRef?: string
+ /** metadata.uid of the CR this subject was read from; undefined if absent. */
+ crUid?: string
}
/** Extract + type-validate the remote routing block from an untrusted `spec.oauth`. */
@@ -320,6 +345,7 @@ export function resolveServerOAuthSubject(
typeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0
? server.spec.contextRef
: undefined
+ const crUid = readCrUid(server)
// ─── Remote lane (`source:'remote'`) ─────────────────────────────────────
if (oauth.source === 'remote') {
@@ -341,7 +367,7 @@ export function resolveServerOAuthSubject(
decl.clientIdRef = secretSource.clientIdRef
decl.clientSecretRef = secretSource.clientSecretRef
}
- return { decl, grantScope, contextRef }
+ return { decl, grantScope, contextRef, crUid }
}
// ─── Generic self-hosted lane (`source:'generic'`, DEC-28) ────────────────
@@ -365,7 +391,7 @@ export function resolveServerOAuthSubject(
decl.clientIdRef = secretSource.clientIdRef
decl.clientSecretRef = secretSource.clientSecretRef
}
- return { decl, grantScope, contextRef }
+ return { decl, grantScope, contextRef, crUid }
}
// ─── Baked lane (byte-identical to before) ───────────────────────────────
@@ -384,5 +410,6 @@ export function resolveServerOAuthSubject(
},
grantScope,
contextRef,
+ crUid,
}
}
diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.ts
index 479c904e6..d9254b579 100644
--- a/control-api/src/oauth/store.ts
+++ b/control-api/src/oauth/store.ts
@@ -35,6 +35,14 @@ export type OAuthOwnerKind = 'recipe' | 'mcpserver'
*
* `grantKind` is required on every call so each site declares intent — there
* is no implicit default.
+ *
+ * `crUid` is the installation identity of an mcp-server owner (the live CR's
+ * `metadata.uid`). The row readers ({@link getOAuthGrant}, {@link oauthGrantExists})
+ * only return an mcp-server row sealed with that uid or unsealed (legacy), and an
+ * mcp-server key WITHOUT a uid matches nothing: a same-name reinstall gets a new
+ * uid, so a grant consented against the previous installation stays inert even if
+ * its teardown never ran. Ignored for the recipe domain. Locks, deletes and
+ * listings do not apply it (see {@link lockOAuthGrantForRefresh}).
*/
export type OAuthGrantKey =
| {
@@ -45,6 +53,7 @@ export type OAuthGrantKey =
recipeName: string
userId: string
oauthClientId: string
+ crUid?: string
}
| {
grantKind: 'service'
@@ -53,6 +62,7 @@ export type OAuthGrantKey =
recipeNamespace: string
recipeName: string
oauthClientId: string
+ crUid?: string
}
| {
grantKind: 'shared'
@@ -62,6 +72,7 @@ export type OAuthGrantKey =
recipeName: string
contextId: string
oauthClientId: string
+ crUid?: string
}
/** Resolve the owner domain of a key, defaulting to the recipe domain. */
@@ -96,6 +107,8 @@ export interface OAuthGrantRow {
updatedAt: Date
/** True when the user consented to a background workload using this grant. */
background: boolean
+ /** metadata.uid of the McpServer installation the grant was consented against; absent if unsealed. */
+ crUid?: string
}
export type UpsertOAuthGrantInput = OAuthGrantKey & {
@@ -422,7 +435,7 @@ export type GetOAuthGrantInput = OAuthGrantKey & {
const SELECT_COLUMNS = `owner_kind, recipe_namespace, recipe_name, user_id, context_id,
bootstrapped_by_user_id, oauth_client_id, grant_kind,
provider, access_token_encrypted, refresh_token_encrypted,
- access_token_expires_at, updated_at, background`
+ access_token_expires_at, updated_at, background, cr_uid`
interface OAuthGrantDbRow {
owner_kind: OAuthOwnerKind
@@ -439,10 +452,27 @@ interface OAuthGrantDbRow {
access_token_expires_at: Date | null
updated_at: Date
background: boolean
+ cr_uid: string | null
+}
+
+/**
+ * Installation-identity predicate for the row readers, appended to each flavor's
+ * WHERE with `nextParam` as its placeholder index. Returns null when the key can
+ * match no row (an mcp-server key without a uid). Unsealed rows (`cr_uid IS NULL`)
+ * stay visible: a pod that predates install identity writes them during a rollout.
+ */
+function installIdentityFence(
+ input: OAuthGrantKey,
+ nextParam: number
+): { sql: string; params: string[] } | null {
+ if (resolveOwnerKind(input) !== 'mcpserver') return { sql: '', params: [] }
+ if (typeof input.crUid !== 'string' || input.crUid.length === 0) return null
+ return { sql: ` AND (cr_uid = $${nextParam} OR cr_uid IS NULL)`, params: [input.crUid] }
}
/**
- * Read one grant row, decrypting tokens. Returns null when no row exists.
+ * Read one grant row, decrypting tokens. Returns null when no row exists, or when
+ * an mcp-server row belongs to a different installation than `input.crUid`.
*/
export async function getOAuthGrant(
db: DbClient,
@@ -450,6 +480,8 @@ export async function getOAuthGrant(
input: GetOAuthGrantInput
): Promise<OAuthGrantRow | null> {
const ownerKind = resolveOwnerKind(input)
+ const fence = installIdentityFence(input, input.grantKind === 'service' ? 5 : 6)
+ if (!fence) return null
const result =
input.grantKind === 'user'
? await db.query(
@@ -458,8 +490,15 @@ export async function getOAuthGrant(
WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'${
input.requireBackground ? ' AND background = true' : ''
- }`,
- [ownerKind, input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
+ }${fence.sql}`,
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.userId,
+ input.oauthClientId,
+ ...fence.params,
+ ]
)
: input.grantKind === 'shared'
? await db.query(
@@ -467,21 +506,30 @@ export async function getOAuthGrant(
FROM oauth_grants
WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5
- AND grant_kind = 'shared'${input.requireBackground ? ' AND background = true' : ''}`,
+ AND grant_kind = 'shared'${input.requireBackground ? ' AND background = true' : ''}${
+ fence.sql
+ }`,
[
ownerKind,
input.recipeNamespace,
input.recipeName,
input.contextId,
input.oauthClientId,
+ ...fence.params,
]
)
: await db.query(
`SELECT ${SELECT_COLUMNS}
FROM oauth_grants
WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
- AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'`,
- [ownerKind, input.recipeNamespace, input.recipeName, input.oauthClientId]
+ AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'${fence.sql}`,
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.oauthClientId,
+ ...fence.params,
+ ]
)
if (result.rows.length === 0) return null
const row = result.rows[0] as OAuthGrantDbRow
@@ -502,15 +550,19 @@ export async function getOAuthGrant(
accessTokenExpiresAt: row.access_token_expires_at ?? undefined,
updatedAt: row.updated_at,
background: row.background,
+ crUid: row.cr_uid ?? undefined,
}
}
/**
* Existence check without decrypting tokens — for status endpoints that only
- * need to know whether a grant is connected.
+ * need to know whether a grant is connected. Same installation-identity fence as
+ * {@link getOAuthGrant}.
*/
export async function oauthGrantExists(db: DbClient, input: GetOAuthGrantInput): Promise<boolean> {
const ownerKind = resolveOwnerKind(input)
+ const fence = installIdentityFence(input, input.grantKind === 'service' ? 5 : 6)
+ if (!fence) return false
const result =
input.grantKind === 'user'
? await db.query(
@@ -518,16 +570,25 @@ export async function oauthGrantExists(db: DbClient, input: GetOAuthGrantInput):
WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
AND user_id = $4 AND oauth_client_id = $5 AND grant_kind = 'user'${
input.requireBackground ? ' AND background = true' : ''
- }
+ }${fence.sql}
LIMIT 1`,
- [ownerKind, input.recipeNamespace, input.recipeName, input.userId, input.oauthClientId]
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.userId,
+ input.oauthClientId,
+ ...fence.params,
+ ]
)
: input.grantKind === 'shared'
? await db.query(
`SELECT 1 FROM oauth_grants
WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
AND user_id IS NULL AND context_id = $4 AND oauth_client_id = $5
- AND grant_kind = 'shared'${input.requireBackground ? ' AND background = true' : ''}
+ AND grant_kind = 'shared'${input.requireBackground ? ' AND background = true' : ''}${
+ fence.sql
+ }
LIMIT 1`,
[
ownerKind,
@@ -535,14 +596,21 @@ export async function oauthGrantExists(db: DbClient, input: GetOAuthGrantInput):
input.recipeName,
input.contextId,
input.oauthClientId,
+ ...fence.params,
]
)
: await db.query(
`SELECT 1 FROM oauth_grants
WHERE owner_kind = $1 AND recipe_namespace = $2 AND recipe_name = $3
- AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'
+ AND user_id IS NULL AND oauth_client_id = $4 AND grant_kind = 'service'${fence.sql}
LIMIT 1`,
- [ownerKind, input.recipeNamespace, input.recipeName, input.oauthClientId]
+ [
+ ownerKind,
+ input.recipeNamespace,
+ input.recipeName,
+ input.oauthClientId,
+ ...fence.params,
+ ]
)
return result.rows.length > 0
}
@@ -794,6 +862,7 @@ interface RemoteGrantWindowDbRow {
context_id: string | null
oauth_client_id: string
grant_kind: 'user' | 'service' | 'shared'
+ cr_uid: string
}
/**
@@ -802,7 +871,9 @@ interface RemoteGrantWindowDbRow {
* the key is derived from `grant_kind`, independent of provider). The enumeration
* filter admits only `shared` and background `user` grants, so those are the only
* two flavors handled; a `service`/unexpected row throws (fail loud, never mint a
- * malformed key).
+ * malformed key). The key carries the row's own `cr_uid` so the engine's re-read
+ * finds this row; whether that uid is still the live installation is decided by
+ * the engine against the owner CR it reads before refreshing.
*/
function remoteGrantKeyFromRow(row: RemoteGrantWindowDbRow): OAuthGrantKey {
if (row.grant_kind === 'user') {
@@ -814,6 +885,7 @@ function remoteGrantKeyFromRow(row: RemoteGrantWindowDbRow): OAuthGrantKey {
recipeName: row.recipe_name,
userId: row.user_id,
oauthClientId: row.oauth_client_id,
+ crUid: row.cr_uid,
}
}
if (row.grant_kind === 'shared') {
@@ -825,6 +897,7 @@ function remoteGrantKeyFromRow(row: RemoteGrantWindowDbRow): OAuthGrantKey {
recipeName: row.recipe_name,
contextId: row.context_id,
oauthClientId: row.oauth_client_id,
+ crUid: row.cr_uid,
}
}
throw new Error(`unexpected grant_kind for remote proactive candidate: ${row.grant_kind}`)
@@ -849,7 +922,8 @@ function remoteGrantKeyFromRow(row: RemoteGrantWindowDbRow): OAuthGrantKey {
* expiry in `(now+Br, now+Bp]`, and `grant_kind='shared' OR (grant_kind='user' AND
* background=true)` (SEC-5: unattended use only — non-background user grants are
* excluded here as a first line of defense, `requireBackground:true` being the
- * second). Returns the flavored keys; tokens are never read.
+ * second), sealed to an installation (`cr_uid IS NOT NULL`). Returns the flavored
+ * keys; tokens are never read.
*/
export async function listRemoteGrantsInProactiveWindow(
db: DbClient,
@@ -857,7 +931,7 @@ export async function listRemoteGrantsInProactiveWindow(
): Promise<OAuthGrantKey[]> {
const result = await db.query(
`SELECT owner_kind, recipe_namespace, recipe_name, user_id, context_id,
- oauth_client_id, grant_kind
+ oauth_client_id, grant_kind, cr_uid
FROM oauth_grants
WHERE owner_kind = 'mcpserver'
AND provider IN ('remote', 'generic')
@@ -865,6 +939,10 @@ export async function listRemoteGrantsInProactiveWindow(
AND access_token_expires_at > NOW() + ($1::bigint * INTERVAL '1 millisecond')
AND access_token_expires_at <= NOW() + ($2::bigint * INTERVAL '1 millisecond')
AND (grant_kind = 'shared' OR (grant_kind = 'user' AND background = true))
+ -- An unsealed (legacy) row has no installation the sweep could check it
+ -- against: the key built from it would match nothing in the fenced reader.
+ -- It is refreshed only on the reactive path, whose key carries the live uid.
+ AND cr_uid IS NOT NULL
ORDER BY recipe_namespace, recipe_name, oauth_client_id, grant_kind,
user_id NULLS FIRST, context_id NULLS FIRST`,
[window.reactiveBufferMs, window.proactiveBufferMs]
@@ -971,6 +1049,13 @@ export async function claimRemoteGrantForRefresh(
* Deliberately NOT extracted to a shared helper: that would touch the proactive
* claim (hot path, green). If the key semantics change, grep `grant_kind = 'user'`
* / `'shared'` / `'service'` and change all six together.
+ *
+ * One deliberate exception: the installation-identity fence (`cr_uid`,
+ * {@link installIdentityFence}) lives ONLY in the two row readers. It is a read
+ * fence. Deletes must still reach rows of a dead installation (a revoke or a
+ * teardown has to be able to remove them), the locks only serialize — the engine
+ * that runs under them re-reads through the fenced reader — and the refresh UPDATE
+ * only ever follows that fenced read and never writes `cr_uid`.
*/
export async function lockOAuthGrantForRefresh(
txClient: DbClient,
diff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.ts
index 7908bf87f..604f19c2d 100644
--- a/control-api/src/oauth/tokenHelper.ts
+++ b/control-api/src/oauth/tokenHelper.ts
@@ -128,6 +128,15 @@ export async function getAccessToken(
}
if (!recipe) return { kind: 'recipe_not_found' }
+ // A grant sealed with another installation's uid is inert: the owner was
+ // uninstalled and a same-name server now exists. Refreshing it would spend the
+ // old refresh token against the new installation's client (and, for DCR, a
+ // rejected POST would be misread as the new client being invalid). The fenced
+ // reader above cannot catch this when the key came from the row itself (the
+ // proactive sweep) or when the CR was replaced after the caller read it.
+ const ownerCrUid = recipe.metadata?.uid
+ if (grant.crUid !== undefined && grant.crUid !== ownerCrUid) return { kind: 'no_grant' }
+
const decl = recipe.spec?.oauthClients?.find(c => c.id === input.oauthClientId)
if (!decl) return { kind: 'unknown_oauth_client' }
@@ -140,7 +149,7 @@ export async function getAccessToken(
// refresh — surfaces `connect_required` in mcp-host. Derived from the flag,
// NOT heuristically from token presence.
if (!decl.remote.supportsRefresh) return { kind: 'no_grant' }
- return refreshRemoteGrant(grant.refreshToken, decl, input, deps)
+ return refreshRemoteGrant(grant.refreshToken, decl, ownerCrUid, input, deps)
}
// Generic self-hosted lane (`source:'generic'`, DEC-28): same fail-closed
@@ -148,7 +157,7 @@ export async function getAccessToken(
// but the request is composed from the CR knobs (`buildAdapterFromConfig`).
if (decl.generic) {
if (!decl.generic.supportsRefresh) return { kind: 'no_grant' }
- return refreshGenericGrant(grant.refreshToken, decl, input, deps)
+ return refreshGenericGrant(grant.refreshToken, decl, ownerCrUid, input, deps)
}
if (!isKnownOAuthProvider(decl.provider)) {
@@ -266,6 +275,7 @@ export async function getAccessToken(
async function refreshRemoteGrant(
refreshToken: string,
decl: OAuthClientDecl,
+ ownerCrUid: string | undefined,
input: GetAccessTokenInput,
deps: GetAccessTokenDeps
): Promise<GetAccessTokenResult> {
@@ -274,7 +284,7 @@ async function refreshRemoteGrant(
const credResult = await resolveRemoteClientCredential(
decl,
input.recipeNamespace,
- input.recipeName,
+ { name: input.recipeName, crUid: ownerCrUid },
{
db: deps.db,
encryptionKey: deps.encryptionKey,
@@ -339,6 +349,7 @@ async function refreshRemoteGrant(
async function refreshGenericGrant(
refreshToken: string,
decl: OAuthClientDecl,
+ ownerCrUid: string | undefined,
input: GetAccessTokenInput,
deps: GetAccessTokenDeps
): Promise<GetAccessTokenResult> {
@@ -347,7 +358,7 @@ async function refreshGenericGrant(
const credResult = await resolveRemoteClientCredential(
decl,
input.recipeNamespace,
- input.recipeName,
+ { name: input.recipeName, crUid: ownerCrUid },
{
db: deps.db,
encryptionKey: deps.encryptionKey,
diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.ts
index 7e18f5235..7365883b0 100644
--- a/control-api/src/routes/external/oauthCallback.ts
+++ b/control-api/src/routes/external/oauthCallback.ts
@@ -90,15 +90,10 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
}
const resolved = resolveServerOAuthSubject(server)
if (!resolved) return null
- // Seal grants written by this consent to the CR's identity (R3-H5): the uid is
- // the apiserver's, unique per object, so a same-name reinstall's teardown never
- // purges this installation's grant. Undefined only if the CR carried no uid.
- const crUid = (server as { metadata?: { uid?: unknown } }).metadata?.uid
- return {
- namespace: config.mcpServersNamespace,
- ...(typeof crUid === 'string' && crUid ? { crUid } : {}),
- ...resolved,
- }
+ // `resolved.crUid` seals grants written by this consent to the CR's identity:
+ // the uid is the apiserver's, unique per object, so a same-name reinstall's
+ // teardown never purges this installation's grant and its readers never see it.
+ return { namespace: config.mcpServersNamespace, ...resolved }
},
}
diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.ts
index 8cf367bb3..985bcb5eb 100644
--- a/control-api/src/routes/mcpOauth.ts
+++ b/control-api/src/routes/mcpOauth.ts
@@ -16,6 +16,7 @@ import { integrationNotConfigured, isSecretNotFound } from '../oauth/integration
import {
type McpServerOAuthDecl,
buildMcpServerGrantKey,
+ readCrUid,
resolveServerOAuth,
resolveServerOAuthSubject,
} from '../oauth/mcpServerOAuthSpec.js'
@@ -61,7 +62,7 @@ import { extractBearerToken } from '../utils/extractBearerToken.js'
*/
export interface McpServerResource {
- metadata?: { name?: string; namespace?: string }
+ metadata?: { name?: string; namespace?: string; uid?: string }
spec?: {
auth?: { type?: unknown }
oauth?: McpServerOAuthDecl
@@ -72,6 +73,18 @@ export interface McpServerResource {
}
}
+/**
+ * The owner metadata the refresh engine reads. `uid` is the installation identity
+ * a grant was sealed with; it is kept only when it is a non-empty string, so a
+ * malformed value can never equal a sealed grant's uid.
+ */
+function ownerMetadata(server: McpServerResource): RecipeWithOAuthClients['metadata'] {
+ const md = server.metadata
+ if (!md) return undefined
+ const uid = readCrUid(server)
+ return { name: md.name, namespace: md.namespace, ...(uid ? { uid } : {}) }
+}
+
/**
* Normalize a McpServer's single `spec.oauth` object into the
* `{ spec: { oauthClients: [decl] } }` shape the owner-agnostic broker +
@@ -90,7 +103,7 @@ export function normalizeMcpServerOwnerDecl(
if (oauth.source === 'remote') {
const resolved = resolveServerOAuthSubject(server)
if (!resolved) return null
- return { metadata: server.metadata, spec: { oauthClients: [resolved.decl] } }
+ return { metadata: ownerMetadata(server), spec: { oauthClients: [resolved.decl] } }
}
// Generic self-hosted lane (`source:'generic'`, DEC-28): delegate to the SAME
// subject resolver (D4 — no drift with mint + callback) so the refresh reader
@@ -99,7 +112,7 @@ export function normalizeMcpServerOwnerDecl(
if (oauth.source === 'generic') {
const resolved = resolveServerOAuthSubject(server)
if (!resolved) return null
- return { metadata: server.metadata, spec: { oauthClients: [resolved.decl] } }
+ return { metadata: ownerMetadata(server), spec: { oauthClients: [resolved.decl] } }
}
// Baked lane (unchanged; a public baked client is tolerated per E-19.2).
if (typeof oauth.id !== 'string' || typeof oauth.provider !== 'string') return null
@@ -121,7 +134,7 @@ export function normalizeMcpServerOwnerDecl(
normalizedSecretRef = { name: clientSecretRef.name, key: clientSecretRef.key }
}
return {
- metadata: server.metadata,
+ metadata: ownerMetadata(server),
spec: {
oauthClients: [
{
diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.ts
index ec0e3d8df..4eae39362 100644
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@ -88,7 +88,7 @@ interface ContextCR {
}
interface McpServerCR {
- metadata?: { name?: string }
+ metadata?: { name?: string; uid?: string }
spec?: {
enabled?: boolean
auth?: { type?: string }
@@ -393,9 +393,9 @@ export async function resolveMcpServersForAgents(
// Directory identity remains useful when optional MCP catalog enrichment
// is temporarily unavailable — but the degradation must be observable, or
// a broken mcpservers list path reads as "this agent has no tools".
- console.error(
- '[mcpInvocable] mcpservers list failed; directory served without MCP catalog:',
- err instanceof Error ? err.message : String(err)
+ log.error(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'mcpservers list failed; directory served without MCP catalog'
)
}
@@ -425,9 +425,9 @@ export async function resolveMcpServersForAgents(
} catch (err) {
// Preserve the authorized directory DTOs with an empty tool catalog —
// loudly, so a Context-read outage is distinguishable from "no tools".
- console.error(
- '[mcpInvocable] context allowlist load failed; directory served with empty tool catalogs:',
- err instanceof Error ? err.message : String(err)
+ log.error(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'context allowlist load failed; directory served with empty tool catalogs'
)
}
}
diff --git a/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
new file mode 100644
index 000000000..7338b0709
--- /dev/null
+++ b/control-api/test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
@@ -0,0 +1,333 @@
+/**
+ * The DCR credential reader (`resolveRemoteClientCredential`, shared by the
+ * consent exchange and the refresh) only uses a `dynamic_clients` row that is not
+ * yet bound to a CR — the consent can land between the CR create and the bind —
+ * or is bound to the live CR's uid. A row bound to another uid belongs to a
+ * previous installation of the same name and must never be presented to the AS.
+ *
+ * Real producers throughout (T1): the discovery result comes from running the
+ * real `discoverRemoteOAuth` over the DCR-confidential pilot, the CR `spec.oauth`
+ * from the install's `buildRemoteOAuthSpec`, the CR uid from the gateway, and the
+ * `dynamic_clients` rows from the saga's own store calls on a real Postgres. The
+ * RFC 7591 registration response is the only external fixture (a live DCR POST
+ * would create a client at a third party).
+ *
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+ * test/oauth.dcrCredential.installIdentity.realPostgres.integration.test.ts
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'
+import {
+ type CallbackDeps,
+ type CallbackInput,
+ type McpServerOAuthReader,
+ handleOAuthCallback,
+} from '../src/oauth/callback.js'
+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'
+import {
+ bindDynamicClientToResource,
+ insertDynamicClientPending,
+} from '../src/oauth/dynamicClientStore.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
+import { signOAuthState } from '../src/oauth/state.js'
+import { upsertOAuthGrant } from '../src/oauth/store.js'
+import { getAccessToken } from '../src/oauth/tokenHelper.js'
+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import {
+ DCR_CONFIDENTIAL_REGISTRATION_RESPONSE,
+ dcrPilot,
+ makeDiscoveryTransport,
+} from './fixtures/remoteOAuthDiscovery.js'
+import { MockGateway } from './mockGateway.js'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NS = config.mcpServersNamespace
+const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'
+const VALIDATED_IP = '93.184.216.34'
+const REG = DCR_CONFIDENTIAL_REGISTRATION_RESPONSE
+
+/** DCR-confidential pilot whose AS also advertises RFC 9207 (the remote callback requires it). */
+function dcrConfidentialWithIss() {
+ const pilot = dcrPilot('confidential')
+ const as = JSON.parse(pilot.as.json)
+ as.authorization_response_iss_parameter_supported = true
+ return { ...pilot, as: { ...pilot.as, json: JSON.stringify(as) } }
+}
+
+/** Token endpoint that records every POST and always issues tokens. */
+function recordingAs() {
+ const posts: { url: string; body: string }[] = []
+ const transport = async (input: PinnedTransportInput): Promise<PinnedRawResponse> => {
+ posts.push({ url: input.url, body: input.body ?? '' })
+ return {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({
+ access_token: 'NEW-AT',
+ refresh_token: 'NEW-RT',
+ expires_in: 3600,
+ }),
+ }
+ }
+ return { transport, posts }
+}
+
+describeRealPostgres(
+ 'DCR credential reader fenced by the live installation (real Postgres)',
+ () => {
+ const database = `control_api_dcr_identity_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+ let discovery: DiscoveryResult
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+
+ const pilot = dcrConfidentialWithIss()
+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, {
+ transport: makeDiscoveryTransport(pilot),
+ resolveDns: async () => [VALIDATED_IP],
+ })
+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
+ discovery = outcome.result
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ /** Create the DCR CR the install saga would create; returns its gateway-assigned uid. */
+ async function createCr(gateway: MockGateway, name: string): Promise<string> {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: {
+ contextRef: 'ctx-A',
+ auth: { type: 'oauth' },
+ oauth: buildRemoteOAuthSpec(discovery, {
+ clientMode: 'confidential',
+ grantScope: 'user',
+ dynamicClientId: REG.client_id,
+ }),
+ },
+ },
+ NS
+ )
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as {
+ metadata: { uid: string }
+ }
+ return cr.metadata.uid
+ }
+
+ /** The saga's step 0: claim the name with a pending row carrying the registered client. */
+ async function insertPending(name: string): Promise<string> {
+ const installId = randomUUID()
+ const { inserted } = await insertDynamicClientPending(db, KEY, {
+ serverNamespace: NS,
+ serverName: name,
+ issuer: discovery.issuer,
+ clientId: REG.client_id,
+ clientMode: 'confidential',
+ clientSecret: REG.client_secret,
+ registrationAccessToken: REG.registration_access_token,
+ registrationClientUri: REG.registration_client_uri,
+ installId,
+ })
+ expect(inserted).toBe(true)
+ return installId
+ }
+
+ async function bind(name: string, installId: string, crUid: string): Promise<void> {
+ const { bound } = await bindDynamicClientToResource(
+ db,
+ { ownerKind: 'mcpserver', serverNamespace: NS, serverName: name },
+ installId,
+ crUid
+ )
+ expect(bound).toBe(true)
+ }
+
+ /** Install, bind, uninstall WITHOUT teardown, reinstall under the same name. */
+ async function reinstallLeavingOldRow(gateway: MockGateway, name: string) {
+ const oldUid = await createCr(gateway, name)
+ await bind(name, await insertPending(name), oldUid)
+ await gateway.deleteResource('mcpservers', name, NS)
+ const liveUid = await createCr(gateway, name)
+ expect(liveUid).not.toBe(oldUid)
+ return { oldUid, liveUid }
+ }
+
+ /** The production subject reader (`external/oauthCallback.ts`) over the gateway. */
+ function subjectReader(gateway: MockGateway): McpServerOAuthReader {
+ return {
+ async read(name) {
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as Parameters<
+ typeof resolveServerOAuthSubject
+ >[0]
+ const resolved = resolveServerOAuthSubject(cr)
+ return resolved ? { namespace: NS, ...resolved } : null
+ },
+ }
+ }
+
+ function consent(
+ gateway: MockGateway,
+ name: string,
+ transport: ReturnType<typeof recordingAs>['transport']
+ ) {
+ const input: CallbackInput = {
+ oauthClientId: 'remote',
+ code: 'AUTH_CODE',
+ state: signOAuthState(STATE_SECRET, {
+ subjectKind: 'mcp',
+ mcpServerName: name,
+ userId: 'user-9',
+ oauthClientId: REG.client_id,
+ grantKind: 'user',
+ background: false,
+ } as Parameters<typeof signOAuthState>[1]),
+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/remote',
+ iss: discovery.issuer,
+ }
+ const deps: CallbackDeps = {
+ db,
+ recipeReader: { read: async () => null },
+ mcpServerReader: subjectReader(gateway),
+ userContextsReader: async () => ({ contextIds: ['ctx-A'] }),
+ secretReader: { read: async () => ({}) },
+ fetchFn: (async () => {
+ throw new Error('remote lane must not use fetchFn')
+ }) as unknown as typeof fetch,
+ stateSecret: STATE_SECRET,
+ encryptionKey: KEY,
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: transport,
+ }
+ return handleOAuthCallback(input, deps)
+ }
+
+ it('consent with a PENDING row (between CR create and bind) and a live CR exchanges normally', async () => {
+ const gateway = new MockGateway(NS)
+ const name = `dcr-pending-${randomUUID().slice(0, 8)}`
+ await insertPending(name)
+ await createCr(gateway, name)
+ const as = recordingAs()
+
+ const result = await consent(gateway, name, as.transport)
+
+ expect(result.kind).toBe('ok')
+ expect(as.posts).toHaveLength(1)
+ expect(as.posts[0].body).toContain(`client_id=${REG.client_id}`)
+ expect(as.posts[0].body).toContain('client_secret=')
+ })
+
+ it('consent with a row bound to the live CR exchanges normally', async () => {
+ const gateway = new MockGateway(NS)
+ const name = `dcr-live-${randomUUID().slice(0, 8)}`
+ const installId = await insertPending(name)
+ await bind(name, installId, await createCr(gateway, name))
+ const as = recordingAs()
+
+ const result = await consent(gateway, name, as.transport)
+
+ expect(result.kind).toBe('ok')
+ expect(as.posts).toHaveLength(1)
+ })
+
+ it('consent never presents the client of a previous installation of the same name', async () => {
+ const gateway = new MockGateway(NS)
+ const name = `dcr-stale-${randomUUID().slice(0, 8)}`
+ await reinstallLeavingOldRow(gateway, name)
+ const as = recordingAs()
+
+ const result = await consent(gateway, name, as.transport)
+
+ expect(result.kind).toBe('secret_missing')
+ expect(as.posts).toHaveLength(0)
+ })
+
+ it('refresh never presents the client of a previous installation of the same name', async () => {
+ const gateway = new MockGateway(NS)
+ const name = `dcr-stale-refresh-${randomUUID().slice(0, 8)}`
+ const { liveUid } = await reinstallLeavingOldRow(gateway, name)
+ // A grant of the live installation, due for refresh.
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-9',
+ oauthClientId: REG.client_id,
+ provider: 'remote',
+ accessToken: 'OLD-AT',
+ refreshToken: 'OLD-RT',
+ accessTokenExpiresInSec: 10,
+ crUid: liveUid,
+ })
+ const as = recordingAs()
+
+ const result = await getAccessToken(
+ {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-9',
+ oauthClientId: REG.client_id,
+ crUid: liveUid,
+ },
+ {
+ db,
+ recipeReader: {
+ read: async n =>
+ normalizeMcpServerOwnerDecl(
+ (await gateway.getResource('mcpservers', n, NS)) as McpServerResource
+ ),
+ },
+ secretReader: { read: async () => ({}) },
+ fetchFn: (async () => {
+ throw new Error('remote lane must not use fetchFn')
+ }) as unknown as typeof fetch,
+ encryptionKey: KEY,
+ resolveDns: async () => [VALIDATED_IP],
+ pinnedTransport: as.transport,
+ }
+ )
+
+ expect(result.kind).toBe('secret_missing')
+ expect(as.posts).toHaveLength(0)
+ })
+ }
+)
diff --git a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
index 50fd005fd..5b37eae8f 100644
--- a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
@@ -155,6 +155,7 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
recipeName: 'gdrive',
userId: 'user-a',
oauthClientId: 'google-drive',
+ crUid: U,
})
).toBe(false)
expect(
@@ -165,6 +166,7 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
recipeName: 'gdrive',
contextId: 'ctx-A',
oauthClientId: 'google-drive',
+ crUid: U,
})
).toBe(false)
expect(
@@ -175,6 +177,7 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
recipeName: 'gdrive',
userId: 'user-legacy',
oauthClientId: 'google-drive',
+ crUid: U,
})
).toBe(false)
// … the DIFFERENT-uid gdrive grant (the reinstall's) SURVIVES (R3-H5 fence) …
@@ -186,6 +189,7 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
recipeName: 'gdrive',
userId: 'user-reinstall',
oauthClientId: 'google-drive',
+ crUid: U_PRIME,
})
).toBe(true)
// … and the peer server's grant is untouched (scoped purge, no blast radius).
@@ -197,6 +201,7 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
recipeName: 'teamdrive',
userId: 'user-a',
oauthClientId: 'google-drive',
+ crUid: U,
})
).toBe(true)
})
diff --git a/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts b/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
index 308b8454e..c3a03147e 100644
--- a/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
@@ -12,6 +12,7 @@ import {
oauthGrantExists,
upsertOAuthGrant,
} from '../src/oauth/store.js'
+import { MockGateway } from './mockGateway.js'
// T1/T4 — the disconnect composition (buildMcpServerGrantKey → deleteOAuthGrant)
// exercised against grant rows built by the REAL producers (`upsertOAuthGrant` /
@@ -34,15 +35,24 @@ function databaseUrl(baseUrl: string, database: string): string {
const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
const NS = config.mcpServersNamespace
-/** A minimal McpServer CR, resolved through the REAL resolver the endpoint uses. */
-function resolvedFor(grantScope: 'user' | 'context', contextRef: string) {
- const resolved = resolveServerOAuth({
- spec: {
- contextRef,
- oauth: { id: 'google-drive', provider: 'google', grantScope },
+/**
+ * A minimal McpServer CR created in the gateway (which assigns its `metadata.uid`,
+ * as the apiserver does) and resolved through the REAL resolver the endpoint uses.
+ */
+async function resolvedFor(name: string, grantScope: 'user' | 'context', contextRef: string) {
+ const gateway = new MockGateway(NS)
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: { contextRef, oauth: { id: 'google-drive', provider: 'google', grantScope } },
},
- })
- if (!resolved) throw new Error('fixture server did not resolve to OAuth')
+ NS
+ )
+ const resolved = resolveServerOAuth(
+ (await gateway.getResource('mcpservers', name, NS)) as Parameters<typeof resolveServerOAuth>[0]
+ )
+ if (!resolved?.crUid) throw new Error('fixture server did not resolve to OAuth with a uid')
return resolved
}
@@ -75,8 +85,9 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
})
it('user flavor: deletes ONLY the caller-owned grant (a peer on the same server survives)', async () => {
- const resolved = resolvedFor('user', 'ctx-9')
- // Two members each connect the SAME user-scope server (real producer).
+ const resolved = await resolvedFor('gdrive', 'user', 'ctx-9')
+ // Two members each connect the SAME user-scope server (real producer), sealed
+ // with the installation uid as the consent callback does.
for (const userId of ['user-a', 'user-b']) {
await upsertOAuthGrant(db, KEY, {
grantKind: 'user',
@@ -88,6 +99,7 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
provider: 'google',
accessToken: `at-${userId}`,
refreshToken: `rt-${userId}`,
+ crUid: resolved.crUid,
})
}
@@ -99,31 +111,20 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
expect(keyA).not.toBeNull()
await deleteOAuthGrant(db, keyA!)
- // Observable state (T4): user-a's grant is gone, user-b's is untouched.
- expect(
- await oauthGrantExists(db, {
- grantKind: 'user',
- ownerKind: 'mcpserver',
- recipeNamespace: NS,
- recipeName: 'gdrive',
- userId: 'user-a',
- oauthClientId: 'google-drive',
- })
- ).toBe(false)
- expect(
- await oauthGrantExists(db, {
- grantKind: 'user',
- ownerKind: 'mcpserver',
- recipeNamespace: NS,
- recipeName: 'gdrive',
- userId: 'user-b',
- oauthClientId: 'google-drive',
- })
- ).toBe(true)
+ // Observable state (T4), read with the same key derivation the readers use:
+ // user-a's grant is gone, user-b's is untouched.
+ const readKey = (userId: string) =>
+ buildMcpServerGrantKey(resolved, {
+ mcpServersNamespace: NS,
+ mcpServerName: 'gdrive',
+ userId,
+ })!
+ expect(await oauthGrantExists(db, readKey('user-a'))).toBe(false)
+ expect(await oauthGrantExists(db, readKey('user-b'))).toBe(true)
})
it('context flavor: deletes ONLY the target Context grant (a sibling shared grant survives)', async () => {
- const resolved = resolvedFor('context', 'ctx-A')
+ const resolved = await resolvedFor('teamdrive', 'context', 'ctx-A')
// Two DIFFERENT Contexts each bootstrap a shared identity on the SAME server
// (real producer). ctx-B is the sibling that must survive — the mirror of
// the user-flavor case's user-b, so a shared DELETE that lost its
@@ -139,6 +140,7 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
provider: 'google',
accessToken: `shared-at-${contextId}`,
refreshToken: `shared-rt-${contextId}`,
+ crUid: resolved.crUid,
})
expect(inserted).toBe(true)
}
@@ -162,6 +164,7 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
recipeName: 'teamdrive',
contextId: 'ctx-A',
oauthClientId: 'google-drive',
+ crUid: resolved.crUid,
})
).toBe(false)
// … but the sibling ctx-B shared grant on the SAME server SURVIVES. Drop the
@@ -174,6 +177,7 @@ describeRealPostgres('mcp-server grant disconnect composition (real Postgres)',
recipeName: 'teamdrive',
contextId: 'ctx-B',
oauthClientId: 'google-drive',
+ crUid: resolved.crUid,
})
).toBe(true)
})
diff --git a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
index 029574212..5f08d652a 100644
--- a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
@@ -215,7 +215,9 @@ describeRealPostgres('teardownMcpServerOAuthState — fenced by cr_uid (real Pos
)
expect(result.grants).toBe('done')
- const exists = (userId: string) =>
+ // Each row is read by the installation that could see it, so a `false` means
+ // the row is gone rather than merely invisible to a foreign uid.
+ const exists = (userId: string, crUid: string) =>
oauthGrantExists(db, {
grantKind: 'user',
ownerKind: 'mcpserver',
@@ -223,11 +225,12 @@ describeRealPostgres('teardownMcpServerOAuthState — fenced by cr_uid (real Pos
recipeName: name,
userId,
oauthClientId: 'client',
+ crUid,
})
- expect(await exists('user-u')).toBe(false)
- expect(await exists('user-legacy')).toBe(false)
+ expect(await exists('user-u', U)).toBe(false)
+ expect(await exists('user-legacy', U)).toBe(false)
// The reinstall's grant (uid U′) survives (R3-H5).
- expect(await exists('user-reinstall')).toBe(true)
+ expect(await exists('user-reinstall', Uprime)).toBe(true)
})
it('a server with no OAuth state is a clean no-op (none/none, no revoke)', async () => {
diff --git a/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts b/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts
index 5e68e0ab1..cbfe2a003 100644
--- a/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.proactiveRefresh.realPostgres.integration.test.ts
@@ -22,7 +22,6 @@ import type {
import type { RecipeWithOAuthClients } from '../src/oauth/callback.js'
import { listExpiringDynamicClients, upsertDynamicClient } from '../src/oauth/dynamicClientStore.js'
import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
-import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
import {
type OAuthGrantKey,
bootstrapSharedOAuthGrant,
@@ -32,6 +31,8 @@ import {
upsertOAuthGrant,
} from '../src/oauth/store.js'
import { getAccessToken } from '../src/oauth/tokenHelper.js'
+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import { MockGateway } from './mockGateway.js'
const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
const describeRealPostgres = adminUrl ? describe : describe.skip
@@ -89,6 +90,7 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
recipeName: server,
contextId: ctx,
oauthClientId: REMOTE_OAUTH_ID,
+ crUid: uidOf(server),
})
async function seedShared(
@@ -97,6 +99,7 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
provider: string,
expiresInSec: number | undefined
): Promise<void> {
+ await install(server)
await bootstrapSharedOAuthGrant(db, KEY, {
...sharedKey(server, ctx),
bootstrappedByUserId: 'user-1',
@@ -113,6 +116,7 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
background: boolean,
expiresInSec: number
): Promise<void> {
+ await install(server)
await upsertOAuthGrant(db, KEY, {
grantKind: 'user',
ownerKind: 'mcpserver',
@@ -124,6 +128,7 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
accessToken: 'AT',
refreshToken: 'RT',
accessTokenExpiresInSec: expiresInSec,
+ crUid: uidOf(server),
})
// The background column is set elsewhere at consent time; drive it directly
// here (real schema column) to build the background-vs-not distinction.
@@ -137,31 +142,54 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
}
}
- // Remote owner decl produced by the REAL resolver (T1), so the refresh path
- // reads the same public/remote routing the mint + callback do.
- const REMOTE_TOKEN_ENDPOINT = 'https://as.example.com/token'
const REMOTE_VALIDATED_IP = '93.184.216.34'
- function remoteOwnerDecl(): RecipeWithOAuthClients {
- const resolved = resolveServerOAuthSubject({
- spec: {
- contextRef: 'ctx-1',
- oauth: {
- source: 'remote',
- id: REMOTE_OAUTH_ID,
- clientMode: 'public',
- authorizationEndpoint: 'https://as.example.com/authorize',
- tokenEndpoint: REMOTE_TOKEN_ENDPOINT,
- issuer: 'https://as.example.com',
- resource: 'https://as.example.com',
- grantScope: 'user',
- scopes: ['read'],
- bearerInBody: false,
- supportsRefresh: true,
+ // The owner CR lives in a gateway (which assigns its `metadata.uid`, as the
+ // apiserver does) and is read back through the REAL owner normalizer the
+ // refresh engine consumes (T1). Grants are sealed with that uid, as the consent
+ // callback does, and keys carry it, as the readers derive them.
+ const gateway = new MockGateway(NS)
+ const uids = new Map<string, string>()
+ async function install(server: string): Promise<void> {
+ if (uids.has(server)) return
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: server },
+ spec: {
+ contextRef: 'ctx-1',
+ auth: { type: 'oauth' },
+ oauth: {
+ source: 'remote',
+ id: REMOTE_OAUTH_ID,
+ clientMode: 'public',
+ authorizationEndpoint: 'https://as.example.com/authorize',
+ tokenEndpoint: 'https://as.example.com/token',
+ issuer: 'https://as.example.com',
+ resource: 'https://as.example.com',
+ grantScope: 'user',
+ scopes: ['read'],
+ bearerInBody: false,
+ supportsRefresh: true,
+ },
},
},
- })
- if (!resolved) throw new Error('fixture: remote resolve returned null')
- return { spec: { oauthClients: [resolved.decl] } }
+ NS
+ )
+ const cr = (await gateway.getResource('mcpservers', server, NS)) as {
+ metadata: { uid: string }
+ }
+ uids.set(server, cr.metadata.uid)
+ }
+ function uidOf(server: string): string {
+ const uid = uids.get(server)
+ if (!uid) throw new Error(`fixture: ${server} not installed`)
+ return uid
+ }
+ const ownerReader = {
+ read: async (name: string): Promise<RecipeWithOAuthClients | null> =>
+ normalizeMcpServerOwnerDecl(
+ (await gateway.getResource('mcpservers', name, NS)) as McpServerResource
+ ),
}
const constTransport =
(responseJson: string): PinnedTransport =>
@@ -172,7 +200,7 @@ describeRealPostgres('oauth proactive refresh — enumeration + claim (real Post
})
const refreshDeps = (transport: PinnedTransport) => ({
db,
- recipeReader: { read: async () => remoteOwnerDecl() },
+ recipeReader: ownerReader,
secretReader: { read: async () => ({}) },
fetchFn: (async () => {
throw new Error('remote refresh must not use fetchFn')
diff --git a/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts b/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts
new file mode 100644
index 000000000..fcd00fd40
--- /dev/null
+++ b/control-api/test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts
@@ -0,0 +1,192 @@
+/**
+ * The reactive broker builds its grant key from the CR it read (uid U1). If the
+ * server is uninstalled and reinstalled under the same name (uid U2) before the
+ * refresh runs, the fenced reader still finds the U1 grant — the key says U1 —
+ * but the owner the engine reads is now U2. The engine must treat the grant as
+ * inert: no refresh POST with the old refresh token against the new
+ * installation, and no `invalid_client` misread as the new client being broken.
+ *
+ * Real producers (T1): the CR and both uids come from the gateway, the key from
+ * `resolveServerOAuth` + `buildMcpServerGrantKey`, the owner from
+ * `normalizeMcpServerOwnerDecl`, the grant from `upsertOAuthGrant` on a real
+ * Postgres (the reactive slow path takes a real row lock).
+ *
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+ * test/oauth.reactiveRefresh.installIdentity.realPostgres.integration.test.ts
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient, DbTransactionClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { buildMcpServerGrantKey, resolveServerOAuth } from '../src/oauth/mcpServerOAuthSpec.js'
+import { resultToOutcome } from '../src/oauth/proactiveRefreshPolicy.js'
+import { getAccessTokenReactive } from '../src/oauth/reactiveTokenHelper.js'
+import { getOAuthGrant, upsertOAuthGrant } from '../src/oauth/store.js'
+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import { MockGateway } from './mockGateway.js'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NS = config.mcpServersNamespace
+const NAME = 'gdrive-toctou'
+
+async function createCr(
+ gateway: MockGateway
+): Promise<McpServerResource & { metadata: { uid: string } }> {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: NAME },
+ spec: {
+ contextRef: 'ctx-1',
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'google-drive',
+ provider: 'google',
+ clientIdRef: { name: 'google-creds', key: 'client-id' },
+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },
+ grantScope: 'user',
+ },
+ },
+ },
+ NS
+ )
+ return (await gateway.getResource('mcpservers', NAME, NS)) as McpServerResource & {
+ metadata: { uid: string }
+ }
+}
+
+describeRealPostgres(
+ 'reactive refresh — CR replaced after the key was built (real Postgres)',
+ () => {
+ const database = `control_api_reactive_identity_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ it('returns no_grant without a refresh POST when the owner was reinstalled mid-request', async () => {
+ const gateway = new MockGateway(NS)
+ const u1 = await createCr(gateway)
+
+ // Consent against U1; the access token is due for refresh.
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: NAME,
+ userId: 'alice',
+ oauthClientId: 'google-drive',
+ provider: 'google',
+ accessToken: 'AT-U1',
+ refreshToken: 'RT-U1',
+ accessTokenExpiresInSec: 10,
+ crUid: u1.metadata.uid,
+ })
+
+ // The broker derives the key from the CR it read (U1).
+ const resolved = resolveServerOAuth(u1)
+ if (!resolved) throw new Error('fixture: not an OAuth server')
+ const key = buildMcpServerGrantKey(resolved, {
+ mcpServerName: NAME,
+ mcpServersNamespace: NS,
+ userId: 'alice',
+ })
+ if (!key) throw new Error('fixture: no key')
+
+ // The AS rejects the U1 refresh token, as it would against a new installation.
+ const fetchFn = vi.fn(
+ async () =>
+ ({
+ ok: false,
+ status: 401,
+ text: async () => '{"error":"invalid_client"}',
+ json: async () => ({ error: 'invalid_client' }),
+ }) as Response
+ )
+
+ let u2Uid: string | undefined
+ const result = await getAccessTokenReactive(
+ { ...key, requireBackground: false },
+ {
+ db,
+ recipeReader: {
+ read: async name =>
+ normalizeMcpServerOwnerDecl(
+ (await gateway.getResource('mcpservers', name, NS)) as McpServerResource
+ ),
+ },
+ secretReader: {
+ read: async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' }),
+ },
+ fetchFn: fetchFn as unknown as typeof fetch,
+ encryptionKey: KEY,
+ // Between the fast-path read and the locked engine: uninstall + reinstall.
+ runInTransaction: async <T>(
+ work: (txDb: DbTransactionClient) => Promise<T>
+ ): Promise<T> => {
+ await gateway.deleteResource('mcpservers', NAME, NS)
+ u2Uid = (await createCr(gateway)).metadata.uid
+ const client = await dbPool.connect()
+ try {
+ await client.query('BEGIN')
+ const txDb = {
+ query: (t: string, v?: unknown[]) => client.query(t, v),
+ } as unknown as DbTransactionClient
+ const out = await work(txDb)
+ await client.query('COMMIT')
+ return out
+ } catch (err) {
+ await client.query('ROLLBACK')
+ throw err
+ } finally {
+ client.release()
+ }
+ },
+ }
+ )
+
+ expect(u2Uid).toBeDefined()
+ expect(u2Uid).not.toBe(u1.metadata.uid)
+ expect(result).toEqual({ kind: 'no_grant' })
+ expect(resultToOutcome(result)).not.toBe('client_invalid')
+ expect(fetchFn).not.toHaveBeenCalled()
+ // The U1 grant is left as it was: inert, not refreshed.
+ const row = await getOAuthGrant(db, KEY, key)
+ expect(row?.accessToken).toBe('AT-U1')
+ expect(row?.refreshToken).toBe('RT-U1')
+ })
+ }
+)
diff --git a/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts b/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
index 4570e7680..d29448b5b 100644
--- a/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.reactiveRefreshLock.realPostgres.integration.test.ts
@@ -27,7 +27,6 @@ import type {
} from '../src/http/pinnedFetch.js'
import type { RecipeWithOAuthClients } from '../src/oauth/callback.js'
import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
-import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'
import { getAccessTokenReactive } from '../src/oauth/reactiveTokenHelper.js'
import {
type OAuthGrantKey,
@@ -36,6 +35,8 @@ import {
getOAuthGrant,
} from '../src/oauth/store.js'
import { getAccessToken } from '../src/oauth/tokenHelper.js'
+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import { MockGateway } from './mockGateway.js'
const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
const describeRealPostgres = adminUrl ? describe : describe.skip
@@ -55,7 +56,6 @@ const NS = config.mcpServersNamespace
const WINDOW = { proactiveBufferMs: 300_000, reactiveBufferMs: 60_000 }
const IN_WINDOW_SEC = 200 // 60s < 200s ≤ 300s → proactive window AND stale under Bp
const REMOTE_OAUTH_ID = 'https://control.example.com/.well-known/evenfire-mcp-client'
-const REMOTE_TOKEN_ENDPOINT = 'https://as.example.com/token'
const REMOTE_VALIDATED_IP = '93.184.216.34'
describeRealPostgres('oauth reactive refresh — row-lock serialization (real Postgres)', () => {
@@ -93,9 +93,11 @@ describeRealPostgres('oauth reactive refresh — row-lock serialization (real Po
recipeName: server,
contextId: ctx,
oauthClientId: REMOTE_OAUTH_ID,
+ crUid: uidOf(server),
})
async function seedShared(server: string, ctx: string, expiresInSec: number): Promise<void> {
+ await install(server)
await bootstrapSharedOAuthGrant(db, KEY, {
...sharedKey(server, ctx),
bootstrappedByUserId: 'user-1',
@@ -106,27 +108,53 @@ describeRealPostgres('oauth reactive refresh — row-lock serialization (real Po
})
}
- function remoteOwnerDecl(): RecipeWithOAuthClients {
- const resolved = resolveServerOAuthSubject({
- spec: {
- contextRef: 'ctx-1',
- oauth: {
- source: 'remote',
- id: REMOTE_OAUTH_ID,
- clientMode: 'public',
- authorizationEndpoint: 'https://as.example.com/authorize',
- tokenEndpoint: REMOTE_TOKEN_ENDPOINT,
- issuer: 'https://as.example.com',
- resource: 'https://as.example.com',
- grantScope: 'user',
- scopes: ['read'],
- bearerInBody: false,
- supportsRefresh: true,
+ // The owner CR lives in a gateway (which assigns its `metadata.uid`, as the
+ // apiserver does) and is read back through the REAL owner normalizer the
+ // refresh engine consumes (T1). Grants are sealed with that uid, as the consent
+ // callback does, and keys carry it, as the readers derive them.
+ const gateway = new MockGateway(NS)
+ const uids = new Map<string, string>()
+ async function install(server: string): Promise<void> {
+ if (uids.has(server)) return
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: server },
+ spec: {
+ contextRef: 'ctx-1',
+ auth: { type: 'oauth' },
+ oauth: {
+ source: 'remote',
+ id: REMOTE_OAUTH_ID,
+ clientMode: 'public',
+ authorizationEndpoint: 'https://as.example.com/authorize',
+ tokenEndpoint: 'https://as.example.com/token',
+ issuer: 'https://as.example.com',
+ resource: 'https://as.example.com',
+ grantScope: 'user',
+ scopes: ['read'],
+ bearerInBody: false,
+ supportsRefresh: true,
+ },
},
},
- })
- if (!resolved) throw new Error('fixture: remote resolve returned null')
- return { spec: { oauthClients: [resolved.decl] } }
+ NS
+ )
+ const cr = (await gateway.getResource('mcpservers', server, NS)) as {
+ metadata: { uid: string }
+ }
+ uids.set(server, cr.metadata.uid)
+ }
+ function uidOf(server: string): string {
+ const uid = uids.get(server)
+ if (!uid) throw new Error(`fixture: ${server} not installed`)
+ return uid
+ }
+ const ownerReader = {
+ read: async (name: string): Promise<RecipeWithOAuthClients | null> =>
+ normalizeMcpServerOwnerDecl(
+ (await gateway.getResource('mcpservers', name, NS)) as McpServerResource
+ ),
}
/**
@@ -174,7 +202,7 @@ describeRealPostgres('oauth reactive refresh — row-lock serialization (real Po
const reactiveDeps = (transport: PinnedTransport) => ({
db,
- recipeReader: { read: async () => remoteOwnerDecl() },
+ recipeReader: ownerReader,
secretReader: { read: async () => ({}) },
fetchFn: (async () => {
throw new Error('remote refresh must not use fetchFn')
@@ -236,7 +264,7 @@ describeRealPostgres('oauth reactive refresh — row-lock serialization (real Po
{ ...key, requireBackground: false },
{
db: c1Tx,
- recipeReader: { read: async () => remoteOwnerDecl() },
+ recipeReader: ownerReader,
secretReader: { read: async () => ({}) },
fetchFn: (async () => {
throw new Error('remote refresh must not use fetchFn')
diff --git a/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts b/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts
new file mode 100644
index 000000000..113dd7315
--- /dev/null
+++ b/control-api/test/oauth.store.installIdentityFence.realPostgres.integration.test.ts
@@ -0,0 +1,214 @@
+/**
+ * Installation-identity fence on the grant READERS, on a real Postgres.
+ *
+ * A same-name reinstall of an OAuth McpServer gets a new `metadata.uid`. Grants
+ * consented against the previous installation must be invisible to the readers
+ * of the new one (`getOAuthGrant` / `oauthGrantExists`), even if the uninstall
+ * never purged them — otherwise a reinstall that reuses the same `oauth.id`
+ * silently re-authorizes every previous user.
+ *
+ * Fixtures come from the real producers (T1): the two installations are created
+ * in the gateway (which assigns each its uid, as the apiserver does), the reader
+ * keys are derived with `resolveServerOAuth` + `buildMcpServerGrantKey` from the
+ * CR the gateway returns, and the grants are written by the real store writers
+ * sealed with the uid the consent callback would carry.
+ *
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+ * test/oauth.store.installIdentityFence.realPostgres.integration.test.ts
+ */
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { buildMcpServerGrantKey, resolveServerOAuth } from '../src/oauth/mcpServerOAuthSpec.js'
+import {
+ type OAuthGrantKey,
+ bootstrapSharedOAuthGrant,
+ getOAuthGrant,
+ oauthGrantExists,
+ upsertOAuthGrant,
+} from '../src/oauth/store.js'
+import { MockGateway } from './mockGateway.js'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NS = config.mcpServersNamespace
+const OAUTH_ID = 'google-drive'
+
+type ServerCR = Parameters<typeof resolveServerOAuth>[0] & { metadata: { uid: string } }
+
+async function createServer(
+ gateway: MockGateway,
+ name: string,
+ grantScope: 'user' | 'context'
+): Promise<ServerCR> {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: {
+ contextRef: 'ctx-1',
+ auth: { type: 'oauth' },
+ oauth: { id: OAUTH_ID, provider: 'google', grantScope },
+ },
+ },
+ NS
+ )
+ return (await gateway.getResource('mcpservers', name, NS)) as ServerCR
+}
+
+/**
+ * Install `name`, uninstall it, and install it again under the same name: the
+ * gateway gives each installation its own uid, exactly the reinstall shape.
+ */
+async function installThenReinstall(
+ name: string,
+ grantScope: 'user' | 'context'
+): Promise<{ old: ServerCR; live: ServerCR }> {
+ const gateway = new MockGateway(NS)
+ const old = await createServer(gateway, name, grantScope)
+ await gateway.deleteResource('mcpservers', name, NS)
+ const live = await createServer(gateway, name, grantScope)
+ expect(live.metadata.uid).not.toBe(old.metadata.uid)
+ return { old, live }
+}
+
+/** The reader key exactly as the token broker / grant gate / sweep derive it. */
+function readerKey(server: ServerCR, name: string, userId?: string): OAuthGrantKey {
+ const resolved = resolveServerOAuth(server)
+ if (!resolved) throw new Error('fixture: server did not resolve as OAuth')
+ const key = buildMcpServerGrantKey(resolved, {
+ mcpServerName: name,
+ mcpServersNamespace: NS,
+ userId,
+ })
+ if (!key) throw new Error('fixture: no grant key')
+ return key
+}
+
+describeRealPostgres('grant readers fenced by the live installation uid (real Postgres)', () => {
+ const database = `control_api_install_fence_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ async function consentUser(name: string, userId: string, crUid: string | undefined) {
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId,
+ oauthClientId: OAUTH_ID,
+ provider: 'google',
+ accessToken: `at-${userId}`,
+ refreshToken: `rt-${userId}`,
+ accessTokenExpiresInSec: 3600,
+ crUid,
+ })
+ }
+
+ it('a user grant of a previous installation is invisible to the reinstall', async () => {
+ const name = `fence-user-${randomUUID().slice(0, 8)}`
+ const { old, live } = await installThenReinstall(name, 'user')
+ await consentUser(name, 'user-1', old.metadata.uid)
+
+ expect(await getOAuthGrant(db, KEY, readerKey(live, name, 'user-1'))).toBeNull()
+ expect(await oauthGrantExists(db, readerKey(live, name, 'user-1'))).toBe(false)
+ // Control: the row is really there — the installation it was sealed with sees it.
+ expect((await getOAuthGrant(db, KEY, readerKey(old, name, 'user-1')))?.accessToken).toBe(
+ 'at-user-1'
+ )
+ })
+
+ it('a shared grant of a previous installation is invisible to the reinstall', async () => {
+ const name = `fence-shared-${randomUUID().slice(0, 8)}`
+ const { old, live } = await installThenReinstall(name, 'context')
+ const { inserted } = await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ contextId: 'ctx-1',
+ oauthClientId: OAUTH_ID,
+ bootstrappedByUserId: 'user-1',
+ provider: 'google',
+ accessToken: 'at-shared',
+ refreshToken: 'rt-shared',
+ crUid: old.metadata.uid,
+ })
+ expect(inserted).toBe(true)
+
+ expect(await getOAuthGrant(db, KEY, readerKey(live, name))).toBeNull()
+ expect(await oauthGrantExists(db, readerKey(live, name))).toBe(false)
+ expect((await getOAuthGrant(db, KEY, readerKey(old, name)))?.accessToken).toBe('at-shared')
+ })
+
+ it('an unsealed (legacy) grant stays visible to the live installation', async () => {
+ const name = `fence-legacy-${randomUUID().slice(0, 8)}`
+ const { live } = await installThenReinstall(name, 'user')
+ await consentUser(name, 'user-1', undefined)
+
+ const row = await getOAuthGrant(db, KEY, readerKey(live, name, 'user-1'))
+ expect(row?.accessToken).toBe('at-user-1')
+ expect(row?.crUid).toBeUndefined()
+ expect(await oauthGrantExists(db, readerKey(live, name, 'user-1'))).toBe(true)
+ })
+
+ it('a grant of the live installation is visible and reports its uid', async () => {
+ const name = `fence-live-${randomUUID().slice(0, 8)}`
+ const { live } = await installThenReinstall(name, 'user')
+ await consentUser(name, 'user-1', live.metadata.uid)
+
+ const row = await getOAuthGrant(db, KEY, readerKey(live, name, 'user-1'))
+ expect(row?.accessToken).toBe('at-user-1')
+ expect(row?.crUid).toBe(live.metadata.uid)
+ })
+
+ it('an mcp-server reader key without a uid matches no row, sealed or legacy', async () => {
+ const name = `fence-nouid-${randomUUID().slice(0, 8)}`
+ const { live } = await installThenReinstall(name, 'user')
+ await consentUser(name, 'user-sealed', live.metadata.uid)
+ await consentUser(name, 'user-legacy', undefined)
+
+ // The same CR as the gateway returned it, minus its uid.
+ const uidless = { ...live, metadata: {} } as unknown as ServerCR
+ for (const userId of ['user-sealed', 'user-legacy']) {
+ const key = readerKey(uidless, name, userId)
+ expect(await getOAuthGrant(db, KEY, key)).toBeNull()
+ expect(await oauthGrantExists(db, key)).toBe(false)
+ }
+ })
+})
diff --git a/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts b/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
index 67f9ee86b..1a3de3ba8 100644
--- a/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.store.sharedGrants.realPostgres.integration.test.ts
@@ -8,6 +8,7 @@ import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
import {
bootstrapSharedOAuthGrant,
getOAuthGrant,
+ oauthGrantExists,
refreshOAuthGrantTokens,
upsertOAuthGrant,
} from '../src/oauth/store.js'
@@ -27,6 +28,9 @@ function databaseUrl(baseUrl: string, database: string): string {
}
const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+// The McpServer installation these grants were consented against; readers carry
+// the live CR's uid, writers seal with it.
+const INSTALL_UID = 'uid-install-1'
describeRealPostgres('oauth store — shared grants (real Postgres)', () => {
const database = `control_api_shared_grants_${randomUUID().replace(/-/g, '')}`
@@ -63,6 +67,7 @@ describeRealPostgres('oauth store — shared grants (real Postgres)', () => {
recipeName: server,
contextId,
oauthClientId: 'google-drive',
+ crUid: INSTALL_UID,
})
it('bootstrap is first-wins; a token refresh preserves bootstrapped_by and updates tokens', async () => {
@@ -169,6 +174,7 @@ describeRealPostgres('oauth store — shared grants (real Postgres)', () => {
oauthClientId: 'google-drive',
provider: 'google',
accessToken: 'USER-TOKEN',
+ crUid: INSTALL_UID,
})
await bootstrapSharedOAuthGrant(db, KEY, {
...sharedKey(server, 'ctx-1'),
@@ -183,6 +189,7 @@ describeRealPostgres('oauth store — shared grants (real Postgres)', () => {
recipeName: server,
userId: 'user-1',
oauthClientId: 'google-drive',
+ crUid: INSTALL_UID,
})
const sharedGrant = await getOAuthGrant(db, KEY, sharedKey(server, 'ctx-1'))
expect(userGrant?.accessToken).toBe('USER-TOKEN')
diff --git a/control-api/test/oauth.store.sharedGrants.test.ts b/control-api/test/oauth.store.sharedGrants.test.ts
index de4373886..3de700bb6 100644
--- a/control-api/test/oauth.store.sharedGrants.test.ts
+++ b/control-api/test/oauth.store.sharedGrants.test.ts
@@ -39,6 +39,9 @@ const SHARED_KEY = {
oauthClientId: 'google-drive',
}
+// A reader key as `buildMcpServerGrantKey` produces it: it carries the live CR uid.
+const SHARED_READ_KEY = { ...SHARED_KEY, crUid: 'uid-1' }
+
describe('oauth store — shared (context-identity) grants', () => {
it('bootstrapSharedOAuthGrant issues INSERT … ON CONFLICT DO UPDATE fenced by cr_uid, returns inserted', async () => {
const { db, calls } = fakeDb([{ id: 1 }], 1)
@@ -148,25 +151,50 @@ describe('oauth store — shared (context-identity) grants', () => {
access_token_expires_at: null,
updated_at: new Date(),
background: false,
+ cr_uid: 'uid-1',
},
])
- const row = await getOAuthGrant(db, KEY, SHARED_KEY)
+ const row = await getOAuthGrant(db, KEY, SHARED_READ_KEY)
expect(row?.grantKind).toBe('shared')
expect(row?.ownerKind).toBe('mcpserver')
expect(row?.contextId).toBe('ctx-9')
expect(row?.bootstrappedByUserId).toBe('user-1')
expect(row?.accessToken).toBe('A')
+ expect(row?.crUid).toBe('uid-1')
expect(calls[0].text).toContain("grant_kind = 'shared'")
expect(calls[0].text).toContain('context_id = $4')
- expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'ctx-9', 'google-drive'])
+ expect(calls[0].text).toContain('AND (cr_uid = $6 OR cr_uid IS NULL)')
+ expect(calls[0].values).toEqual([
+ 'mcpserver',
+ 'mcp-server',
+ 'gdrive',
+ 'ctx-9',
+ 'google-drive',
+ 'uid-1',
+ ])
})
- it('oauthGrantExists(shared) is scoped to the context key', async () => {
+ it('oauthGrantExists(shared) is scoped to the context key and the installation', async () => {
const { db, calls } = fakeDb([{ '?column?': 1 }])
- const exists = await oauthGrantExists(db, SHARED_KEY)
+ const exists = await oauthGrantExists(db, SHARED_READ_KEY)
expect(exists).toBe(true)
expect(calls[0].text).toContain("grant_kind = 'shared'")
- expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'ctx-9', 'google-drive'])
+ expect(calls[0].text).toContain('AND (cr_uid = $6 OR cr_uid IS NULL)')
+ expect(calls[0].values).toEqual([
+ 'mcpserver',
+ 'mcp-server',
+ 'gdrive',
+ 'ctx-9',
+ 'google-drive',
+ 'uid-1',
+ ])
+ })
+
+ it('an mcp-server reader key without a uid matches nothing and issues no query', async () => {
+ const { db, calls } = fakeDb([{ '?column?': 1 }])
+ expect(await oauthGrantExists(db, SHARED_KEY)).toBe(false)
+ expect(await getOAuthGrant(db, KEY, SHARED_KEY)).toBeNull()
+ expect(calls).toHaveLength(0)
})
it('deleteOAuthGrant(shared) deletes the single shared row by context key', async () => {
@@ -206,8 +234,36 @@ describe('oauth store — owner_kind on user/service ops (recipe domain unchange
recipeName: 'gdrive',
userId: 'user-1',
oauthClientId: 'google-drive',
+ crUid: 'uid-1',
})
expect(calls[0].text).toContain('owner_kind = $1')
- expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'gdrive', 'user-1', 'google-drive'])
+ expect(calls[0].text).toContain('AND (cr_uid = $6 OR cr_uid IS NULL)')
+ expect(calls[0].values).toEqual([
+ 'mcpserver',
+ 'mcp-server',
+ 'gdrive',
+ 'user-1',
+ 'google-drive',
+ 'uid-1',
+ ])
+ })
+
+ it('getOAuthGrant(user) in the recipe domain carries no installation fence', async () => {
+ const { db, calls } = fakeDb()
+ await getOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'leadforge',
+ userId: 'user-1',
+ oauthClientId: 'google-gmail',
+ })
+ expect(calls[0].text).not.toContain('cr_uid =')
+ expect(calls[0].values).toEqual([
+ 'recipe',
+ 'sandbox-recipes',
+ 'leadforge',
+ 'user-1',
+ 'google-gmail',
+ ])
})
})
diff --git a/control-api/test/oauth.tokenHelper.refreshRace.test.ts b/control-api/test/oauth.tokenHelper.refreshRace.test.ts
index 274e1e422..5aa9c759f 100644
--- a/control-api/test/oauth.tokenHelper.refreshRace.test.ts
+++ b/control-api/test/oauth.tokenHelper.refreshRace.test.ts
@@ -6,6 +6,8 @@ import {
} from '../src/oauth/callback.js'
import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'
import { getAccessToken } from '../src/oauth/tokenHelper.js'
+import { type McpServerResource, normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'
+import { MockGateway } from './mockGateway.js'
// R1-B1 — refresh↔DELETE race. A disconnect (DELETE) can land between the token
// read (`getOAuthGrant`) and the refresh write. Refresh MUST NOT resurrect the
@@ -63,9 +65,14 @@ const okRefreshFetch = vi.fn(
* refresh WRITE reports 0 affected rows — the grant was DELETEd concurrently.
* Records every SQL string so the test can assert no INSERT was issued.
*/
-function dbDeletedDuringRefresh() {
+function dbDeletedDuringRefresh(
+ identity: { owner_kind: string; cr_uid: string | null } = {
+ owner_kind: 'recipe',
+ cr_uid: null,
+ }
+) {
const staleRow = {
- owner_kind: 'mcpserver',
+ ...identity,
recipe_namespace: 'sandbox-recipes',
recipe_name: 'gdrive',
user_id: 'user-1',
@@ -100,7 +107,6 @@ describe('getAccessToken — refresh↔DELETE race (R1-B1)', () => {
const result = await getAccessToken(
{
grantKind: 'user',
- ownerKind: 'mcpserver',
recipeNamespace: 'sandbox-recipes',
recipeName: 'gdrive',
userId: 'user-1',
@@ -122,4 +128,69 @@ describe('getAccessToken — refresh↔DELETE race (R1-B1)', () => {
expect(sqls.some(s => s.includes('INSERT INTO oauth_grants'))).toBe(false)
expect(sqls.some(s => s.includes('UPDATE oauth_grants'))).toBe(true)
})
+
+ it('an mcp-server grant sealed with the live CR uid behaves the same', async () => {
+ const gateway = new MockGateway('sandbox-recipes')
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: 'gdrive' },
+ spec: {
+ contextRef: 'ctx-1',
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'salesforce',
+ provider: 'salesforce',
+ clientIdRef: { name: 'salesforce-creds', key: 'client-id' },
+ clientSecretRef: { name: 'salesforce-creds', key: 'client-secret' },
+ scopes: ['api', 'refresh_token'],
+ },
+ },
+ },
+ 'sandbox-recipes'
+ )
+ const server = (await gateway.getResource(
+ 'mcpservers',
+ 'gdrive',
+ 'sandbox-recipes'
+ )) as McpServerResource & { metadata: { uid: string } }
+ const { db, sqls } = dbDeletedDuringRefresh({
+ owner_kind: 'mcpserver',
+ cr_uid: server.metadata.uid,
+ })
+
+ const result = await getAccessToken(
+ {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'gdrive',
+ userId: 'user-1',
+ oauthClientId: 'salesforce',
+ crUid: server.metadata.uid,
+ },
+ {
+ db,
+ recipeReader: {
+ read: async name =>
+ normalizeMcpServerOwnerDecl(
+ (await gateway.getResource(
+ 'mcpservers',
+ name,
+ 'sandbox-recipes'
+ )) as McpServerResource
+ ),
+ },
+ secretReader,
+ fetchFn: okRefreshFetch as unknown as typeof fetch,
+ encryptionKey: KEY,
+ }
+ )
+
+ expect(result.kind).toBe('no_grant')
+ expect(sqls.some(s => s.includes('INSERT INTO oauth_grants'))).toBe(false)
+ // Reaching the UPDATE proves the engine uid check let the sealed grant through (this fake
+ // returns the row to any SELECT, so the SQL fence itself is covered by the real-PG suites).
+ expect(sqls.some(s => s.includes('UPDATE oauth_grants'))).toBe(true)
+ })
})
diff --git a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
index 6dddac38d..46d5dfa9a 100644
--- a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
+++ b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
@@ -132,6 +132,47 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {
])
})
+ // A same-name reinstall gets a new uid. A grant consented against the previous
+ // installation must read as gone, so mcp-host evicts the token it still caches.
+ it('(uid) a grant of a previous installation reports exists:false after a same-name reinstall', async () => {
+ const uidOf = async (name: string) =>
+ ((await gateway.getResource('mcpservers', name, NS)) as { metadata: { uid: string } })
+ .metadata.uid
+ const consent = (userId: string, crUid: string) =>
+ upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive-u',
+ userId,
+ oauthClientId: CLIENT_ID,
+ provider: 'google',
+ accessToken: `at-${userId}`,
+ crUid,
+ })
+
+ seedUserServer('gdrive-u')
+ await consent('alice', await uidOf('gdrive-u'))
+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: true },
+ ])
+
+ // Uninstall without purging the grant, then reinstall under the same name.
+ await gateway.deleteResource('mcpservers', 'gdrive-u', NS)
+ seedUserServer('gdrive-u')
+ await consent('bob', await uidOf('gdrive-u'))
+
+ expect(
+ await resolve([
+ { mcpServerName: 'gdrive-u', userId: 'alice' },
+ { mcpServerName: 'gdrive-u', userId: 'bob' },
+ ])
+ ).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: false },
+ { mcpServerName: 'gdrive-u', userId: 'bob', exists: true },
+ ])
+ })
+
it('(c2) distinguishes two userIds on the SAME server within one batch (real grants)', async () => {
seedUserServer('gdrive-u')
// alice consents; bob does not.
diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.ts
index 5ae3b0405..29bfd1033 100644
--- a/control-api/test/routes.mcpOauth.test.ts
+++ b/control-api/test/routes.mcpOauth.test.ts
@@ -61,6 +61,15 @@ function seedOauthServer(
)
}
+// The uid the gateway assigned to the seeded CR — the installation identity the
+// grant readers are fenced by. Read back from the producer, never invented.
+async function liveUid(gateway: MockGateway, name: string): Promise<string> {
+ const cr = (await gateway.getResource('mcpservers', name, MCP_NS)) as {
+ metadata: { uid: string }
+ }
+ return cr.metadata.uid
+}
+
// Control JWT derived from the REAL minter (T1) — no hand-forged token.
function controlToken(scopes: Array<'oauth:user-token'> = ['oauth:user-token']): string {
return issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], { scopes }).token
@@ -178,7 +187,14 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {
sql.includes('FROM oauth_grants') &&
sql.includes("grant_kind = 'user'")
)
- expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'user-1', 'google-drive'])
+ expect(grantQuery?.[1]).toEqual([
+ 'mcpserver',
+ MCP_NS,
+ 'gdrive',
+ 'user-1',
+ 'google-drive',
+ await liveUid(gateway, 'gdrive'),
+ ])
})
it('404 no_grant when no row exists', async () => {
@@ -244,7 +260,14 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {
sql.includes("grant_kind = 'shared'")
)
// owner, ns, name, contextId(=contextRef), clientId — userId NOT a coordinate.
- expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'ctx-A', 'google-drive'])
+ expect(grantQuery?.[1]).toEqual([
+ 'mcpserver',
+ MCP_NS,
+ 'gdrive',
+ 'ctx-A',
+ 'google-drive',
+ await liveUid(gateway, 'gdrive'),
+ ])
})
// Guardian (T5): a caller with the scope must NOT be able to fetch another
@@ -291,7 +314,14 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {
sql.includes('FROM oauth_grants') &&
sql.includes("grant_kind = 'shared'")
)
- expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'ctx-A', 'google-drive'])
+ expect(grantQuery?.[1]).toEqual([
+ 'mcpserver',
+ MCP_NS,
+ 'gdrive',
+ 'ctx-A',
+ 'google-drive',
+ await liveUid(gateway, 'gdrive'),
+ ])
})
// Fail-closed: a context-flavor server that is missing its CRD-required
@@ -519,7 +549,14 @@ describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', ()
sql.includes('FROM oauth_grants') &&
sql.includes("grant_kind = 'user'")
)
- expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'nobody', 'google-drive'])
+ expect(grantQuery?.[1]).toEqual([
+ 'mcpserver',
+ MCP_NS,
+ 'gdrive',
+ 'nobody',
+ 'google-drive',
+ await liveUid(gateway, 'gdrive'),
+ ])
})
it('200: reports exists:true when the SELECT 1 finds a row', async () => {
@@ -610,7 +647,14 @@ describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', ()
sql.includes("grant_kind = 'shared'")
)
// contextId coordinate is the authoritative ctx-real, NOT the body ctx-foreign.
- expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'team', 'ctx-real', 'google-drive'])
+ expect(grantQuery?.[1]).toEqual([
+ 'mcpserver',
+ MCP_NS,
+ 'team',
+ 'ctx-real',
+ 'google-drive',
+ await liveUid(gateway, 'team'),
+ ])
})
// FIX A: a malformed entry must NOT be dropped (that breaks positional/tuple
diff --git a/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts b/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts
index b8173fc60..84fe8874b 100644
--- a/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts
+++ b/control-api/test/services.access.mcpConnectors.realPostgres.integration.test.ts
@@ -99,6 +99,11 @@ describeRealPostgres('resolveConnectorsForAgents tri-state (real Postgres)', ()
return g
}
+ // The uid the gateway assigned to the server — what the consent callback seals
+ // the grant with and what the gate reads it back by.
+ const uidOf = async (g: MockGateway, name: string) =>
+ ((await g.getResource('mcpservers', name, NS)) as { metadata: { uid: string } }).metadata.uid
+
const statusOf = async (g: MockGateway, userId: string, serverName: string) => {
const agents = await resolveConnectorsForAgents(
g,
@@ -117,6 +122,7 @@ describeRealPostgres('resolveConnectorsForAgents tri-state (real Postgres)', ()
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-u',
+ crUid: await uidOf(g, 'gdrive-u'),
userId: 'alice',
oauthClientId: 'client-gdrive-u',
provider: 'google',
@@ -135,6 +141,7 @@ describeRealPostgres('resolveConnectorsForAgents tri-state (real Postgres)', ()
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-s',
+ crUid: await uidOf(g, 'gdrive-s'),
contextId: 'ctx-1',
oauthClientId: 'client-gdrive-s',
bootstrappedByUserId: 'bob',
@@ -152,6 +159,7 @@ describeRealPostgres('resolveConnectorsForAgents tri-state (real Postgres)', ()
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-x',
+ crUid: await uidOf(g, 'gdrive-x'),
userId: 'carol',
oauthClientId: 'client-gdrive-x',
provider: 'google',
diff --git a/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts
index 6b17a86d7..868aa44b0 100644
--- a/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts
+++ b/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts
@@ -87,6 +87,11 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
return g
}
+ // The uid the gateway assigned to the server — what the consent callback seals
+ // the grant with and what the gate reads it back by.
+ const uidOf = async (g: MockGateway, name: string) =>
+ ((await g.getResource('mcpservers', name, NS)) as { metadata: { uid: string } }).metadata.uid
+
const list = async (g: MockGateway, userId: string) =>
(await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], userId, db)).map(s => s.name)
@@ -99,6 +104,7 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-u',
+ crUid: await uidOf(g, 'gdrive-u'),
userId: 'alice',
oauthClientId: CLIENT_ID,
provider: 'google',
@@ -118,6 +124,7 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-s',
+ crUid: await uidOf(g, 'gdrive-s'),
contextId: 'ctx-1',
oauthClientId: CLIENT_ID,
bootstrappedByUserId: 'bob',
@@ -140,6 +147,7 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-w',
+ crUid: await uidOf(g, 'gdrive-w'),
userId: 'dave',
oauthClientId: CLIENT_ID,
provider: 'google',
@@ -154,6 +162,7 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-w',
+ crUid: await uidOf(g, 'gdrive-w'),
contextId: 'ctx-1',
oauthClientId: CLIENT_ID,
bootstrappedByUserId: 'erin',
@@ -171,6 +180,7 @@ describeRealPostgres('mcpInvocable grant-presence gate (real Postgres)', () => {
ownerKind: 'mcpserver',
recipeNamespace: NS,
recipeName: 'gdrive-x',
+ crUid: await uidOf(g, 'gdrive-x'),
userId: 'carol',
oauthClientId: CLIENT_ID,
provider: 'google',
diff --git a/control-api/test/services.access.mcpInvocable.grantGate.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.test.ts
index b6abe3dba..351784421 100644
--- a/control-api/test/services.access.mcpInvocable.grantGate.test.ts
+++ b/control-api/test/services.access.mcpInvocable.grantGate.test.ts
@@ -142,6 +142,9 @@ describe('resolveInvocableMcpServersForContexts — rpc-proxy grant-presence gat
recipeName: 'gdrive',
userId: CALLER,
oauthClientId: 'google-drive',
+ // The installation identity comes from the listed CR (gateway-assigned uid).
+ crUid: ((await g.getResource('mcpservers', 'gdrive', NS)) as { metadata: { uid: string } })
+ .metadata.uid,
})
})
@@ -179,6 +182,9 @@ describe('resolveInvocableMcpServersForContexts — context (shared) flavor', ()
recipeName: 'gdrive-shared',
contextId: 'ctx-authoritative', // server's spec.contextRef, NOT the scoped ctx-team
oauthClientId: 'google-drive',
+ crUid: (
+ (await g.getResource('mcpservers', 'gdrive-shared', NS)) as { metadata: { uid: string } }
+ ).metadata.uid,
})
// Shared key must not carry a userId — invocability is team-wide.
expect(key).not.toHaveProperty('userId')
diff --git a/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts
new file mode 100644
index 000000000..b62692038
--- /dev/null
+++ b/control-api/test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts
@@ -0,0 +1,264 @@
+/**
+ * The proactive refresh sweep must never spend the refresh token of a grant
+ * consented against a previous installation of a same-name McpServer. The sweep
+ * enumerates grants straight from `oauth_grants`, so the row reader alone cannot
+ * tell a dead installation from the live one; the engine compares the grant's
+ * sealed uid with the owner CR it reads before refreshing.
+ *
+ * Observable (T4): POSTs reaching the token endpoint, the sweep summary, and the
+ * persisted rows. Without the check the dead grant's refresh is POSTed, the AS
+ * rejects it, and the sweep reports `client_invalid` against a healthy server.
+ *
+ * Real producers (T1): the sweep runs end-to-end on a real Postgres against the
+ * gateway (which assigns each installation its uid); the CR `spec.oauth` comes
+ * from the install's `buildRemoteOAuthSpec` over a real `discoverRemoteOAuth`
+ * result; grants are written by the store writers sealed as the consent callback
+ * seals them. Only the network edge of `pinnedFetch` (DNS + socket) is replaced.
+ *
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+ * test/services.oauthProactiveRefreshCron.installIdentity.realPostgres.integration.test.ts
+ */
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient, DbTransactionClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import type { K8sGateway } from '../src/k8s.js'
+import { buildCimdDocument } from '../src/oauth/cimd.js'
+import { type DiscoveryResult, discoverRemoteOAuth } from '../src/oauth/discovery.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { bootstrapSharedOAuthGrant, getOAuthGrant } from '../src/oauth/store.js'
+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'
+import { runProactiveRefreshSweep } from '../src/services/oauthProactiveRefreshCron.js'
+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
+import { MockGateway } from './mockGateway.js'
+
+const VALIDATED_IP = '93.184.216.34'
+
+// Token endpoint behind the pinned transport. A dead installation's refresh token
+// is rejected the way an AS rejects credentials it no longer recognises.
+const tokenEndpoint = vi.hoisted(() => ({ posts: [] as { url: string; body: string }[] }))
+
+vi.mock('../src/http/pinnedFetch.js', async () => {
+ const actual = await vi.importActual<typeof import('../src/http/pinnedFetch.js')>(
+ '../src/http/pinnedFetch.js'
+ )
+ return {
+ ...actual,
+ // Only calls that would reach the real network (the sweep injects no transport)
+ // are redirected; callers that bring their own transport keep it.
+ pinnedFetch: (url: string, field: string, options: Parameters<typeof actual.pinnedFetch>[2]) =>
+ options?.transport
+ ? actual.pinnedFetch(url, field, options)
+ : actual.pinnedFetch(url, field, {
+ ...options,
+ resolveDns: async () => ['93.184.216.34'],
+ transport: async input => {
+ const body = input.body ?? ''
+ tokenEndpoint.posts.push({ url: input.url, body })
+ if (new URLSearchParams(body).get('refresh_token') === 'RT-DEAD') {
+ return {
+ status: 401,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({ error: 'invalid_client' }),
+ }
+ }
+ return {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ bodyText: JSON.stringify({
+ access_token: 'NEW-AT',
+ refresh_token: 'NEW-RT',
+ expires_in: 3600,
+ }),
+ }
+ },
+ }),
+ }
+})
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NS = config.mcpServersNamespace
+const CONTEXT = 'ctx-cron'
+const OPTS = { proactiveBufferMs: 300_000, reactiveBufferMs: 60_000, dcrWarnMs: 604_800_000 }
+const IN_WINDOW_SEC = 200 // Br < 200s ≤ Bp
+
+describeRealPostgres('proactive refresh sweep — installation identity (real Postgres)', () => {
+ const database = `control_api_cron_identity_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+ let discovery: DiscoveryResult
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+
+ const outcome = await discoverRemoteOAuth(PILOTS.notion.mcpUrl, {
+ transport: makeDiscoveryTransport(PILOTS.notion),
+ resolveDns: async () => [VALIDATED_IP],
+ })
+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
+ discovery = outcome.result
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ const oauthId = () => buildCimdDocument('https://control.example.com').client_id
+
+ async function createCr(gateway: MockGateway, name: string): Promise<string> {
+ await gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: {
+ contextRef: CONTEXT,
+ auth: { type: 'oauth' },
+ oauth: buildRemoteOAuthSpec(discovery, {
+ clientMode: 'public',
+ grantScope: 'context',
+ cimdClientId: oauthId(),
+ }),
+ },
+ },
+ NS
+ )
+ const cr = (await gateway.getResource('mcpservers', name, NS)) as { metadata: { uid: string } }
+ return cr.metadata.uid
+ }
+
+ async function consentShared(name: string, crUid: string | undefined, refreshToken: string) {
+ const { inserted } = await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ contextId: CONTEXT,
+ oauthClientId: oauthId(),
+ bootstrappedByUserId: 'user-1',
+ provider: 'remote',
+ accessToken: `AT-${refreshToken}`,
+ refreshToken,
+ accessTokenExpiresInSec: IN_WINDOW_SEC,
+ crUid,
+ })
+ expect(inserted).toBe(true)
+ }
+
+ const sharedKey = (name: string, crUid: string) => ({
+ grantKind: 'shared' as const,
+ ownerKind: 'mcpserver' as const,
+ recipeNamespace: NS,
+ recipeName: name,
+ contextId: CONTEXT,
+ oauthClientId: oauthId(),
+ crUid,
+ })
+
+ function sweep(gateway: MockGateway) {
+ return runProactiveRefreshSweep(gateway as unknown as K8sGateway, OPTS, {
+ db,
+ runInTransaction: async <T>(work: (txDb: DbTransactionClient) => Promise<T>): Promise<T> => {
+ const client = await dbPool.connect()
+ try {
+ await client.query('BEGIN')
+ const txDb = {
+ query: (t: string, v?: unknown[]) => client.query(t, v),
+ } as unknown as DbTransactionClient
+ const result = await work(txDb)
+ await client.query('COMMIT')
+ return result
+ } catch (err) {
+ await client.query('ROLLBACK')
+ throw err
+ } finally {
+ client.release()
+ }
+ },
+ encryptionKey: KEY,
+ fetchFn: (async () => {
+ throw new Error('remote refresh must not use fetchFn')
+ }) as unknown as typeof fetch,
+ })
+ }
+
+ it('refreshes the live installation grant and never POSTs the dead installation one', async () => {
+ const gateway = new MockGateway(NS)
+
+ // `cron-dead`: consented, then uninstalled without purging the grant and
+ // reinstalled under the same name.
+ const deadUid = await createCr(gateway, 'cron-dead')
+ await consentShared('cron-dead', deadUid, 'RT-DEAD')
+ await gateway.deleteResource('mcpservers', 'cron-dead', NS)
+ const reinstalledUid = await createCr(gateway, 'cron-dead')
+ expect(reinstalledUid).not.toBe(deadUid)
+
+ // `cron-live`: a healthy installation whose grant is due.
+ const liveUid = await createCr(gateway, 'cron-live')
+ await consentShared('cron-live', liveUid, 'RT-LIVE')
+
+ tokenEndpoint.posts.length = 0
+ const summary = await sweep(gateway)
+
+ expect(summary.candidates).toBe(2)
+ expect(summary.outcomes.ok).toBe(1)
+ expect(summary.outcomes.no_grant).toBe(1)
+ expect(summary.outcomes.client_invalid).toBe(0)
+ expect(summary.dcrClientInvalidServers).toEqual([])
+
+ expect(tokenEndpoint.posts).toHaveLength(1)
+ expect(tokenEndpoint.posts[0].body).toContain('refresh_token=RT-LIVE')
+
+ // The live grant was renewed; the dead one is untouched (inert, not refreshed).
+ expect((await getOAuthGrant(db, KEY, sharedKey('cron-live', liveUid)))?.accessToken).toBe(
+ 'NEW-AT'
+ )
+ const dead = await getOAuthGrant(db, KEY, sharedKey('cron-dead', deadUid))
+ expect(dead?.accessToken).toBe('AT-RT-DEAD')
+ expect(dead?.refreshToken).toBe('RT-DEAD')
+ })
+
+ it('leaves an unsealed (legacy) grant to the reactive path: not enumerated, not POSTed', async () => {
+ await dbPool.query('DELETE FROM oauth_grants')
+ const gateway = new MockGateway(NS)
+ await createCr(gateway, 'cron-legacy')
+ await consentShared('cron-legacy', undefined, 'RT-LEGACY')
+
+ tokenEndpoint.posts.length = 0
+ const summary = await sweep(gateway)
+
+ expect(summary.candidates).toBe(0)
+ expect(summary.outcomes.no_grant).toBe(0)
+ expect(summary.outcomes.ok).toBe(0)
+ expect(tokenEndpoint.posts).toHaveLength(0)
+ const { rows } = await dbPool.query(
+ `SELECT refresh_token_encrypted IS NOT NULL AS has_rt, cr_uid FROM oauth_grants
+ WHERE recipe_name = 'cron-legacy'`
+ )
+ expect(rows).toEqual([{ has_rt: true, cr_uid: null }])
+ })
+})