Skip to content

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

21.3 KB
Raw Blame
import { BoxDesiredState } from '../../box/enums/box-desired-state.enum'
import { BoxState } from '../../box/enums/box-state.enum'
import { BoxUsagePeriodArchive } from '../../usage/entities/box-usage-period-archive.entity'
import { BoxUsagePeriod } from '../../usage/entities/box-usage-period.entity'
import { AdminOrganizationOverviewService } from './organization-overview.service'

const queryBuilder = () => {
  const builder: Record<string, jest.Mock> = {}
  for (const method of [
    'select',
    'addSelect',
    'where',
    'andWhere',
    'innerJoin',
    'groupBy',
    'addGroupBy',
    'orderBy',
    'addOrderBy',
    'setParameters',
    'take',
    'addCommonTableExpression',
    'from',
  ]) {
    builder[method] = jest.fn(() => builder)
  }
  builder.getRawMany = jest.fn().mockResolvedValue([])
  builder.getMany = jest.fn().mockResolvedValue([])
  return builder
}
const repository = () => {
  const builder = queryBuilder()
  const managerBuilder = queryBuilder()
  return {
    find: jest.fn().mockResolvedValue([]),
    findOne: jest.fn(),
    createQueryBuilder: jest.fn(() => builder),
    builder,
    // Default snapshot: runs the callback with a manager that reports no usage rows.
    manager: {
      builder: managerBuilder,
      createQueryBuilder: jest.fn(() => managerBuilder),
      transaction: jest.fn(async (_level: unknown, run: (snapshot: unknown) => unknown) =>
        run({ find: jest.fn().mockResolvedValue([]) }),
      ),
    },
  }
}
// A `find` without `take` streams however many rows the table happens to hold, so the
// page bound on the response says nothing about the work behind it.
const unboundedFinds = (find: jest.Mock) =>
  find.mock.calls.filter(([options]) => options && typeof options === 'object' && !('take' in options))
const serviceWith = () => {
  const organizations = repository()
  const memberships = repository()
  const users = repository()
  const boxes = repository()
  const usagePeriods = repository()
  const activation = { get: jest.fn().mockResolvedValue(null) }
  const service = new AdminOrganizationOverviewService(
    organizations as never,
    memberships as never,
    users as never,
    boxes as never,
    usagePeriods as never,
    activation as never,
  )
  return { service, organizations, memberships, users, boxes, usagePeriods, activation }
}

