Skip to content

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

TypeScript
21.8 KB
Raw Blame
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { apiGet } from '../../lib/api'
import {
  PublishScopeProvider,
  resetPublishScopeCache,
  usePublishScope,
} from '../../lib/hooks/usePublishScope'
import {
  __resetRegistryCapabilityCacheForTests,
  useRegistryCapability,
} from '../../lib/hooks/useRegistryCapability'
import {
  __resetReadRequestCacheForTests,
  getReadRequestPrincipal,
} from '../../lib/readRequestCache'
import { AuthProvider, useAuth } from '../AuthContext'
import { ToastProvider } from '../Toast'

const replaceMock = vi.fn()

vi.mock('next/navigation', () => ({
  useRouter: () => ({ replace: replaceMock }),
}))

function response(status: number, body: unknown = {}) {
  return {
    ok: status >= 200 && status < 300,
    status,
    statusText: status === 401 ? 'Unauthorized' : 'OK',
    json: async () => body,
    text: async () => JSON.stringify(body),
  } as Response
}

function ExpireSessionButton({ repeated = false }: { repeated?: boolean }) {
  useAuth()
  return (
    <button
      type="button"
      onClick={() => {
        const requests = repeated
          ? [apiGet('/api/v1/admin/hosts'), apiGet('/api/v1/admin/llm-models')]
          : [apiGet('/api/v1/admin/hosts')]
        void Promise.allSettled(requests)
      }}
    >
      Expire session
    </button>
  )
}

function CheckAuthButton() {
  const { checkAuth } = useAuth()
  return (
    <button type="button" onClick={() => void checkAuth()}>
      Check auth
    </button>
  )
}

function LoginButton() {
  const { login } = useAuth()
  return (
    <button type="button" onClick={() => void login('admin-b', 'password')}>
      Log in
    </button>
  )
}

function AuthUserProbe() {
  const { authState } = useAuth()
  return <div data-testid="auth-user">{authState.username || 'signed-out'}</div>
}

function AuthIdentityProbe() {
  const { authState } = useAuth()
  return (
    <>
      <div data-testid="auth-id">{authState.id}</div>
      <div data-testid="auth-username">{authState.username}</div>
      <div data-testid="auth-email">{authState.email}</div>
      <div data-testid="auth-logged-in">{String(authState.isLoggedIn)}</div>
    </>
  )
}

function meResponse(me: Record<string, unknown>): Response {
  return new Response(JSON.stringify({ me }), {
    status: 200,
    headers: { 'content-type': 'application/json' },
  })
}

function AuthProbe() {
  useAuth()
  return <div>Auth mounted</div>
}

function PublishScopeProbe() {
  const { loading, scope } = usePublishScope()
  return <div data-testid="publish-scope">{loading ? 'loading' : (scope?.orgName ?? 'none')}</div>
}

function RegistryCapabilityProbe() {
  const { capability, loading } = useRegistryCapability()
  return (
    <div data-testid="registry-capability">
      {loading ? 'loading' : (capability?.orgName ?? 'none')}
    </div>
  )
}

function LogoutButton() {
  const { logout } = useAuth()
  return (
    <button type="button" onClick={() => void logout()}>
      Log out
    </button>
  )
}

afterEach(() => {
  cleanup()
  resetPublishScopeCache()
  __resetRegistryCapabilityCacheForTests()
  window.localStorage.clear()
  vi.unstubAllGlobals()
  __resetReadRequestCacheForTests()
})

