Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

21.9 KB
Raw Blame
import { createHash, createPublicKey, generateKeyPairSync, verify } from 'node:crypto'
import { Hono } from 'hono'
import nodemailer from 'nodemailer'
import { createCloudAppStore } from '../../../../test/cloud-app-store'
import { buildCtx, createServer } from '../server'
import { serveAppOrigin } from '../proxy/app-origin'
import { createApp } from '../services/apps'
import type { Deps } from '../ctx'
import type { Spec } from '../spec'

const appOrigin = 'https://crm.example.test'
const apiOrigin = 'https://api.example.test'
const describeDatabase = process.env.DB_HOST ? describe : describe.skip
jest.setTimeout(90000)

describeDatabase('App end-user sign-in', () => {
  let fixture: Awaited<ReturnType<typeof createCloudAppStore>>
  let ctx: ReturnType<typeof buildCtx>
  let api: ReturnType<typeof createServer>
  let site: Hono
  const mirrorQuery = jest.fn().mockResolvedValue([])
  const providerFetch = jest.fn()
  const github = { clientId: 'github-test', clientSecret: 'test-secret' }
  const principal = { userId: 'member', actor: 'member', permissions: ['read:apps', 'write:apps', 'delete:apps'] }
  beforeAll(async () => {
    fixture = await createCloudAppStore()
    const identityPrivateKey = generateKeyPairSync('rsa', { modulusLength: 2048 })
      .privateKey.export({ format: 'pem', type: 'pkcs8' })
      .toString()
    ctx = buildCtx(
      {
        publicUrl: apiOrigin,
        managementUrl: apiOrigin,
        sessionSecret: 'test-session-secret',
        identityPrivateKey,
        oauth: { github },
        supervisorUrl: apiOrigin,
        artifactUrl: apiOrigin,
        runtimeImages: {},
        diskSizeGb: 10,
        autoStopSeconds: 900,
        domainsEnabled: true,
        agentMdPath: '',
        svBinDir: '',
      },
      {
        store: fixture.store,
        origins: { envUrl: () => appOrigin, consoleUrl: () => 'https://console.example.test' },
        domains: { verifiedHost: async () => null, list: async () => [] },
        credentials: { authenticate: async () => null },
        appdb: { query: mirrorQuery },
        oauthFetch: providerFetch,
      } as unknown as Deps,
    )
    api = createServer(ctx)
  })
  afterAll(() => fixture?.close())
  beforeEach(async () => {
    await fixture.source.query(`TRUNCATE ${fixture.schema}.apps CASCADE`)
    mirrorQuery.mockClear()
    providerFetch.mockReset()
    const app = await createApp(ctx, 'crm')
    const env = (await ctx.store.envByName(app.id, 'main'))!
    const spec = {
      app: 'crm',
      environment: 'main',
      version: 1,
      access: 'public',
      auth: { providers: ['github', 'google', 'email'], protect: ['/app/*'] },
      database: { migrations: 'migrations/' },
    } as Spec
    await ctx.store.insertSpec(env.id, spec)
    await ctx.store.updateEnv(env.id, { public_url: appOrigin, db_url: 'postgresql://database.example.test/test' })
    const published = (await ctx.store.envById(env.id))!
    site = new Hono().all('*', (c) => serveAppOrigin(ctx, c, published))
  })
  afterEach(() => jest.restoreAllMocks())
  function manage(path: string, method = 'GET', body?: unknown) {
    return api.request(
      apiOrigin + '/v1/apps/crm' + path,
      {
        method,
        ...(body === undefined ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }),
      },
      { platformPrincipal: { ...principal, organizationId: fixture.organizationId } },
    )
  }
  const visitor = (path: string, cookie = '') => site.request(appOrigin + path, { headers: { cookie } })
  const cookieFor = (res: Response, name: string) => {
    const cookie = res.headers.getSetCookie().find((c) => c.startsWith(name + '='))
    expect(cookie).toBeDefined()
    return cookie!.split(';')[0]
  }
  async function githubSignIn() {
    const login = await visitor('/.boxlite/auth/login?provider=github&next=/app/issues')
    expect(login.status).toBe(302)
    const nonce = cookieFor(login, '__Host-bxl_login')
    const start = await api.request(login.headers.get('location')!)
    const target = new URL(start.headers.get('location')!)
    expect(target.origin + target.pathname).toBe('https://github.com/login/oauth/authorize')
    expect(target.searchParams.get('redirect_uri')).toBe(apiOrigin + '/auth/callback/github')
    const verifier = start.headers.getSetCookie()[0].split(';')[0]
    providerFetch.mockImplementation(async (input, init) => {
      switch (String(input)) {
        case 'https://github.com/login/oauth/access_token': {
          const body = new URLSearchParams(String(init.body))
          expect(body.get('code')).toBe('sample-code')
          expect(createHash('sha256').update(body.get('code_verifier')!).digest('base64url')).toBe(
            target.searchParams.get('code_challenge'),
          )
          return Response.json({ access_token: 'test-access' })
        }
        case 'https://api.github.com/user':
          return Response.json({ id: 42, login: 'casey', name: 'Casey' })
        case 'https://api.github.com/user/emails':
          return Response.json([{ email: '[email protected]', primary: true, verified: true }])
        default:
          throw new Error('Unexpected OAuth URL: ' + String(input))
      }
    })
    const callback = await api.request(
      apiOrigin +
        '/auth/callback/github?' +
        new URLSearchParams({ code: 'sample-code', state: target.searchParams.get('state')! }),
      { headers: { cookie: verifier } },
    )
    expect(callback.status).toBe(302)
    const handoff = callback.headers.get('location')!
    expect(new URL(handoff).origin).toBe(appOrigin)
    const complete = await site.request(handoff, { headers: { cookie: nonce } })
    expect(complete.headers.get('location')).toBe('/app/issues')
    expect((await site.request(handoff, { headers: { cookie: nonce } })).status).toBe(400)
    return cookieFor(complete, '__Host-bxl_session')
  }
  it('hands a GitHub user session to the App and reflects sign-out and blocking in management', async () => {
    const cookie = await githubSignIn()
    const me = await (await visitor('/.boxlite/auth/me', cookie)).json()
    expect(me).toMatchObject({ email: '[email protected]', role: 'user', provider: 'github' })
    expect(mirrorQuery).toHaveBeenCalledWith(
      expect.any(String),
      [expect.stringContaining('INSERT INTO boxlite.users')],
      expect.objectContaining({ params: [me.id, me.email, me.name, 'github'] }),
    )
    const auth = '/envs/main/auth'
    expect(await (await manage(auth)).json()).toMatchObject({ enabled: true, users: 1 })
    expect(await (await manage(auth + '/redirect-uris')).json()).toContainEqual(
      expect.objectContaining({ provider: 'github', status: 'ready' }),
    )
    expect(await (await manage(auth + '/users?search=casey')).json()).toMatchObject([{ id: me.id, active_sessions: 1 }])
    expect(await (await manage(auth + '/users/export')).text()).toContain('[email protected],Casey,github')
    expect(await (await manage(auth + '/users/' + me.id + '/signout', 'POST')).json()).toMatchObject({ revoked: 1 })
    expect((await visitor('/.boxlite/auth/me', cookie)).status).toBe(401)
    for (const action of ['block', 'unblock']) {
      expect(await (await manage(auth + '/users/' + me.id + '/' + action, 'POST')).json()).toMatchObject({
        blocked: action === 'block',
      })
    }
  })
  it('issues an environment-bound identity and signs a test user out', async () => {
    const session = await manage('/envs/main/auth/test-sessions', 'POST', { email: '[email protected]', role: 'owner' })
    expect(session.status).toBe(201)
    const { cookie, user } = await session.json()
    const response = await visitor('/.boxlite/auth/me', cookie)
    expect(await response.json()).toMatchObject({ role: 'owner', email: '[email protected]' })
    const { identityToken } = await import('./identity')
    const dbUser = (await ctx.store.get<import('./sessions').AppUser>('SELECT * FROM app_users WHERE id = ?', user.id))!
    const jwt = await identityToken(ctx, dbUser, 'crm', 'main', 'owner')
    const [header, claims, signature] = jwt.split('.')
    const keys = await (await visitor('/.boxlite/auth/jwks.json')).json()
    expect(JSON.parse(Buffer.from(header, 'base64url').toString()).kid).toBe(keys.keys[0].kid)
    expect(
      verify(
        'sha256',
        Buffer.from(header + '.' + claims),
        createPublicKey({ key: keys.keys[0], format: 'jwk' }),
        Buffer.from(signature, 'base64url'),
      ),
    ).toBe(true)
    expect(JSON.parse(Buffer.from(claims, 'base64url').toString())).toMatchObject({ aud: appOrigin, sub: user.id })
    const logout = await visitor('/.boxlite/auth/logout?next=/bye', cookie)
    expect(logout.headers.get('location')).toBe('/bye')
    expect((await visitor('/.boxlite/auth/me', cookie)).status).toBe(401)
    expect((await manage('/envs/main/auth/test-users', 'DELETE')).status).toBe(200)
    expect(await (await manage('/envs/main/auth/users')).json()).toEqual([])
  })
  it('delivers a single-use email code and establishes a session for the verified address', async () => {
    const sendMail = jest.fn().mockResolvedValue({})
    jest.spyOn(nodemailer, 'createTransport').mockReturnValue({ sendMail, close: jest.fn() } as never)
    ctx.config.smtpDevSink = '127.0.0.1:2525'
    const sender = {
      host: '127.0.0.1',
      port: 2525,
      username: 'mailer',
      password: 'sample',
      from: 'Team <[email protected]>',
    }
    expect(await (await manage('/auth/email', 'PUT', sender)).json()).toMatchObject({
      status: { emailSender: { configured: true, passwordSet: true } },
    })
    expect(await (await manage('/auth/email')).json()).not.toHaveProperty('password')
    expect((await manage('/auth/email/test', 'POST', { to: '[email protected]' })).status).toBe(200)
    expect(await (await visitor('/.boxlite/auth/login?provider=email')).text()).toContain('/.boxlite/auth/email/start')
    function post(path: string, values: Record<string, string>, cookie = '') {
      return site.request(appOrigin + '/.boxlite/auth/email/' + path, {
        method: 'POST',
        headers: { cookie, origin: appOrigin },
        body: new URLSearchParams(values),
      })
    }
    const fields = { email: '[email protected]', next: '/app/issues' }
    const start = await post('start', fields)
    expect(start.status).toBe(200)
    const browserCookie = start.headers.getSetCookie()[0].split(';')[0]
    const delivered = sendMail.mock.calls.at(-1)![0]
    expect(delivered.to).toBe('[email protected]')
    const code = delivered.text.match(/\b\d{6}\b/)![0]
    expect(
      (await post('verify', { ...fields, code: code === '000000' ? '111111' : '000000' }, browserCookie)).status,
    ).toBe(400)
    const verified = await post('verify', { ...fields, code }, browserCookie)
    expect(verified.headers.get('location')).toBe(fields.next)
    expect(await (await visitor('/.boxlite/auth/me', cookieFor(verified, '__Host-bxl_session'))).json()).toMatchObject({
      email: '[email protected]',
      provider: 'email',
    })
    expect((await post('verify', { ...fields, code }, browserCookie)).status).toBe(400)
    expect((await manage('/auth/email', 'DELETE')).status).toBe(200)
    expect((await (await manage('/auth')).json()).status.emailSender).toMatchObject({ configured: false })
  })
  it('opens a private App with a one-time ticket carrying the requested test identity', async () => {
    const app = (await ctx.store.appByName('crm'))!
    const env = (await ctx.store.envByName(app.id, 'main'))!
    await ctx.store.updateEnv(env.id, { access_override: 'private' })
    const fresh = (await ctx.store.envById(env.id))!
    site = new Hono().all('*', (c) => serveAppOrigin(ctx, c, fresh))
    const locked = await visitor('/app/issues')
    expect(locked.status).toBe(401)
    const ticket = await manage('/envs/main/open-ticket', 'POST', {
      as: '[email protected]',
      role: 'owner',
      next: '/app/issues',
    })
    expect(ticket.status).toBe(201)
    const { url } = await ticket.json()
    expect(url).not.toContain('[email protected]')
    const opened = await site.request(url)
    expect(opened.headers.get('location')).toBe('/app/issues')
    const cookies = opened.headers
      .getSetCookie()
      .map((c) => c.split(';')[0])
      .join('; ')
    expect(await (await visitor('/.boxlite/auth/me', cookies)).json()).toMatchObject({
      role: 'owner',
      email: '[email protected]',
    })
    expect((await site.request(url)).status).toBe(401)
  })
  it('explains an interrupted sign-in on the App and API origins', async () => {
    expect((await visitor('/app/issues')).status).toBe(401)
    const browser = await site.request(appOrigin + '/app/issues', { headers: { accept: 'text/html' } })
    expect(browser.headers.get('location')).toContain('/.boxlite/auth/login?next=')
    expect((await visitor('/.boxlite/auth/login?provider=twitter')).status).toBe(400)
    const login = await visitor('/.boxlite/auth/login?provider=github')
    const location = new URL(login.headers.get('location')!)
    for (const [field, value, status] of [
      ['env', 'missing', 404],
      ['organization', 'other', 404],
      ['bh', '', 400],
      ['host', 'missing.example.test', 400],
      ['provider', 'google', 400],
    ] as const) {
      const changed = new URL(location)
      changed.searchParams.set(field, value)
      expect((await api.request(changed)).status).toBe(status)
    }
    const start = await api.request(location)
    const state = new URL(start.headers.get('location')!).searchParams.get('state')!
    const callback = apiOrigin + '/auth/callback/github?state=' + state
    const verifier = start.headers.getSetCookie()[0].split(';')[0]
    expect((await api.request(callback + '&code=sample')).status).toBe(400)
    expect((await api.request(callback + '&error=access_denied', { headers: { cookie: verifier } })).status).toBe(400)
    providerFetch.mockResolvedValue(Response.json({ error: 'invalid_grant' }, { status: 400 }))
    const failed = await api.request(callback + '&code=expired', { headers: { cookie: verifier } })
    expect(failed.status).toBe(502)
    expect(await failed.text()).toMatch(/GitHub sign-in failed/)
    expect(
      (
        await api.request(apiOrigin + '/auth/callback/github', {
          method: 'POST',
          body: new URLSearchParams({ state: 'expired', code: 'code' }),
        })
      ).status,
    ).toBe(400)
  })
  it('manages custom OAuth clients without returning the client secret', async () => {
    const settings = '/auth/methods/'
    expect((await manage(settings + 'microsoft', 'PUT', { keys: 'shared' })).status).toBe(400)
    expect((await manage(settings + 'apple', 'PUT', { keys: 'own', clientId: 'com.example.app' })).status).toBe(400)
    expect((await manage(settings + 'missing', 'PUT', { keys: 'shared' })).status).toBe(404)
    const custom = await manage(settings + 'github', 'PUT', {
      keys: 'own',
      clientId: 'app-client',
      clientSecret: 'example-client-secret',
    })
    expect(custom.status).toBe(200)
    expect((await custom.clone().json()).status.methods).toContainEqual(
      expect.objectContaining({ provider: 'github', keys: 'own', clientId: 'app-client' }),
    )
    expect(await custom.text()).not.toContain('example-client-secret')
    expect((await manage(settings + 'github', 'PUT', { keys: 'own', clientId: 'updated-id' })).status).toBe(200)
    expect((await (await manage(settings + 'github', 'PUT', { keys: 'shared' })).json()).status.methods).toContainEqual(
      expect.objectContaining({ provider: 'github', keys: 'shared' }),
    )
  })
  it('keeps test-session expiry fixed and slides a returning OAuth user’s session', async () => {
    const { cookie: testCookie, user } = await (
      await manage('/envs/main/auth/test-sessions', 'POST', { email: '[email protected]' })
    ).json()
    const oauthCookie = await githubSignIn()
    const earlier = new Date(Date.now() - 600000).toISOString()
    const expires = new Date(Date.now() + 600000).toISOString()
    await ctx.store.run('UPDATE app_sessions SET last_seen = ?, expires_at = ?', earlier, expires)
    for (const cookie of [testCookie, oauthCookie])
      expect((await visitor('/.boxlite/auth/me', cookie)).status).toBe(200)
    const sessions = await ctx.store.all<{ kind: string; last_seen: string; expires_at: string }>(
      'SELECT kind,last_seen,expires_at FROM app_sessions',
    )
    expect(sessions.find((s) => s.kind === 'test')?.expires_at).toBe(expires)
    expect(Date.parse(sessions.find((s) => s.kind === 'oauth')!.expires_at)).toBeGreaterThan(Date.parse(expires))
    expect(sessions.every((s) => s.last_seen > earlier)).toBe(true)
    expect((await manage('/envs/main/auth/users/' + user.id + '/block', 'POST')).status).toBe(200)
    expect((await manage('/envs/main/auth/test-sessions', 'POST', { email: '[email protected]' })).status).toBe(403)
  })
  it('validates sender configuration, explains delivery failures and limits email retries', async () => {
    const sendMail = jest.fn().mockResolvedValue({})
    jest.spyOn(nodemailer, 'createTransport').mockReturnValue({ sendMail, close: jest.fn() } as never)
    const sender = { host: '127.0.0.1', port: 2525, from: '[email protected]' }
    ctx.config.smtpDevSink = '127.0.0.1:2525'
    for (const invalid of [{ host: 'not a host' }, { port: 4567 }, { from: 'invalid' }]) {
      expect((await manage('/auth/email', 'PUT', { ...sender, ...invalid })).status).toBe(400)
    }
    expect((await manage('/auth/email', 'PUT', sender)).status).toBe(200)
    const mail = (op: string, fields: Record<string, string>, origin = appOrigin, cookie = '') =>
      site.request(appOrigin + '/.boxlite/auth/email/' + op, {
        method: 'POST',
        headers: { origin, cookie },
        body: new URLSearchParams(fields),
      })
    expect((await mail('start', { email: 'invalid' })).status).toBe(400)
    expect((await mail('start', { email: '[email protected]' }, apiOrigin)).status).toBe(403)
    expect((await mail('verify', {}, apiOrigin)).status).toBe(403)
    const fields = { email: '[email protected]' }
    sendMail.mockRejectedValueOnce(Object.assign(new Error('relay temporarily unavailable'), { code: 'ECONNECTION' }))
    const unavailable = await mail('start', fields)
    expect(unavailable.status).toBe(502)
    for (let i = 0; i < 4; i++) expect((await mail('start', fields)).status).toBe(200)
    expect((await mail('start', fields)).status).toBe(429)
    const first = await mail('start', { email: '[email protected]' })
    const nonce = first.headers.getSetCookie()[0].split(';')[0]
    const delivered = sendMail.mock.calls.at(-1)![0].text.match(/\b\d{6}\b/)![0]
    const wrong = { email: '[email protected]', code: delivered === '000000' ? '111111' : '000000' }
    for (let n = 4; n >= 1; n--)
      expect(await (await mail('verify', wrong, appOrigin, nonce)).text()).toContain(
        n === 1 ? '1 try left' : n + ' tries left',
      )
    expect(await (await mail('verify', wrong, appOrigin, nonce)).text()).toContain('Too many wrong codes')
  })
  it('forwards the signed-in user identity, preserves application cookies, and supports custom-domain sign-in', async () => {
    const app = (await ctx.store.appByName('crm'))!
    const env = (await ctx.store.envByName(app.id, 'main'))!
    await ctx.store.updateEnv(env.id, {
      live_deployment: 1,
      active_box_id: 'runtime',
      box_url: 'http://tunnel.example.test',
    })
    const published = (await ctx.store.envById(env.id))!
    site = new Hono().all('*', (c) => serveAppOrigin(ctx, c, published))
    const cookie = await githubSignIn()
    jest.spyOn(ctx.resources, 'boxStatus').mockResolvedValue('running')
    const upstream = jest.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('welcome'))
    expect(await (await visitor('/app/issues', cookie + '; theme=dark')).text()).toBe('welcome')
    const sent = new Headers(upstream.mock.calls[0][1]!.headers)
    expect(sent.get('x-boxlite-user-email')).toBe('[email protected]')
    expect(sent.get('x-boxlite-user-role')).toBe('user')
    expect(sent.get('x-boxlite-identity')!.split('.')).toHaveLength(3)
    expect(sent.get('cookie')).toBe('theme=dark')
    expect((await visitor('/.boxlite/auth/login?next=/home', cookie)).headers.get('location')).toBe('/home')
    expect((await visitor('/.boxlite/health')).status).toBe(404)
    const verified = 'portal.example.test'
    const check = jest
      .spyOn(ctx.domains, 'verifiedHost')
      .mockImplementation(async (_env, host) => (host === verified ? host : null))
    const login = await site.request(appOrigin + '/.boxlite/auth/login', { headers: { 'x-forwarded-host': verified } })
    const startUrl = new URL(login.headers.get('location')!)
    expect(startUrl.searchParams.get('host')).toBe(verified)
    const start = await api.request(startUrl)
    const state = new URL(start.headers.get('location')!).searchParams.get('state')!
    expect((await api.request(apiOrigin + '/auth/callback/github?error=cancelled&state=' + state)).status).toBe(400)
    expect(check).toHaveBeenCalledWith(expect.objectContaining({ id: env.id }), verified)
  })
  it('shows only the configured sign-in methods and reports unavailable or disabled sign-in', async () => {
    const app = (await ctx.store.appByName('crm'))!
    const env = (await ctx.store.envByName(app.id, 'main'))!
    const oauth = ctx.config.oauth
    try {
      ctx.config.oauth = { github, google: { clientId: 'google-id', clientSecret: 'sample' } }
      expect(await (await visitor('/.boxlite/auth/login')).text()).toMatch(/Continue with Google/)
      ctx.config.oauth = {}
      expect((await visitor('/.boxlite/auth/login')).status).toBe(503)
      expect((await visitor('/.boxlite/auth/unknown')).status).toBe(404)
      expect((await visitor('/.boxlite/auth/email/start')).status).toBe(404)
      expect((await visitor('/.boxlite/auth/complete')).status).toBe(400)
      const spec = (await ctx.store.spec(env.id))!
      await ctx.store.insertSpec(env.id, { ...spec, version: 2, auth: null })
      expect((await visitor('/.boxlite/auth/login')).status).toBe(404)
      expect((await manage('/envs/main/auth/test-sessions', 'POST', { email: '[email protected]' })).status).toBe(409)
    } finally {
      ctx.config.oauth = oauth
    }
  })
})