describe('organization policy inventory reads', () => {
  const organization = {
    id: '00000000-0000-4000-8000-000000000001',
    name: 'Example',
    createdBy: 'creator',
    createdAt: new Date('2026-10-01T00:00:00Z'),
    updatedAt: new Date('2026-10-01T00:00:00Z'),
  }

  it('keeps email verification out of the organization detail response', async () => {
    const { service, organizations, users } = serviceWith()
    organizations.findOne.mockResolvedValue(organization)
    users.find.mockResolvedValue([
      { id: 'creator', email: '[email protected]', name: 'Creator', emailVerified: true },
    ])

    const detail = await service.detail(organization.id, { memberLimit: 50, boxLimit: 50 })

    expect(detail?.creator).toEqual({ userId: 'creator', email: '[email protected]', displayName: 'Creator' })
  })

  it('keeps the detail user query limited to its original fields', async () => {
    const { service, organizations, users } = serviceWith()
    organizations.findOne.mockResolvedValue(organization)

    await service.detail(organization.id, { memberLimit: 50, boxLimit: 50 })

    expect(users.find).toHaveBeenCalledWith(expect.objectContaining({ select: { id: true, email: true, name: true } }))
  })

  it.each([true, false, undefined])('preserves list verification %s', async (emailVerified) => {
    const { service, organizations, users } = serviceWith()
    organizations.builder.getMany.mockResolvedValue([organization])
    const stored = { id: 'creator', email: '[email protected]', name: 'Creator', emailVerified }
    users.find.mockImplementation(async ({ select }) => [
      Object.fromEntries(Object.entries(stored).filter(([key]) => select[key])),
    ])

    const page = await service.list({ limit: 200, boxCountScope: 'all' })

    if (emailVerified === undefined) expect(page.items[0].creator).not.toHaveProperty('emailVerified')
    else expect(page.items[0].creator).toHaveProperty('emailVerified', emailVerified)
  })

  it('reads registration and all-state inventory with page-scoped aggregation', async () => {
    const { service, organizations, memberships, users, boxes } = serviceWith()
    organizations.builder.getMany.mockResolvedValue([organization])
    users.find.mockResolvedValue([
      { id: 'creator', email: '[email protected]', name: 'Creator', emailVerified: true },
    ])

    const page = await service.list({ limit: 200, boxCountScope: 'all' })

    expect(memberships.createQueryBuilder).toHaveBeenCalledTimes(1)
    expect(boxes.createQueryBuilder).toHaveBeenCalledTimes(1)
    expect(page.items[0]).toMatchObject({
      organizationId: organization.id,
      createdAt: organization.createdAt.toISOString(),
      createdBy: 'creator',
      creator: { userId: 'creator', email: '[email protected]', emailVerified: true },
    })
    expect(page.items[0]).toHaveProperty('boxCount', 0)
    expect(page.items[0]).toHaveProperty('memberCount', 0)
    expect(page.items[0]).toHaveProperty('impactState', 'not_impacted')
  })

  it('reads member emails for the page only when the list includes them', async () => {
    const { service, organizations, memberships } = serviceWith()
    const empty = { ...organization, id: '00000000-0000-4000-8000-000000000002' }
    const nextPage = { ...organization, id: '00000000-0000-4000-8000-000000000003' }
    organizations.builder.getMany.mockResolvedValue([organization, empty, nextPage])

    const plain = await service.list({ limit: 2 })

    expect(memberships.createQueryBuilder).toHaveBeenCalledTimes(1)
    expect(memberships.manager.createQueryBuilder).not.toHaveBeenCalled()
    for (const item of plain.items) expect(item).not.toHaveProperty('memberEmails')

    // organizationStats() builds its members query first; the email ranking comes second.
    const ranked = queryBuilder()
    memberships.createQueryBuilder.mockReturnValueOnce(memberships.builder).mockReturnValueOnce(ranked)
    memberships.manager.builder.getRawMany.mockResolvedValue([
      { organizationId: organization.id, email: '[email protected]' },
      { organizationId: organization.id, email: '[email protected]' },
    ])

    const included = await service.list({ limit: 2, includeMemberEmails: true })

    expect(included.items).toEqual([
      expect.objectContaining({
        organizationId: organization.id,
        memberEmails: ['[email protected]', '[email protected]'],
      }),
      expect.objectContaining({ organizationId: empty.id, memberEmails: [] }),
    ])
    expect(ranked.where).toHaveBeenCalledWith(expect.any(String), { organizationIds: [organization.id, empty.id] })
    expect(memberships.manager.builder.where).toHaveBeenCalledWith(expect.any(String), { memberEmailLimit: 200 })
  })

  it('skips the member email read for an empty page', async () => {
    const { service, memberships } = serviceWith()

    const page = await service.list({ limit: 50, includeMemberEmails: true })

    expect(page.items).toEqual([])
    expect(memberships.manager.createQueryBuilder).not.toHaveBeenCalled()
  })

  it('counts retained destroyed and archived rows without changing impact', async () => {
    const { service, organizations, boxes } = serviceWith()
    organizations.builder.getMany.mockResolvedValue([organization])
    boxes.builder.getRawMany.mockResolvedValue(
      [BoxState.DESTROYED, BoxState.ARCHIVED].map((state) => ({
        organizationId: organization.id,
        state,
        desiredState: BoxDesiredState.STARTED,
        boxCount: '1',
        observedAt: organization.updatedAt,
      })),
    )

    const expanded = await service.list(Object.assign({ limit: 200 }, { boxCountScope: 'all' as const }))
    expect(expanded.items[0]).toMatchObject({ boxCount: 2, impactState: 'not_impacted' })
    expect((await service.list({ limit: 200 })).items[0]).toMatchObject({
      boxCount: 0,
      impactState: 'not_impacted',
    })
  })
})

