Skip to content

A desktop coding agent with free access to frontier models.

TypeScript
37.3 KB
Raw Blame
import { createDenTypeId } from "@omnirush-ee/utils/typeid"
import { afterAll, beforeAll, describe, expect, spyOn, test } from "bun:test"

function seedRequiredEnv(): void {
  process.env.DATABASE_URL = process.env.DATABASE_URL ?? "mysql://root:[email protected]:3306/omnirush_test_pr7"
  process.env.DEN_DB_ENCRYPTION_KEY = process.env.DEN_DB_ENCRYPTION_KEY ?? "local-dev-db-encryption-key-please-change-1234567890"
  process.env.BETTER_AUTH_SECRET = process.env.BETTER_AUTH_SECRET ?? "local-dev-secret-not-for-production-use!!"
  process.env.BETTER_AUTH_URL = process.env.BETTER_AUTH_URL ?? "http://127.0.0.1:8790"
  process.env.CORS_ORIGINS = process.env.CORS_ORIGINS ?? "http://127.0.0.1:8790"
  process.env.DEN_API_PUBLIC_URL = process.env.DEN_API_PUBLIC_URL ?? "http://127.0.0.1:8790"
  process.env.DEN_ALLOW_PRIVATE_MCP_URLS = "1"
}

let db: typeof import("../src/db.js").db
let schema: typeof import("@omnirush-ee/den-db/schema")
let drizzle: typeof import("@omnirush-ee/den-db/drizzle")
let DenEnterpriseMcpOAuthPersistence: typeof import("../src/capability-sources/enterprise-mcp-oauth-persistence.js").DenEnterpriseMcpOAuthPersistence
let createExternalMcpConnection: typeof import("../src/capability-sources/external-mcp-connections.js").createExternalMcpConnection
let confirmExternalMcpIssuerReview: typeof import("../src/capability-sources/external-mcp-connections.js").confirmExternalMcpIssuerReview

const userId = createDenTypeId("user")
const organizationId = createDenTypeId("organization")
const memberId = createDenTypeId("member")
let connection: Awaited<ReturnType<typeof createExternalMcpConnection>>

beforeAll(async () => {
  seedRequiredEnv()
  const modules = await Promise.all([
    import("../src/db.js"),
    import("@omnirush-ee/den-db/schema"),
    import("@omnirush-ee/den-db/drizzle"),
    import("../src/capability-sources/enterprise-mcp-oauth-persistence.js"),
    import("../src/capability-sources/external-mcp-connections.js"),
  ])
  db = modules[0].db
  schema = modules[1]
  drizzle = modules[2]
  DenEnterpriseMcpOAuthPersistence = modules[3].DenEnterpriseMcpOAuthPersistence
  createExternalMcpConnection = modules[4].createExternalMcpConnection
  confirmExternalMcpIssuerReview = modules[4].confirmExternalMcpIssuerReview

  await db.insert(schema.AuthUserTable).values({
    id: userId,
    name: "Enterprise MCP Persistence User",
    email: `enterprise-mcp-persistence+${userId}@test.local`,
  })
  await db.insert(schema.OrganizationTable).values({
    id: organizationId,
    name: "Enterprise MCP Persistence Org",
    slug: `enterprise-mcp-persistence-${organizationId}`,
  })
  await db.insert(schema.MemberTable).values({
    id: memberId,
    organizationId,
    userId,
    role: "admin",
  })
  connection = await createExternalMcpConnection({
    organizationId,
    name: "Enterprise MCP persistence test",
    url: "https://mcp.example.test/mcp",
    authType: "oauth",
    credentialMode: "shared",
    createdByOrgMembershipId: memberId,
    access: { orgWide: true, memberIds: [], teamIds: [] },
  })
})

afterAll(async () => {
  await db.delete(schema.ConnectedAccountTable).where(drizzle.eq(schema.ConnectedAccountTable.organizationId, organizationId))
  await db.delete(schema.OrgOAuthClientTable).where(drizzle.eq(schema.OrgOAuthClientTable.organizationId, organizationId))
  await db.delete(schema.ExternalMcpConnectionAccessGrantTable).where(drizzle.eq(schema.ExternalMcpConnectionAccessGrantTable.organizationId, organizationId))
  await db.delete(schema.ExternalMcpConnectionTable).where(drizzle.eq(schema.ExternalMcpConnectionTable.organizationId, organizationId))
  await db.delete(schema.MemberTable).where(drizzle.eq(schema.MemberTable.organizationId, organizationId))
  await db.delete(schema.OrganizationRoleTable).where(drizzle.eq(schema.OrganizationRoleTable.organizationId, organizationId))
  await db.delete(schema.OrganizationTable).where(drizzle.eq(schema.OrganizationTable.id, organizationId))
  await db.delete(schema.AuthUserTable).where(drizzle.eq(schema.AuthUserTable.id, userId))
})

