Skip to content

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

9.3 KB
Raw Blame
import { appSecretNames, deleteAppSecret, orgSecretNames, secretValue, setAppSecret } from './orgs'
import { randomUUID } from 'node:crypto'
import { createCloudAppStore } from '../../../test/cloud-app-store'
import { jsonPost, managementHttp, principal } from '../../../test/cloud-app/management'
import type { Ctx } from './ctx'
import { LOG_RING_SIZE, Store, now } from './db'
import { createApp } from './services/apps'
import { FEEDBACK_PER_HOUR } from './feedback'

const withPostgres = process.env.DB_HOST ? describe : describe.skip
withPostgres('App history and feedback', () => {
  let fixture: Awaited<ReturnType<typeof createCloudAppStore>>
  const otherOrg = randomUUID()
  let ctx: Ctx
  beforeAll(async () => {
    fixture = await createCloudAppStore(randomUUID(), otherOrg)
    ctx = { store: fixture.store, config: {} } as Ctx
  })
  afterAll(() => fixture?.close())

  test('trims only the overflowing environment and combines source, deployment and inclusive time filters', async () => {
    const store = fixture.store
    const start = '2026-02-01T10:00:00.000Z'
    await fixture.source.query(
      `INSERT INTO ${fixture.schema}.logs (env_id,ts,source,level,line) SELECT 'main',$1,'web','info',i::text FROM generate_series(1,$2::int) AS i`,
      [start, LOG_RING_SIZE],
    )
    await store.appendLogs('preview', [{ ts: start, source: 'web', level: 'warn', line: 'preview stays' }])
    const end = '2026-02-01T10:01:00.000Z'
    const observed = await store.appendLogs('main', [
      { ts: start, source: 'build', level: 'info', line: 'first', deployment: 1 },
      { ts: end, source: 'build', level: 'info', line: 'second', deployment: 1 },
      { ts: end, source: 'build', level: 'info', line: 'new release', deployment: 2 },
      { ts: end, source: 'web', level: 'info', line: 'live', deployment: 1 },
    ])
    expect(await store.get('SELECT count(*) AS n FROM logs WHERE env_id = ?', 'main')).toEqual({ n: LOG_RING_SIZE })
    expect(await store.get('SELECT line FROM logs WHERE env_id = ? ORDER BY id LIMIT 1', 'main')).toEqual({ line: '5' })
    expect((await store.logs('preview', {})).map((l) => l.line)).toEqual(['preview stays'])
    expect(await store.logs('main', { since: start, until: end, deployment: 1, source: 'build' })).toEqual(
      observed.slice(0, 2),
    )
    expect((await store.logs('main', { limit: 1, source: 'build', deployment: 1 }))[0].line).toBe('second')
  })

  test('retains deleted names in each organization and clears stored database credentials on update', async () => {
    const app = await createApp(ctx, 'retained')
    const otherStore = new Store(fixture.source, otherOrg, fixture.encryption, fixture.schema)
    const otherApp = await createApp({ store: otherStore } as Ctx, 'retained')
    const env = (await fixture.store.envByName(app.id, 'main'))!
    await fixture.store.updateEnv(env.id, { db_url: 'postgresql://[email protected]/app' })
    await fixture.store.updateEnv(env.id, { db_url: null })
    await fixture.store.updateEnv(env.id, {})
    const [raw] = await fixture.source.query(`SELECT db_url FROM ${fixture.schema}.envs WHERE id=$1`, [env.id])
    expect(raw.db_url).toBeNull()
    await fixture.store.updateApp(app.id, { deleted_at: now() })
    await fixture.store.updateApp(app.id, {})
    expect(await fixture.store.appByName(app.name)).toBeUndefined()
    expect((await fixture.store.appByNameAnyState(app.name))?.id).toBe(app.id)
    expect((await fixture.store.deletedApps()).map((a) => a.id)).toEqual([app.id])
    expect(await otherStore.deletedApps()).toEqual([])
    expect((await otherStore.appByName(app.name))?.id).toBe(otherApp.id)
    const acrossOrgs = new Store(fixture.source, undefined, fixture.encryption, fixture.schema)
    expect((await acrossOrgs.deletedApps()).map((a) => a.id)).toEqual([app.id])
    expect((await acrossOrgs.apps()).map((a) => a.id)).toContain(otherApp.id)
    expect((await acrossOrgs.appById(app.id))?.name).toBe('retained')
    expect((await acrossOrgs.appByName('retained'))?.id).toBe(otherApp.id)
  })

  test('redacts reports at rest, per App, and admits another report once the hourly budget expires', async () => {
    const app = await createApp(ctx, 'feedback-limit')
    const second = await createApp(ctx, 'feedback-other')
    const send = managementHttp(ctx)
    const caller = { ...principal, organizationId: fixture.organizationId }
    const feedback = (name: string, payload: object) =>
      send('/v1/apps/' + name + '/feedback', jsonPost(payload), caller)
    const report = await feedback(app.name, {
      message: 'Could not log in at postgresql://owner:[email protected]/app',
      command: 'boxlite auth login --token bxt_ABCDEFGHIJKL',
      env: 'main',
      cli_version: '1.4',
    })
    expect(report.status).toBe(201)
    const receipt = await report.json()
    const listing = await send('/admin/feedback', {}, { ...caller, admin: true })
    expect(await listing.json()).toContainEqual(
      expect.objectContaining({
        id: receipt.id,
        app: app.name,
        actor: caller.actor,
        env: 'main',
        cli_version: '1.4',
        message: 'Could not log in at postgresql://owner:****@db.example.test/app',
        command: 'boxlite auth login --token bxt_…IJKL',
      }),
    )
    for (let i = 1; i < FEEDBACK_PER_HOUR; i++)
      expect((await feedback(app.name, { message: 'Deployment stalled again' })).status).toBe(201)
    const limited = await feedback(app.name, { message: 'Deployment waiting for a slot' })
    expect(limited.status).toBe(429)
    expect(await limited.json()).toMatchObject({ error: { code: 'rate_limited' } })
    expect((await feedback(second.name, { message: 'Build log does not update' })).status).toBe(201)
    await fixture.store.run(
      'UPDATE feedback SET created_at = ? WHERE id = ?',
      new Date(Date.now() - 3_600_001).toISOString(),
      receipt.id,
    )
    expect((await feedback(app.name, { message: 'Deployment waiting for a slot' })).status).toBe(201)
  })

  test('rejects unsupported credential updates before writing and accepts a parameterized replacement', async () => {
    const app = await createApp(ctx, 'credential-update')
    const store = fixture.store
    const env = (await store.envByName(app.id, 'main'))!
    await expect(
      store.run('UPDATE envs AS e SET control_secret = ? WHERE e.id = ?', 'replacement', env.id),
    ).rejects.toThrow('Unsupported secret mutation')
    await expect(
      store.run('UPDATE envs SET control_secret = ? || ? WHERE id = ?', 'part', 'two', env.id),
    ).rejects.toThrow('Secret mutation must assign one parameter')
    expect((await store.envById(env.id))?.control_secret).toBe(env.control_secret)
    expect(
      await store.run('UPDATE envs SET control_secret = ? WHERE id = ? RETURNING id', 'replacement', env.id),
    ).toMatchObject({ changes: 1 })
    expect((await store.envById(env.id))?.control_secret).toBe('replacement')
    const [stored] = await fixture.source.query(`SELECT control_secret FROM ${fixture.schema}.envs WHERE id=$1`, [
      env.id,
    ])
    expect(stored.control_secret).not.toBe('replacement')
  })

  test('secret references resolve within their App or organization and writes keep values out of activity', async () => {
    const app = await createApp(ctx, 'secret-scopes')
    const otherApp = await createApp(ctx, 'separate-secrets')
    const inherited = await createApp(
      { store: new Store(fixture.source, otherOrg, fixture.encryption, fixture.schema) } as Ctx,
      'other-organization',
    )
    await fixture.store.run(
      'INSERT INTO org_secrets (org_id,name,value,updated_at) VALUES (?,?,?,?)',
      fixture.organizationId,
      'org/cache',
      'shared-cache',
      now(),
    )
    const first = await setAppSecret(ctx, app, 'cache', 'first-cache', 'user:one')
    const next = await setAppSecret(ctx, app, 'app/cache', 'second-cache', 'user:two')
    expect(first).toMatchObject({ name: 'app/cache', created: true })
    expect(next).toMatchObject({ name: 'app/cache', created: false })
    expect(await secretValue(ctx, app, 'app/cache')).toBe('second-cache')
    expect(await secretValue(ctx, otherApp, 'app/cache')).toBeUndefined()
    expect(await secretValue(ctx, otherApp, 'org/cache')).toBe('shared-cache')
    expect(await secretValue(ctx, inherited, 'org/cache')).toBeUndefined()
    expect(await appSecretNames(ctx, app.id)).toEqual([{ name: 'app/cache', updated_at: next.updated_at }])
    expect(await orgSecretNames(ctx, otherOrg)).toEqual([])
    for (const [name, value] of [
      ['org/cache', 'sample'],
      ['empty', ''],
      ['large', 'x'.repeat(65_537)],
    ]) {
      await expect(setAppSecret(ctx, app, name, value, 'actor')).rejects.toMatchObject({ code: 'invalid_request' })
    }
    await deleteAppSecret(ctx, app, 'app/cache', 'user:one')
    await expect(deleteAppSecret(ctx, app, 'cache', 'user:one')).rejects.toMatchObject({ code: 'not_found' })
    expect(await secretValue(ctx, app, 'app/cache')).toBeUndefined()
    expect(await secretValue(ctx, app, 'org/cache')).toBe('shared-cache')
    const events = await fixture.store.all<{ action: string; detail: string }>(
      "SELECT action, detail FROM activity WHERE app_id = ? AND action LIKE 'secret.%' ORDER BY id",
      app.id,
    )
    expect(events.map((e) => [e.action, JSON.parse(e.detail)])).toEqual([
      ['secret.set', { name: 'app/cache' }],
      ['secret.update', { name: 'app/cache' }],
      ['secret.delete', { name: 'app/cache' }],
    ])
  })
})