describe('AdminOrganizationOverviewService', () => {
  afterEach(() => jest.useRealTimers())

  it.each([true, false])('projects the stored suspension flag %s from the selected row', async (suspended) => {
    const { service, organizations } = serviceWith()
    const stored = {
      id: 'org-1',
      name: 'Example',
      createdAt: new Date('2026-10-01T00:00:00Z'),
      createdBy: 'creator-1',
      updatedAt: new Date('2026-10-20T00:00:00Z'),
      suspended,
    }
    organizations.findOne.mockImplementation(async ({ select }: { select: Record<string, boolean> }) =>
      Object.fromEntries(Object.entries(stored).filter(([column]) => select[column])),
    )

    const result = await service.detail('org-1', { memberLimit: 50, boxLimit: 50 })

    expect(result).toHaveProperty('suspended', suspended)
    expect(organizations.findOne).toHaveBeenCalledTimes(1)
    expect(organizations.findOne).toHaveBeenCalledWith(
      expect.objectContaining({ select: expect.objectContaining({ suspended: true }) }),
    )
  })

  it('omits usage reads by default and reads the stored creator independently of membership', async () => {
    const { service, organizations, memberships, users, boxes, usagePeriods, activation } = serviceWith()
    organizations.findOne.mockResolvedValue({
      id: 'org-1',
      name: 'Example',
      createdAt: new Date('2026-10-01T00:00:00Z'),
      createdBy: 'original-creator',
      updatedAt: new Date('2026-10-20T00:00:00Z'),
    })
    memberships.find.mockResolvedValue([])
    boxes.find.mockResolvedValue([])
    users.find.mockResolvedValue([{ id: 'original-creator', email: '[email protected]', name: 'Creator' }])
    const query = { memberLimit: 50, boxLimit: 50 }
    const result = await service.detail('org-1', query)
    expect(usagePeriods.manager.transaction).not.toHaveBeenCalled()
    expect(result).toMatchObject({
      createdAt: '2026-10-01T00:00:00.000Z',
      createdBy: 'original-creator',
      creator: { userId: 'original-creator', email: '[email protected]' },
    })
    expect(result).not.toHaveProperty('usage')
    expect(result).not.toHaveProperty('activation')
    expect(activation.get).not.toHaveBeenCalled()
    activation.get.mockResolvedValue({ organizationId: 'org-1', lastBoxCreatedAt: null } as never)
    const expanded = await service.detail('org-1', { ...query, includeActivation: true })
    expect(expanded?.activation).toEqual({ organizationId: 'org-1', lastBoxCreatedAt: null })
    expect(activation.get).toHaveBeenCalledWith('org-1')
    expect(usagePeriods.manager.transaction).not.toHaveBeenCalled()
  })

  it('returns the organization projection and treats wildcard characters literally', async () => {
    const { service, organizations, memberships, boxes } = serviceWith()
    organizations.builder.getMany.mockResolvedValue([
      {
        id: 'org-1',
        name: 'Acme',
        createdAt: new Date('2026-08-01T00:00:00Z'),
        createdBy: 'usr-1',
        updatedAt: new Date('2026-08-30T01:00:00Z'),
      },
    ])
    memberships.builder.getRawMany.mockResolvedValue([{ organizationId: 'org-1', memberCount: '2' }])
    boxes.builder.getRawMany.mockResolvedValue([
      {
        organizationId: 'org-1',
        state: BoxState.STARTED,
        desiredState: BoxDesiredState.STARTED,
        boxCount: '1',
        observedAt: new Date('2026-08-30T01:00:00Z'),
      },
    ])

    await expect(service.list({ query: 'Acme_%', limit: 50 })).resolves.toEqual({
      items: [
        {
          organizationId: 'org-1',
          name: 'Acme',
          createdAt: '2026-08-01T00:00:00.000Z',
          createdBy: 'usr-1',
          creator: null,
          memberCount: 2,
          boxCount: 1,
          impactState: 'not_impacted',
          observedAt: '2026-08-30T01:00:00.000Z',
        },
      ],
      nextCursor: null,
      limit: 50,
      observedAt: '2026-08-30T01:00:00.000Z',
    })
    expect(organizations.builder.andWhere).toHaveBeenCalledWith('organization.name ILIKE :search', {
      searchId: 'Acme_%',
      search: '%Acme\\_\\%%',
    })
    expect(boxes.find).not.toHaveBeenCalled()
  })

  it('keeps creator identity when the user has no email and batches creators for the page', async () => {
    const { service, organizations, users, usagePeriods } = serviceWith()
    organizations.builder.getMany.mockResolvedValue([
      {
        id: '00000000-0000-4000-8000-000000000001',
        name: 'Example',
        createdBy: 'creator',
        createdAt: new Date('2026-10-01T00:00:00Z'),
        updatedAt: new Date('2026-10-01T00:00:00Z'),
      },
    ])
    users.find.mockResolvedValue([{ id: 'creator', email: '', name: 'Creator' }])
    const page = await service.list({ limit: 2 })
    expect(page.items[0]).toMatchObject({ createdBy: 'creator', creator: { userId: 'creator', email: null } })
    expect(users.find).toHaveBeenCalledTimes(1)
    expect(usagePeriods.manager.transaction).not.toHaveBeenCalled()
  })

  it('composes bounded member and box partitions without sensitive fields', async () => {
    jest.useFakeTimers().setSystemTime(new Date('2026-08-31T00:00:00Z'))
    const { service, organizations, memberships, users, boxes, usagePeriods } = serviceWith()
    const observedAt = new Date('2026-08-30T01:00:00Z')
    organizations.findOne.mockResolvedValue({
      id: 'org-1',
      name: 'Acme',
      createdAt: new Date('2026-08-01T00:00:00Z'),
      createdBy: 'usr-1',
      updatedAt: observedAt,
    })
    memberships.find.mockResolvedValue([{ userId: 'usr-1', role: 'owner', createdAt: observedAt }])
    users.find.mockResolvedValue([{ id: 'usr-1', email: '[email protected]', name: 'Ops' }])
    boxes.find.mockResolvedValue([
      {
        id: 'box-1',
        organizationId: 'org-1',
        name: 'api',
        state: BoxState.STARTED,
        desiredState: BoxDesiredState.STARTED,
        runnerId: null,
        region: 'sgp-a',
        updatedAt: observedAt,
      },
    ])
    const snapshot = {
      find: jest.fn(async (entity: unknown) =>
        entity === BoxUsagePeriod
          ? [{ startAt: new Date('2026-08-30T00:00:00Z'), endAt: new Date('2026-08-30T01:00:00Z'), cpu: 1, disk: 2 }]
          : [{ startAt: new Date('2026-08-29T00:00:00Z'), endAt: new Date('2026-08-29T00:30:00Z'), cpu: 2, disk: 1 }],
      ),
    }
    usagePeriods.manager.transaction.mockImplementation(async (_level: unknown, run: (m: unknown) => unknown) =>
      run(snapshot),
    )

    const dossier = await service.detail('org-1', { memberLimit: 50, boxLimit: 50, includeUsage: true })
    expect(dossier).toMatchObject({
      organizationId: 'org-1',
      name: 'Acme',
      members: { items: [{ userId: 'usr-1', email: '[email protected]', organizationRole: 'owner' }] },
      boxes: { items: [{ id: 'box-1', name: 'api', observedState: 'started', desiredState: 'started' }] },
      impact: { state: 'not_impacted' },
      usage: { computeSeconds: '7200', storageByteSeconds: '9663676416000' },
    })
    expect(snapshot.find.mock.calls.map(([entity]) => entity)).toEqual([BoxUsagePeriod, BoxUsagePeriodArchive])
    expect(JSON.stringify(dossier)).not.toMatch(/authToken|environment|errorReason|keyPair|publicKeys/)
  })

  it('reports global impact when the impacted box is outside the requested page', async () => {
    jest.useFakeTimers().setSystemTime(new Date('2026-08-31T00:00:00Z'))
    const { service, organizations, memberships, boxes, usagePeriods } = serviceWith()
    const observedAt = new Date('2026-08-30T01:00:00Z')
    organizations.findOne.mockResolvedValue({
      id: 'org-1',
      name: 'Acme',
      createdAt: new Date('2026-08-01T00:00:00Z'),
      createdBy: 'usr-1',
      updatedAt: observedAt,
    })
    memberships.find.mockResolvedValue([])
    boxes.find.mockResolvedValue([
      {
        id: 'box-1',
        organizationId: 'org-1',
        name: 'healthy',
        state: BoxState.STARTED,
        desiredState: BoxDesiredState.STARTED,
        runnerId: null,
        region: 'sgp-a',
        updatedAt: observedAt,
      },
      {
        id: 'box-2',
        organizationId: 'org-1',
        name: 'broken',
        state: BoxState.ERROR,
        desiredState: BoxDesiredState.STARTED,
        runnerId: null,
        region: 'sgp-a',
        updatedAt: observedAt,
      },
    ])

    boxes.builder.getMany.mockResolvedValue([
      {
        id: 'box-2',
        organizationId: 'org-1',
        name: 'broken',
        state: BoxState.ERROR,
        desiredState: BoxDesiredState.STARTED,
        runnerId: null,
        region: 'sgp-a',
        updatedAt: observedAt,
      },
    ])

    const dossier = await service.detail('org-1', { memberLimit: 1, boxLimit: 1 })

    expect(dossier).toMatchObject({
      boxes: { items: [{ id: 'box-1' }], nextCursor: expect.any(String) },
      impact: {
        state: 'impacted',
        evidence: [{ boxId: 'box-2', summary: 'broken: error (desired started)' }],
      },
    })
  })

  it('rejects an invalid organization cursor before querying the repository', async () => {
    const { service, organizations } = serviceWith()

    await expect(
      service.list({ cursor: Buffer.from('not-a-uuid').toString('base64url'), limit: 50 }),
    ).rejects.toMatchObject({ status: 400 })
    expect(organizations.createQueryBuilder).not.toHaveBeenCalled()
  })

  it('aggregates member and box counts in the database instead of loading their rows', async () => {
    const { service, organizations, memberships, boxes } = serviceWith()
    organizations.builder.getMany.mockResolvedValue([
      {
        id: 'org-1',
        name: 'Acme',
        createdAt: new Date('2026-08-01T00:00:00Z'),
        createdBy: 'usr-1',
        updatedAt: new Date('2026-08-30T01:00:00Z'),
      },
    ])

    await service.list({ limit: 200 })

    expect(memberships.createQueryBuilder).toHaveBeenCalled()
    expect(boxes.createQueryBuilder).toHaveBeenCalled()
    expect(unboundedFinds(memberships.find)).toEqual([])
    expect(unboundedFinds(boxes.find)).toEqual([])
  })

  it('bounds the organization detail box query to the requested page', async () => {
    const { service, organizations, memberships, boxes } = serviceWith()
    organizations.findOne.mockResolvedValue({
      id: 'org-1',
      name: 'Acme',
      createdAt: new Date('2026-08-01T00:00:00Z'),
      createdBy: 'usr-1',
      updatedAt: new Date('2026-08-30T01:00:00Z'),
    })
    memberships.find.mockResolvedValue([])
    boxes.find.mockResolvedValue([])
    await service.detail('org-1', { memberLimit: 25, boxLimit: 25 })

    expect(unboundedFinds(boxes.find)).toEqual([])
  })

  // An unprojected getMany() reads every Box column. `secrets` holds the real secret
  // values (box.dto.ts) and `authToken` is the box's own credential, and the evidence
  // below renders neither — so neither belongs in the API process.
  it('reads only the box columns the impact evidence renders', async () => {
    const { service, organizations, memberships, boxes } = serviceWith()
    organizations.findOne.mockResolvedValue({
      id: 'org-1',
      name: 'Acme',
      createdAt: new Date('2026-08-01T00:00:00Z'),
      createdBy: 'usr-1',
      updatedAt: new Date('2026-08-30T01:00:00Z'),
    })
    memberships.find.mockResolvedValue([])
    boxes.find.mockResolvedValue([])

    await service.detail('org-1', { memberLimit: 25, boxLimit: 25 })

    const [columns] = boxes.builder.select.mock.calls[0] ?? []
    expect(columns).toEqual(['box.id', 'box.name', 'box.state', 'box.desiredState', 'box.updatedAt'])
  })

  // list() decodes its cursor before it queries, so a malformed cursor is a 400 there.
  // Decoding after the lookup turns the same input into a 404 on an organization that
  // does not exist, and spends a round trip on one that does.
  it('rejects a malformed member cursor before reading the organization', async () => {
    const { service, organizations } = serviceWith()
    organizations.findOne.mockResolvedValue(null)

    await expect(
      // 'a' decodes to an empty string, so it is not a cursor this API ever handed out.
      service.detail('org-1', { memberCursor: 'a', memberLimit: 25, boxLimit: 25 }),
    ).rejects.toMatchObject({ status: 400 })
    expect(organizations.findOne).not.toHaveBeenCalled()
  })

  // Rollover deletes the live row and inserts a fresh-id archive copy in one transaction
  // (usage.service.ts). Two reads on two pool connections straddle that commit: the period
  // is counted twice or lost, and the archive id is new so it cannot be de-duplicated.
  it('reads live and archived usage from one snapshot', async () => {
    const { service, organizations, memberships, boxes, usagePeriods } = serviceWith()
    organizations.findOne.mockResolvedValue({
      id: 'org-1',
      name: 'Acme',
      createdAt: new Date('2026-08-01T00:00:00Z'),
      createdBy: 'usr-1',
      updatedAt: new Date('2026-08-30T01:00:00Z'),
    })
    memberships.find.mockResolvedValue([])
    boxes.find.mockResolvedValue([])
    const manager = { find: jest.fn().mockResolvedValue([]) }
    usagePeriods.manager.transaction.mockImplementation(async (_level: unknown, run: (m: unknown) => unknown) =>
      run(manager),
    )

    await service.detail('org-1', { memberLimit: 25, boxLimit: 25, includeUsage: true })

    expect(usagePeriods.manager.transaction).toHaveBeenCalledWith('REPEATABLE READ', expect.any(Function))
    expect(usagePeriods.find).not.toHaveBeenCalled()
    expect(manager.find).toHaveBeenCalledTimes(2)
  })
})