function context(offsetMs = 30_000) {
  return {
    connectionId: connection.id,
    commitExpiresAt: Date.now() + offsetMs,
    signal: new AbortController().signal,
  }
}

describe("Den enterprise MCP OAuth persistence adapter", () => {
  test("preserves a newer credential and logs rejection only for the revision that was read", async () => {
    const rejected = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP rejected credential",
      url: "https://mcp.example.test/rejected",
      authType: "oauth",
      credentialMode: "shared",
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    await db.update(schema.ExternalMcpConnectionTable)
      .set({ accessToken: "rejected-token", connectedAt: new Date() })
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, rejected.id))
    const current = (await db.select()
      .from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, rejected.id))
      .limit(1))[0]
    if (!current) throw new Error("Expected the rejected credential connection.")
    const { ExternalMcpDiagnosticTracker, createExternalMcpDiagnosticFetch } = await import("../src/capability-sources/external-mcp-diagnostics.js")
    const { appLogger } = await import("../src/observability/logger.js")
    const tracker = new ExternalMcpDiagnosticTracker("invalidation-test-reference")
    const persistence = new DenEnterpriseMcpOAuthPersistence(current, undefined, tracker)
    const rejectionContext = { ...context(), connectionId: current.id }
    const loaded = await persistence.credentials.load(rejectionContext)
    if (!loaded) throw new Error("Expected the saved credential")
    const newerUpdatedAt = new Date(current.updatedAt.getTime() + 1_000)
    await db.update(schema.ExternalMcpConnectionTable).set({
      accessToken: "newer-access-secret",
      refreshToken: "newer-refresh-secret",
      updatedAt: newerUpdatedAt,
    }).where(drizzle.eq(schema.ExternalMcpConnectionTable.id, current.id))
    await createExternalMcpDiagnosticFetch({
      endpoint: current.url,
      tracker,
      fetch: async () => Response.json({ error: "invalid_grant", access_token: "provider-access-secret", refresh_token: "provider-refresh-secret" }, { status: 400 }),
    })("https://identity.example.test/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ grant_type: "refresh_token" }) })
    const logged = spyOn(appLogger, "warn").mockImplementation(() => {})

    try {
      await expect(persistence.credentials.invalidate({
        context: { ...rejectionContext, commitExpiresAt: Date.now() - 1 },
        reason: "provider-rejected",
      })).rejects.toThrow("deadline expired")
      expect(logged).not.toHaveBeenCalled()
      await persistence.credentials.invalidate({
        context: rejectionContext,
        reason: "provider-rejected",
      })
      expect(logged).toHaveBeenCalledTimes(1)
      expect(logged.mock.calls[0]).toEqual([
        "external_mcp_credential_invalidation_skipped",
        expect.objectContaining({
          connection_id: current.id,
          organization_id: organizationId,
          org_membership_id: null,
          reason: "provider-rejected",
          loaded_revision: loaded.revision,
          current_revision: `${current.id}:${newerUpdatedAt.getTime()}`,
          revision_changed: true,
          had_access: true,
          had_refresh: true,
          skip_reason: "revision-changed",
          diagnostic: expect.objectContaining({ httpStatus: 400, providerErrorMessage: expect.stringContaining("invalid_grant") }),
        }),
      ])
      expect(JSON.stringify(logged.mock.calls)).not.toMatch(/newer-access-secret|newer-refresh-secret|provider-access-secret|provider-refresh-secret/)
      const preserved = await persistence.credentials.load(rejectionContext)
      expect(preserved?.tokens.access_token).toBe("newer-access-secret")
      expect(preserved?.tokens.refresh_token).toBe("newer-refresh-secret")
      const withoutRead = new DenEnterpriseMcpOAuthPersistence(current, undefined, tracker)
      await withoutRead.credentials.invalidate({ context: rejectionContext, reason: "post-authorization-validation-failed" })
      expect(logged.mock.calls[1]).toEqual([
        "external_mcp_credential_invalidation_skipped",
        expect.objectContaining({ skip_reason: "no-loaded-revision", reason: "post-authorization-validation-failed" }),
      ])
      expect((await persistence.credentials.load(rejectionContext))?.tokens.access_token).toBe("newer-access-secret")
      logged.mockClear()
      logged.mockImplementationOnce(() => { throw new Error("Synthetic log sink failure") })
      await persistence.credentials.invalidate({ context: rejectionContext, reason: "provider-rejected" })
      expect(logged).toHaveBeenCalledTimes(1)
      expect(logged.mock.calls[0]).toEqual([
        "external_mcp_credential_invalidated",
        expect.objectContaining({
          loaded_revision: preserved?.revision,
          current_revision: preserved?.revision,
          revision_changed: false,
          had_access: true,
          had_refresh: true,
        }),
      ])
    } finally {
      logged.mockRestore()
    }

    const after = (await db.select()
      .from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, rejected.id))
      .limit(1))[0]
    expect(after?.accessToken).toBeNull()
    expect(after?.credentialHealth?.status).toBe("reconnect_required")
    expect(after?.credentialHealth?.reason).toBe("authorization_rejected")
  })

  test("marks issuer mismatches for explicit administrator review", async () => {
    const issuerConnection = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP changed issuer",
      url: "https://mcp.example.test/issuer",
      authType: "oauth",
      credentialMode: "shared",
      oauthConfiguration: {
        version: 1,
        authorizationServerIssuer: "https://login.old.example.test",
        requestedScopes: [],
      },
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    const persistence = new DenEnterpriseMcpOAuthPersistence(issuerConnection)
    await persistence.discovery.invalidate({
      context: {
        connectionId: issuerConnection.id,
        commitExpiresAt: Date.now() + 30_000,
        signal: new AbortController().signal,
      },
      reason: "issuer-mismatch",
    })

    const after = (await db.select()
      .from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, issuerConnection.id))
      .limit(1))[0]
    expect(after?.oauthConfiguration?.authorizationServerIssuer).toBe("https://login.old.example.test")
    expect(after?.oauthIssuerReviewRequiredAt).not.toBeNull()
  })

  test("preserves credentials when an administrator confirms the same live issuer", async () => {
    const issuer = "https://login.same.example.test"
    const sameIssuer = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP same issuer review",
      url: "https://mcp.example.test/same-issuer",
      authType: "oauth",
      credentialMode: "shared",
      oauthConfiguration: { version: 1, authorizationServerIssuer: issuer, requestedScopes: [] },
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    await db.update(schema.ExternalMcpConnectionTable).set({
      accessToken: "still-valid-token",
      connectedAt: new Date(),
      oauthIssuerReviewRequiredAt: new Date(),
    }).where(drizzle.eq(schema.ExternalMcpConnectionTable.id, sameIssuer.id))
    const before = (await db.select().from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, sameIssuer.id)).limit(1))[0]
    if (!before) throw new Error("Expected the same-issuer connection.")

    const result = await confirmExternalMcpIssuerReview({
      organizationId,
      connectionId: sameIssuer.id,
      expectedUpdatedAt: before.updatedAt,
      authorizationServerIssuer: issuer,
    })

    expect(result.status).toBe("confirmed")
    if (result.status !== "confirmed") throw new Error("Expected issuer confirmation.")
    expect(result.issuerChanged).toBe(false)
    expect(result.connection.accessToken).toBe("still-valid-token")
    expect(result.connection.oauthIssuerReviewRequiredAt).toBeNull()
  })

  test("invalidates issuer-bound OAuth state when an administrator confirms a changed live issuer", async () => {
    const changedIssuer = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP changed issuer confirmation",
      url: "https://mcp.example.test/changed-issuer",
      authType: "oauth",
      credentialMode: "per_member",
      oauthConfiguration: {
        version: 1,
        authorizationServerIssuer: "https://login.old.example.test",
        requestedScopes: [],
      },
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    await db.insert(schema.OrgOAuthClientTable).values({
      id: createDenTypeId("orgOAuthClient"),
      organizationId,
      providerId: changedIssuer.id,
      clientId: "issuer-bound-client",
      createdByOrgMembershipId: memberId,
    })
    await db.insert(schema.ConnectedAccountTable).values({
      id: createDenTypeId("connectedAccount"),
      organizationId,
      orgMembershipId: memberId,
      providerId: changedIssuer.id,
      accessToken: "issuer-bound-member-token",
    })
    await db.update(schema.ExternalMcpConnectionTable)
      .set({ oauthIssuerReviewRequiredAt: new Date() })
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, changedIssuer.id))
    const before = (await db.select().from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, changedIssuer.id)).limit(1))[0]
    if (!before) throw new Error("Expected the changed-issuer connection.")

    const result = await confirmExternalMcpIssuerReview({
      organizationId,
      connectionId: changedIssuer.id,
      expectedUpdatedAt: before.updatedAt,
      authorizationServerIssuer: "https://login.new.example.test",
    })

    expect(result.status).toBe("confirmed")
    if (result.status !== "confirmed") throw new Error("Expected issuer confirmation.")
    expect(result.issuerChanged).toBe(true)
    expect(result.reconnectionRequired).toBe(true)
    expect(result.connection.oauthConfiguration?.authorizationServerIssuer).toBe("https://login.new.example.test")
    expect(result.connection.oauthIssuerReviewRequiredAt).toBeNull()
    expect(await db.select().from(schema.ConnectedAccountTable)
      .where(drizzle.eq(schema.ConnectedAccountTable.providerId, changedIssuer.id))).toEqual([])
    expect(await db.select().from(schema.OrgOAuthClientTable)
      .where(drizzle.eq(schema.OrgOAuthClientTable.providerId, changedIssuer.id))).toEqual([])
  })

  test("stores DCR secrets only in encrypted columns and returns the first registration", async () => {
    const persistence = new DenEnterpriseMcpOAuthPersistence(connection)
    const saved = await persistence.clientRegistrations.save({
      context: context(),
      clientInformation: {
        client_id: "registered-client",
        client_secret: "encrypted-client-secret",
        registration_access_token: "must-not-enter-json",
        token_endpoint_auth_method: "client_secret_post",
        issuer: "https://login.example.test",
      },
      source: "dynamic",
    })
    expect(saved.clientInformation.client_id).toBe("registered-client")
    expect(saved.clientInformation.issuer).toBe("https://login.example.test")
    const rows = await db
      .select()
      .from(schema.OrgOAuthClientTable)
      .where(drizzle.and(
        drizzle.eq(schema.OrgOAuthClientTable.organizationId, organizationId),
        drizzle.eq(schema.OrgOAuthClientTable.providerId, connection.id),
      ))
      .limit(1)
    expect(rows[0]?.clientSecret).toBe("encrypted-client-secret")
    expect(JSON.stringify(rows[0]?.extra)).not.toContain("encrypted-client-secret")
    expect(JSON.stringify(rows[0]?.extra)).not.toContain("must-not-enter-json")

    const loser = await persistence.clientRegistrations.save({
      context: context(),
      clientInformation: { client_id: "losing-client" },
      source: "dynamic",
    })
    expect(loser.clientInformation.client_id).toBe("registered-client")
  })

  test("rejects a stale client registration when the selected issuer changes in flight", async () => {
    const originalIssuer = "https://login.registration-old.example.test"
    const replacementIssuer = "https://login.registration-new.example.test"
    const changed = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP registration issuer race",
      url: "https://mcp.example.test/registration-issuer-race",
      authType: "oauth",
      credentialMode: "shared",
      oauthConfiguration: {
        version: 1,
        authorizationServerIssuer: originalIssuer,
        requestedScopes: [],
      },
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    const persistence = new DenEnterpriseMcpOAuthPersistence(changed)
    await db
      .update(schema.ExternalMcpConnectionTable)
      .set({
        oauthConfiguration: {
          ...changed.oauthConfiguration,
          authorizationServerIssuer: replacementIssuer,
        },
      })
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, changed.id))

    await expect(persistence.clientRegistrations.save({
      context: {
        connectionId: changed.id,
        commitExpiresAt: Date.now() + 30_000,
        signal: new AbortController().signal,
      },
      clientInformation: {
        client_id: "stale-registration",
        issuer: originalIssuer,
      },
      redirectUri: "https://app.omnirushlabs.com/api/den/v1/mcp-connections/oauth/callback",
      source: "dynamic",
    })).rejects.toMatchObject({ code: "MCP_OAUTH_CONFIGURATION_CHANGED" })

    expect(await db
      .select()
      .from(schema.OrgOAuthClientTable)
      .where(drizzle.eq(schema.OrgOAuthClientTable.providerId, changed.id))).toEqual([])
  })

  test("isolates concurrent signed PKCE transactions and consumes only the callback winner", async () => {
    const persistence = new DenEnterpriseMcpOAuthPersistence(connection)
    // OAuth discovery always persists before any token exchange; the stored
    // discovery state is what binds the connection to its issuer.
    await persistence.discovery.save({
      context: context(),
      state: {
        authorizationServerUrl: "https://login.example.test",
        authorizationServerMetadata: {
          issuer: "https://login.example.test",
          authorization_endpoint: "https://login.example.test/authorize",
          token_endpoint: "https://login.example.test/token",
          response_types_supported: ["code"],
        },
      },
    })
    const registration = await persistence.clientRegistrations.load(context())
    if (!registration) throw new Error("Expected the seeded OAuth client registration.")
    await persistence.authorizations.begin({
      context: context(),
      id: "signed-state-a",
      codeVerifier: "a".repeat(43),
      expiresAt: Date.now() + 10 * 60_000,
      clientRegistrationRevision: registration.revision,
    })
    await persistence.authorizations.begin({
      context: context(),
      id: "signed-state-b",
      codeVerifier: "b".repeat(43),
      expiresAt: Date.now() + 10 * 60_000,
      clientRegistrationRevision: registration.revision,
    })
    const first = await persistence.authorizations.load({ context: context(), id: "signed-state-a" })
    const second = await persistence.authorizations.load({ context: context(), id: "signed-state-b" })
    expect(first?.codeVerifier).toBe("a".repeat(43))
    expect(second?.codeVerifier).toBe("b".repeat(43))
    const connectionRows = await db
      .select({ pending: schema.ExternalMcpConnectionTable.pendingCodeVerifier })
      .from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, connection.id))
      .limit(1)
    expect(connectionRows[0]?.pending).not.toContain("signed-state-a")
    expect(connectionRows[0]?.pending).not.toContain("signed-state-b")

    if (!first) throw new Error("Expected the first OAuth authorization transaction.")
    await persistence.credentials.save({
      context: context(),
      tokens: {
        access_token: "callback-access-token",
        refresh_token: "callback-refresh-token",
        token_type: "Bearer",
        expires_in: 3_600,
        issuer: "https://login.example.test",
      },
      expiresAt: Date.now() + 3_600_000,
      source: "authorization-code",
      authorization: first.handle,
      clientRegistrationRevision: registration.revision,
    })
    expect(await persistence.authorizations.load({ context: context(), id: "signed-state-a" })).toBeUndefined()
    expect(await persistence.authorizations.load({ context: context(), id: "signed-state-b" })).toBeDefined()
    expect((await persistence.credentials.load(context()))?.tokens).toMatchObject({
      access_token: "callback-access-token",
      issuer: "https://login.example.test",
    })
    const currentCredential = await persistence.credentials.load(context())
    await expect(persistence.credentials.save({
      context: context(),
      tokens: {
        access_token: "wrong-issuer-token",
        token_type: "Bearer",
        issuer: "https://attacker.example.test",
      },
      source: "refresh",
      expectedCredentialRevision: currentCredential?.revision,
    })).rejects.toMatchObject({ code: "MCP_OAUTH_ISSUER_MISMATCH" })
    expect((await persistence.credentials.load(context()))?.tokens.access_token).toBe("callback-access-token")

    await expect(persistence.credentials.save({
      context: context(),
      tokens: { access_token: "late-replay-token", token_type: "Bearer" },
      source: "authorization-code",
      authorization: first.handle,
      clientRegistrationRevision: registration.revision,
    })).rejects.toThrow("missing, expired, or already consumed")
    expect((await persistence.credentials.load(context()))?.tokens.access_token).toBe("callback-access-token")

    // The root trailing-slash alias of the selected issuer is the same
    // authorization server (RFC 8414's one tolerance) and must stay accepted.
    const aliasCredential = await persistence.credentials.load(context())
    await persistence.credentials.save({
      context: context(),
      tokens: {
        access_token: "alias-issuer-token",
        token_type: "Bearer",
        issuer: "https://login.example.test/",
      },
      source: "refresh",
      expectedCredentialRevision: aliasCredential?.revision,
    })
    expect((await persistence.credentials.load(context()))?.tokens.access_token).toBe("alias-issuer-token")
  })

  test("rejects persistence after its lifecycle deadline without changing credentials", async () => {
    const persistence = new DenEnterpriseMcpOAuthPersistence(connection)
    const before = await persistence.credentials.load(context())
    await expect(persistence.credentials.save({
      context: context(-1),
      tokens: { access_token: "must-not-commit", token_type: "Bearer" },
      source: "refresh",
    })).rejects.toThrow("deadline expired")
    const after = await persistence.credentials.load(context())
    expect(after?.tokens.access_token).toBe(before?.tokens.access_token)
  })

  test("rejects late credential and client writes after the connection identity changes", async () => {
    const oldIdentity = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP old identity",
      url: "https://old-mcp.example.test/mcp",
      authType: "oauth",
      credentialMode: "shared",
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    const persistence = new DenEnterpriseMcpOAuthPersistence(oldIdentity)
    await db
      .update(schema.ExternalMcpConnectionTable)
      .set({ url: "https://replacement-mcp.example.test/mcp", updatedAt: new Date() })
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, oldIdentity.id))
    const oldContext = {
      connectionId: oldIdentity.id,
      commitExpiresAt: Date.now() + 30_000,
      signal: new AbortController().signal,
    }

    await expect(persistence.credentials.save({
      context: oldContext,
      tokens: { access_token: "late-enterprise-token", token_type: "Bearer" },
      source: "refresh",
    })).rejects.toThrow("identity changed")
    await expect(persistence.clientRegistrations.save({
      context: oldContext,
      clientInformation: { client_id: "late-enterprise-client" },
      source: "dynamic",
    })).rejects.toThrow("identity changed")

    const rows = await db
      .select()
      .from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, oldIdentity.id))
      .limit(1)
    expect(rows[0]?.accessToken).toBeNull()
    const clients = await db
      .select()
      .from(schema.OrgOAuthClientTable)
      .where(drizzle.eq(schema.OrgOAuthClientTable.providerId, oldIdentity.id))
    expect(clients).toEqual([])
  })

  test("advances a per-member connectedAt only after a fresh authorization callback commits", async () => {
    const perMemberConnection = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP reconnect completion",
      url: "https://mcp.example.test/reconnect",
      authType: "oauth",
      credentialMode: "per_member",
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    const persistence = new DenEnterpriseMcpOAuthPersistence(
      perMemberConnection,
      { orgMembershipId: memberId },
    )
    const reconnectContext = {
      connectionId: perMemberConnection.id,
      commitExpiresAt: Date.now() + 30_000,
      signal: new AbortController().signal,
    }
    const registration = await persistence.clientRegistrations.save({
      context: reconnectContext,
      clientInformation: { client_id: "per-member-reconnect-client" },
      source: "dynamic",
    })
    await persistence.authorizations.begin({
      context: reconnectContext,
      id: "signed-state-per-member-reconnect",
      codeVerifier: "r".repeat(43),
      expiresAt: Date.now() + 600_000,
      clientRegistrationRevision: registration.revision,
    })
    const pending = await persistence.authorizations.load({
      context: reconnectContext,
      id: "signed-state-per-member-reconnect",
    })
    if (!pending) throw new Error("Expected a pending per-member reconnect.")
    const beforeRows = await db
      .select()
      .from(schema.ConnectedAccountTable)
      .where(drizzle.and(
        drizzle.eq(schema.ConnectedAccountTable.orgMembershipId, memberId),
        drizzle.eq(schema.ConnectedAccountTable.providerId, perMemberConnection.id),
      ))
      .limit(1)
    const before = beforeRows[0]
    if (!before) throw new Error("Expected the pending account row.")

    await persistence.credentials.save({
      context: reconnectContext,
      tokens: { access_token: "fresh-member-access", token_type: "Bearer" },
      source: "authorization-code",
      authorization: pending.handle,
      clientRegistrationRevision: registration.revision,
    })

    const afterRows = await db
      .select()
      .from(schema.ConnectedAccountTable)
      .where(drizzle.eq(schema.ConnectedAccountTable.id, before.id))
      .limit(1)
    expect(afterRows[0]?.accessToken).toBe("fresh-member-access")
    expect(afterRows[0]?.connectedAt.getTime()).toBeGreaterThan(before.connectedAt.getTime())
  })

  test("never persists a member token issuer to the shared connection configuration", async () => {
    const memberIssuerConnection = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP member token issuer",
      url: "https://mcp.example.test/member-token-issuer",
      authType: "oauth",
      credentialMode: "per_member",
      oauthConfiguration: { version: 1, authorizationServerIssuer: null, requestedScopes: [] },
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    const persistence = new DenEnterpriseMcpOAuthPersistence(
      memberIssuerConnection,
      { orgMembershipId: memberId },
    )
    const memberContext = {
      connectionId: memberIssuerConnection.id,
      commitExpiresAt: Date.now() + 30_000,
      signal: new AbortController().signal,
    }
    const registration = await persistence.clientRegistrations.save({
      context: memberContext,
      clientInformation: { client_id: "member-issuer-client" },
      source: "dynamic",
    })
    await persistence.authorizations.begin({
      context: memberContext,
      id: "signed-state-member-issuer",
      codeVerifier: "m".repeat(43),
      expiresAt: Date.now() + 600_000,
      clientRegistrationRevision: registration.revision,
    })
    const pending = await persistence.authorizations.load({
      context: memberContext,
      id: "signed-state-member-issuer",
    })
    if (!pending) throw new Error("Expected the pending member authorization.")

    await persistence.credentials.save({
      context: memberContext,
      tokens: {
        access_token: "member-scoped-token",
        token_type: "Bearer",
        issuer: "https://member-supplied.example.test",
      },
      source: "authorization-code",
      authorization: pending.handle,
      clientRegistrationRevision: registration.revision,
    })

    const sharedRow = (await db
      .select()
      .from(schema.ExternalMcpConnectionTable)
      .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, memberIssuerConnection.id))
      .limit(1))[0]
    expect(sharedRow?.oauthConfiguration?.authorizationServerIssuer ?? null).toBeNull()
    expect(sharedRow?.accessToken ?? null).toBeNull()
  })

  test("removes a denied per-member authorization and keeps repeated cleanup idempotent", async () => {
    const perMemberConnection = await createExternalMcpConnection({
      organizationId,
      name: "Enterprise MCP denied callback cleanup",
      url: "https://mcp.example.test/mcp",
      authType: "oauth",
      credentialMode: "per_member",
      createdByOrgMembershipId: memberId,
      access: { orgWide: true, memberIds: [], teamIds: [] },
    })
    const adapter = await import("../src/capability-sources/enterprise-mcp-client-adapter.js")
    const persistence = new DenEnterpriseMcpOAuthPersistence(
      perMemberConnection,
      { orgMembershipId: memberId },
    )
    await persistence.authorizations.begin({
      context: {
        connectionId: perMemberConnection.id,
        commitExpiresAt: Date.now() + 30_000,
        signal: new AbortController().signal,
      },
      id: "signed-state-already-absent",
      codeVerifier: "d".repeat(43),
      expiresAt: Date.now() + 600_000,
    })
    await expect(adapter.abandonExternalMcpAuth(
      perMemberConnection,
      "signed-state-already-absent",
      { orgMembershipId: memberId },
      "req_denial_cleanup",
    )).resolves.toBeUndefined()
    expect(await persistence.authorizations.load({
      context: {
        connectionId: perMemberConnection.id,
        commitExpiresAt: Date.now() + 30_000,
        signal: new AbortController().signal,
      },
      id: "signed-state-already-absent",
    })).toBeUndefined()
    await expect(adapter.abandonExternalMcpAuth(
      perMemberConnection,
      "signed-state-already-absent",
      { orgMembershipId: memberId },
      "req_denial_cleanup_repeat",
    )).resolves.toBeUndefined()
  })

  test("completes signed state, PKCE, token commit, and post-callback MCP validation together", async () => {
    let origin = ""
    const server = Bun.serve({
      port: 0,
      async fetch(request) {
        const url = new URL(request.url)
        if (url.pathname === "/.well-known/oauth-protected-resource/mcp") {
          return Response.json({
            resource: `${origin}/mcp`,
            authorization_servers: [origin],
            scopes_supported: ["tools.read"],
          })
        }
        if (url.pathname === "/.well-known/oauth-authorization-server") {
          return Response.json({
            issuer: origin,
            authorization_endpoint: `${origin}/authorize`,
            token_endpoint: `${origin}/token`,
            registration_endpoint: `${origin}/register`,
            response_types_supported: ["code"],
            grant_types_supported: ["authorization_code", "refresh_token"],
            token_endpoint_auth_methods_supported: ["none"],
            code_challenge_methods_supported: ["S256"],
          })
        }
        if (url.pathname === "/register") {
          const metadata: unknown = await request.json()
          const redirectUris = typeof metadata === "object" && metadata !== null && "redirect_uris" in metadata
            && Array.isArray(metadata.redirect_uris)
            && metadata.redirect_uris.every((value) => typeof value === "string")
            ? metadata.redirect_uris
            : []
          return Response.json({
            client_id: "end-to-end-client",
            token_endpoint_auth_method: "none",
            redirect_uris: redirectUris,
            grant_types: ["authorization_code", "refresh_token"],
            response_types: ["code"],
          }, { status: 201 })
        }
        if (url.pathname === "/token") {
          const form = new URLSearchParams(await request.text())
          expect(form.get("grant_type")).toBe("authorization_code")
          expect(form.get("code")).toBe("approved-code")
          expect(form.get("code_verifier")?.length).toBeGreaterThanOrEqual(43)
          return Response.json({
            access_token: "end-to-end-access-token",
            refresh_token: "end-to-end-refresh-token",
            token_type: "Bearer",
            expires_in: 3_600,
          })
        }
        if (url.pathname === "/mcp") {
          if (request.headers.get("authorization") !== "Bearer end-to-end-access-token") {
            return new Response(null, {
              status: 401,
              headers: {
                "www-authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp", scope="tools.read"`,
              },
            })
          }
          const body = await request.text()
          if (!body) return new Response(null, { status: 202 })
          const rpc: unknown = JSON.parse(body)
          if (typeof rpc !== "object" || rpc === null || !("method" in rpc)) {
            return Response.json({ error: "invalid_request" }, { status: 400 })
          }
          if (rpc.method === "notifications/initialized") return new Response(null, { status: 202 })
          const id = "id" in rpc && (typeof rpc.id === "string" || typeof rpc.id === "number") ? rpc.id : null
          if (rpc.method === "tools/list") {
            return Response.json({
              jsonrpc: "2.0",
              id,
              result: { tools: [] },
            })
          }
          return Response.json({
            jsonrpc: "2.0",
            id,
            result: {
              protocolVersion: "2025-06-18",
              capabilities: { tools: {} },
              serverInfo: { name: "den-enterprise-e2e", version: "1.0.0" },
            },
          })
        }
        return new Response(null, { status: 404 })
      },
    })
    origin = `http://127.0.0.1:${server.port}`
    try {
      const endToEndConnection = await createExternalMcpConnection({
        organizationId,
        name: "Enterprise MCP OAuth e2e",
        url: `${origin}/mcp`,
        authType: "oauth",
        credentialMode: "shared",
        createdByOrgMembershipId: memberId,
        access: { orgWide: true, memberIds: [], teamIds: [] },
      })
      const adapter = await import("../src/capability-sources/enterprise-mcp-client-adapter.js")
      const redirectUri = "https://den.example.test/v1/mcp-connections/callback"
      const signedState = "signed-den-state-end-to-end"
      const started = await adapter.connectExternalMcp(
        endToEndConnection,
        redirectUri,
        signedState,
        undefined,
        "req_enterprise_e2e_start",
      )
      expect(started.status).toBe("needs_auth")
      if (started.status !== "needs_auth") throw new Error("Expected provider authorization to be required.")
      expect(new URL(started.authorizeUrl).searchParams.get("state")).toBe(signedState)

      const refreshedRows = await db
        .select()
        .from(schema.ExternalMcpConnectionTable)
        .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, endToEndConnection.id))
        .limit(1)
      const refreshed = refreshedRows[0]
      if (!refreshed) throw new Error("Expected the OAuth connection after Connect start.")
      await adapter.completeExternalMcpAuth(
        refreshed,
        "approved-code",
        redirectUri,
        undefined,
        "req_enterprise_e2e_callback",
        signedState,
      )
      const committedRows = await db
        .select()
        .from(schema.ExternalMcpConnectionTable)
        .where(drizzle.eq(schema.ExternalMcpConnectionTable.id, endToEndConnection.id))
        .limit(1)
      expect(committedRows[0]?.accessToken).toBe("end-to-end-access-token")
      expect(committedRows[0]?.refreshToken).toBe("end-to-end-refresh-token")
      expect(committedRows[0]?.pendingCodeVerifier).toBeNull()
      expect(committedRows[0]?.credentialHealth?.status).toBe("ready")
    } finally {
      server.stop(true)
    }
  })
})