describe('AuthProvider session expiry handling', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    resetPublishScopeCache()
    __resetRegistryCapabilityCacheForTests()
    window.history.pushState({}, '', '/')
  })

  it('shows one session-expired toast and redirects to login for repeated 401s', async () => {
    window.history.pushState({}, '', '/agents/chatllm/env#runtime')
    window.localStorage.setItem('controlUiAdminToken', 'expired-token')
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(response(200, { me: { id: 'admin', role: 'admin' } }))
      .mockResolvedValue(response(401, { error: 'expired' }))
    vi.stubGlobal('fetch', fetchMock)

    render(
      <ToastProvider>
        <AuthProvider>
          <ExpireSessionButton repeated />
        </AuthProvider>
      </ToastProvider>
    )

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
    fireEvent.click(screen.getByRole('button', { name: /expire session/i }))

    await waitFor(() => {
      expect(screen.getAllByText('Session expired. Please sign in again.')).toHaveLength(1)
    })
    expect(replaceMock).toHaveBeenCalledWith('/?next=%2Fagents%2Fchatllm%2Fenv%23runtime')
    expect(replaceMock).toHaveBeenCalledTimes(1)
    expect(window.localStorage.getItem('controlUiAdminToken')).toBeNull()
  })

  it('re-arms the session-expired toast after a successful auth check', async () => {
    window.history.pushState({}, '', '/agents')
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(response(200, { me: { id: 'admin', role: 'admin' } }))
      .mockResolvedValueOnce(response(401, { error: 'expired' }))
      .mockResolvedValueOnce(response(200, { me: { id: 'admin', role: 'admin' } }))
      .mockResolvedValueOnce(response(401, { error: 'expired' }))
    vi.stubGlobal('fetch', fetchMock)

    render(
      <ToastProvider>
        <AuthProvider>
          <ExpireSessionButton />
          <CheckAuthButton />
        </AuthProvider>
      </ToastProvider>
    )

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
    fireEvent.click(screen.getByRole('button', { name: /expire session/i }))
    await waitFor(() =>
      expect(screen.getAllByText('Session expired. Please sign in again.')).toHaveLength(1)
    )

    fireEvent.click(screen.getByRole('button', { name: /check auth/i }))
    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3))

    fireEvent.click(screen.getByRole('button', { name: /expire session/i }))
    await waitFor(() =>
      expect(screen.getAllByText('Session expired. Please sign in again.')).toHaveLength(2)
    )
  })

  it('does not re-arm the session-expired toast after a failed auth check', async () => {
    window.history.pushState({}, '', '/agents')
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(response(200, { me: { id: 'admin', role: 'admin' } }))
      .mockResolvedValueOnce(response(401, { error: 'expired' }))
      .mockResolvedValueOnce(response(401, { error: 'expired' }))
      .mockResolvedValueOnce(response(401, { error: 'expired' }))
    vi.stubGlobal('fetch', fetchMock)

    render(
      <ToastProvider>
        <AuthProvider>
          <ExpireSessionButton />
          <CheckAuthButton />
        </AuthProvider>
      </ToastProvider>
    )

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
    fireEvent.click(screen.getByRole('button', { name: /expire session/i }))
    await waitFor(() =>
      expect(screen.getAllByText('Session expired. Please sign in again.')).toHaveLength(1)
    )

    fireEvent.click(screen.getByRole('button', { name: /check auth/i }))
    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3))

    fireEvent.click(screen.getByRole('button', { name: /expire session/i }))
    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(4))
    expect(screen.getAllByText('Session expired. Please sign in again.')).toHaveLength(1)
    expect(replaceMock).toHaveBeenCalledTimes(1)
  })

  it('clears publish-scope and registry-capability caches after login', async () => {
    let registryIdentity = 'Org A'
    const requests: string[] = []
    const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
      const url = String(input)
      const method = init?.method || 'GET'
      requests.push(`${method} ${url}`)
      if (url.includes('/api/v1/admin/registry/publish-scope')) {
        return response(200, {
          scope: registryIdentity === 'Org A' ? '@org-a' : '@org-b',
          curator: false,
          orgName: registryIdentity,
        })
      }
      if (url.includes('/api/v1/admin/registry/connect')) {
        return response(200, {
          state: 'connected',
          org: registryIdentity,
          authEnabled: true,
        })
      }
      if (url.includes('/api/v1/admin/auth/me')) {
        return response(401, { error: 'expired' })
      }
      if (url.includes('/api/v1/admin/auth/login')) {
        return response(200, {
          me: { id: 'admin', username: 'admin-b', email: '[email protected]' },
        })
      }
      throw new Error(`unexpected request: ${method} ${url}`)
    })
    vi.stubGlobal('fetch', fetchMock)

    const publishA = render(
      <PublishScopeProvider cacheKey="admin">
        <PublishScopeProbe />
      </PublishScopeProvider>
    )
    await waitFor(() => expect(screen.getByTestId('publish-scope')).toHaveTextContent('Org A'))
    publishA.unmount()

    const capabilityA = render(<RegistryCapabilityProbe />)
    await waitFor(() =>
      expect(screen.getByTestId('registry-capability')).toHaveTextContent('Org A')
    )
    capabilityA.unmount()

    registryIdentity = 'Org B'
    const auth = render(
      <ToastProvider>
        <AuthProvider>
          <LoginButton />
          <AuthUserProbe />
        </AuthProvider>
      </ToastProvider>
    )
    await waitFor(() =>
      expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('/auth/me'), expect.anything())
    )
    fireEvent.click(screen.getByRole('button', { name: /log in/i }))
    await waitFor(() => expect(screen.getByTestId('auth-user')).toHaveTextContent('admin-b'))
    auth.unmount()

    render(
      <PublishScopeProvider cacheKey="admin">
        <PublishScopeProbe />
      </PublishScopeProvider>
    )
    await waitFor(() => expect(screen.getByTestId('publish-scope')).toHaveTextContent('Org B'))
    cleanup()

    render(<RegistryCapabilityProbe />)
    await waitFor(() =>
      expect(screen.getByTestId('registry-capability')).toHaveTextContent('Org B')
    )
    expect(
      requests.filter(request => request.includes('/api/v1/admin/registry/publish-scope'))
    ).toHaveLength(4)
  })

  it('clears publish-scope and registry-capability caches after session expiration', async () => {
    let registryIdentity = 'Org A'
    const requests: string[] = []
    const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
      const url = String(input)
      const method = init?.method || 'GET'
      requests.push(`${method} ${url}`)
      if (url.includes('/api/v1/admin/registry/publish-scope')) {
        return response(200, {
          scope: registryIdentity === 'Org A' ? '@org-a' : '@org-b',
          curator: false,
          orgName: registryIdentity,
        })
      }
      if (url.includes('/api/v1/admin/registry/connect')) {
        return response(200, {
          state: 'connected',
          org: registryIdentity,
          authEnabled: true,
        })
      }
      if (url.includes('/api/v1/admin/auth/me')) {
        return response(200, { me: { id: 'admin', username: 'admin-a' } })
      }
      if (url.includes('/api/v1/admin/hosts')) {
        return response(401, { error: 'expired' })
      }
      throw new Error(`unexpected request: ${method} ${url}`)
    })
    vi.stubGlobal('fetch', fetchMock)

    const publishA = render(
      <PublishScopeProvider cacheKey="admin">
        <PublishScopeProbe />
      </PublishScopeProvider>
    )
    await waitFor(() => expect(screen.getByTestId('publish-scope')).toHaveTextContent('Org A'))
    publishA.unmount()

    const capabilityA = render(<RegistryCapabilityProbe />)
    await waitFor(() =>
      expect(screen.getByTestId('registry-capability')).toHaveTextContent('Org A')
    )
    capabilityA.unmount()

    render(
      <ToastProvider>
        <AuthProvider>
          <ExpireSessionButton />
        </AuthProvider>
      </ToastProvider>
    )
    await waitFor(() =>
      expect(fetchMock).toHaveBeenCalledWith(expect.stringContaining('/auth/me'), expect.anything())
    )
    fireEvent.click(screen.getByRole('button', { name: /expire session/i }))
    await waitFor(() =>
      expect(screen.getAllByText('Session expired. Please sign in again.')).toHaveLength(1)
    )
    cleanup()

    registryIdentity = 'Org B'
    render(
      <PublishScopeProvider cacheKey="admin">
        <PublishScopeProbe />
      </PublishScopeProvider>
    )
    await waitFor(() => expect(screen.getByTestId('publish-scope')).toHaveTextContent('Org B'))
    cleanup()

    render(<RegistryCapabilityProbe />)
    await waitFor(() =>
      expect(screen.getByTestId('registry-capability')).toHaveTextContent('Org B')
    )
    expect(
      requests.filter(request => request.includes('/api/v1/admin/registry/publish-scope'))
    ).toHaveLength(4)
  })

  it('clears legacy storage without a toast when no cookie session exists on mount', async () => {
    window.history.pushState({}, '', '/agents/context1')
    window.localStorage.setItem('controlUiAdminToken', 'expired-token')
    const fetchMock = vi.fn().mockResolvedValue(response(401, { error: 'expired' }))
    vi.stubGlobal('fetch', fetchMock)

    render(
      <ToastProvider>
        <AuthProvider>
          <AuthProbe />
        </AuthProvider>
      </ToastProvider>
    )

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
    expect(screen.queryByText('Session expired. Please sign in again.')).toBeNull()
    expect(replaceMock).not.toHaveBeenCalled()
    expect(window.localStorage.getItem('controlUiAdminToken')).toBeNull()
  })

  it('redirects to login after logout', async () => {
    window.localStorage.setItem('controlUiAdminToken', 'valid-token')
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(response(200, { me: { id: 'admin', role: 'admin' } }))
      .mockResolvedValueOnce(response(200, { ok: true }))
    vi.stubGlobal('fetch', fetchMock)

    render(
      <ToastProvider>
        <AuthProvider>
          <LogoutButton />
        </AuthProvider>
      </ToastProvider>
    )

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
    fireEvent.click(screen.getByRole('button', { name: /log out/i }))

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
    expect(replaceMock).toHaveBeenCalledWith('/')
    expect(window.localStorage.getItem('controlUiAdminToken')).toBeNull()
  })

  it('reverifies a remote cookie-session change once without an invalidation loop', async () => {
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(
        response(200, { me: { id: 'admin-a', username: 'admin-a', role: 'admin' } })
      )
      .mockResolvedValueOnce(
        response(200, { me: { id: 'admin-b', username: 'admin-b', role: 'admin' } })
      )
    vi.stubGlobal('fetch', fetchMock)
    render(
      <ToastProvider>
        <AuthProvider>
          <AuthUserProbe />
        </AuthProvider>
      </ToastProvider>
    )
    await waitFor(() => expect(screen.getByTestId('auth-user')).toHaveTextContent('admin-a'))
    const otherTab = new BroadcastChannel('control-ui-read-metadata-invalidation')
    const loopMessages: unknown[] = []
    otherTab.onmessage = event => loopMessages.push(event.data)
    await act(async () => {
      otherTab.postMessage({ type: 'session-invalidation' })
      await new Promise(resolve => setTimeout(resolve, 0))
    })
    await waitFor(() => expect(screen.getByTestId('auth-user')).toHaveTextContent('admin-b'))
    expect(getReadRequestPrincipal()?.principalId).toBe('admin-b')
    expect(fetchMock).toHaveBeenCalledTimes(2)
    expect(loopMessages).toEqual([])
    otherTab.close()
  })

  it.each([null, '', undefined])(
    'clears the previous identity fields after remote sign-in with email %s',
    async email => {
      const fetchMock = vi
        .fn()
        .mockResolvedValueOnce(
          meResponse({
            id: 'admin-a',
            username: 'username-a',
            email: '[email protected]',
            role: 'admin',
          })
        )
        .mockResolvedValueOnce(meResponse({ id: 'admin-b', email, role: 'admin' }))
      vi.stubGlobal('fetch', fetchMock)
      render(
        <ToastProvider>
          <AuthProvider>
            <AuthIdentityProbe />
          </AuthProvider>
        </ToastProvider>
      )
      await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-a'))
      expect(screen.getByTestId('auth-email')).toHaveTextContent('[email protected]')
      const otherTab = new BroadcastChannel('control-ui-read-metadata-invalidation')
      try {
        await act(async () => {
          otherTab.postMessage({ type: 'session-invalidation' })
          await new Promise(resolve => setTimeout(resolve, 0))
        })
        await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-b'))
        expect(screen.getByTestId('auth-email')).toBeEmptyDOMElement()
        expect(screen.getByTestId('auth-username')).toBeEmptyDOMElement()
        expect(screen.queryByText('[email protected]')).toBeNull()
        expect(getReadRequestPrincipal()?.principalId).toBe('admin-b')
        expect(fetchMock).toHaveBeenCalledTimes(2)
      } finally {
        otherTab.close()
      }
    }
  )

  it('preserves omitted fields for the same identity and clears an explicitly null email', async () => {
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(
        meResponse({
          id: 'admin-a',
          username: 'username-a',
          email: '[email protected]',
          role: 'admin',
        })
      )
      .mockResolvedValueOnce(meResponse({ id: 'admin-a', role: 'admin' }))
      .mockResolvedValueOnce(meResponse({ id: 'admin-a', email: null, role: 'admin' }))
    vi.stubGlobal('fetch', fetchMock)
    render(
      <ToastProvider>
        <AuthProvider>
          <AuthIdentityProbe />
          <CheckAuthButton />
        </AuthProvider>
      </ToastProvider>
    )
    await waitFor(() =>
      expect(screen.getByTestId('auth-email')).toHaveTextContent('[email protected]')
    )
    fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
    expect(screen.getByTestId('auth-username')).toHaveTextContent('username-a')
    expect(screen.getByTestId('auth-email')).toHaveTextContent('[email protected]')
    fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
    await waitFor(() => expect(screen.getByTestId('auth-email')).toBeEmptyDOMElement())
    expect(screen.getByTestId('auth-username')).toHaveTextContent('username-a')
  })

  it.each(['response', 'body'] as const)(
    'does not let an obsolete %s clear a newer confirmed login, and still honors a current 401',
    async phase => {
      let completeOld!: () => void
      let oldBodyStarted = false
      const oldResponse = meResponse({
        id: 'admin-a',
        username: 'username-a',
        email: '[email protected]',
        role: 'admin',
      })
      const deferredResponse = new Promise<Response>(resolve => {
        if (phase === 'response') completeOld = () => resolve(oldResponse)
        else resolve(oldResponse)
      })
      if (phase === 'body') {
        vi.spyOn(oldResponse, 'text').mockImplementation(() => {
          oldBodyStarted = true
          return new Promise((_resolve, reject) => {
            completeOld = () => reject(new Error('Old body failed'))
          })
        })
      }
      const fetchMock = vi
        .fn()
        .mockResolvedValueOnce(
          meResponse({
            id: 'admin-a',
            username: 'username-a',
            email: '[email protected]',
            role: 'admin',
          })
        )
        // Deliberately ignore AbortSignal at this network/body seam: the UI
        // operation fence must hold even when a transport completion is late.
        .mockReturnValueOnce(deferredResponse)
        .mockResolvedValueOnce(
          meResponse({ id: 'admin-b', username: 'username-b', email: null, role: 'admin' })
        )
        .mockResolvedValueOnce(new Response(JSON.stringify({ error: 'expired' }), { status: 401 }))
      vi.stubGlobal('fetch', fetchMock)
      render(
        <ToastProvider>
          <AuthProvider>
            <AuthIdentityProbe />
            <CheckAuthButton />
            <LoginButton />
          </AuthProvider>
        </ToastProvider>
      )
      await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-a'))
      fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
      await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
      if (phase === 'body') await waitFor(() => expect(oldBodyStarted).toBe(true))
      fireEvent.click(screen.getByRole('button', { name: 'Log in' }))
      await waitFor(() => expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-b'))
      await act(async () => {
        completeOld()
        await Promise.resolve()
        await Promise.resolve()
      })
      expect(screen.getByTestId('auth-id')).toHaveTextContent('admin-b')
      expect(screen.getByTestId('auth-logged-in')).toHaveTextContent('true')
      expect(getReadRequestPrincipal()?.principalId).toBe('admin-b')
      expect(screen.queryByText('[email protected]')).toBeNull()
      fireEvent.click(screen.getByRole('button', { name: 'Check auth' }))
      await waitFor(() => expect(screen.getByTestId('auth-logged-in')).toHaveTextContent('false'))
      expect(getReadRequestPrincipal()).toBeNull()
    }
  )

  it('redirects after logout even when token revocation fails', async () => {
    window.localStorage.setItem('controlUiAdminToken', 'valid-token')
    const fetchMock = vi
      .fn()
      .mockResolvedValueOnce(response(200, { me: { id: 'admin', role: 'admin' } }))
      .mockResolvedValueOnce(response(500, { error: 'revoke failed' }))
    vi.stubGlobal('fetch', fetchMock)

    render(
      <ToastProvider>
        <AuthProvider>
          <LogoutButton />
        </AuthProvider>
      </ToastProvider>
    )

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))
    fireEvent.click(screen.getByRole('button', { name: /log out/i }))

    await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2))
    expect(replaceMock).toHaveBeenCalledWith('/')
    expect(window.localStorage.getItem('controlUiAdminToken')).toBeNull()
  })
})