|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { freebuffAttribution, outboxEvent, user } from '@sim/db/schema' |
| 3 | +import { generateId } from '@sim/utils/id' |
| 4 | +import { eq, inArray, sql } from 'drizzle-orm' |
| 5 | +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' |
| 6 | +import { freebuffAgenticOutboxHandlers } from '@/lib/analytics/freebuff-agentic/outbox' |
| 7 | +import { |
| 8 | + bindFreebuffAttribution, |
| 9 | + enqueueFreebuffUse, |
| 10 | +} from '@/lib/analytics/freebuff-agentic/service' |
| 11 | +import { |
| 12 | + readFreebuffAttribution, |
| 13 | + sealFreebuffAttribution, |
| 14 | +} from '@/lib/analytics/freebuff-agentic/token' |
| 15 | +import { processOutboxEventById } from '@/lib/core/outbox/service' |
| 16 | + |
| 17 | +/** Protects token secrecy, expiry, transactional rollback, replay identity and retry policy. */ |
| 18 | +const userId = generateId() |
| 19 | +const token = 'fixture-opaque-token-not-issued-by-freebuff' |
| 20 | +const executionId = generateId() |
| 21 | +const ids = [`freebuff:account_created:${userId}`, `freebuff:tool_used:${executionId}`] |
| 22 | + |
| 23 | +beforeAll(async () => { |
| 24 | + await db.insert(user).values({ |
| 25 | + id: userId, |
| 26 | + name: 'Fixture', |
| 27 | + email: `${userId}@example.test`, |
| 28 | + emailVerified: true, |
| 29 | + createdAt: new Date(), |
| 30 | + updatedAt: new Date(), |
| 31 | + }) |
| 32 | +}) |
| 33 | +afterAll(async () => { |
| 34 | + await db |
| 35 | + .delete(outboxEvent) |
| 36 | + .where( |
| 37 | + sql`${outboxEvent.id} like ${`freebuff:expire:${userId}:%`} or ${inArray(outboxEvent.id, ids)}` |
| 38 | + ) |
| 39 | + await db.delete(user).where(eq(user.id, userId)) |
| 40 | +}) |
| 41 | + |
| 42 | +beforeEach(async () => { |
| 43 | + await db |
| 44 | + .delete(outboxEvent) |
| 45 | + .where( |
| 46 | + sql`${outboxEvent.id} like ${`freebuff:expire:${userId}:%`} or ${inArray(outboxEvent.id, ids)}` |
| 47 | + ) |
| 48 | + await db.delete(freebuffAttribution).where(eq(freebuffAttribution.userId, userId)) |
| 49 | +}) |
| 50 | +afterEach(() => { |
| 51 | + vi.useRealTimers() |
| 52 | + vi.unstubAllGlobals() |
| 53 | +}) |
| 54 | +async function seedUse() { |
| 55 | + await bindFreebuffAttribution(userId, await sealFreebuffAttribution(token), new Date()) |
| 56 | + await db.transaction((tx) => enqueueFreebuffUse(tx, userId, executionId, new Date())) |
| 57 | +} |
| 58 | + |
| 59 | +describe('agentic attribution across committed outcomes', () => { |
| 60 | + it('rejects tampered and expired capture without exposing the bearer token', async () => { |
| 61 | + const sealed = await sealFreebuffAttribution(token) |
| 62 | + expect(sealed).not.toContain(token) |
| 63 | + expect((await readFreebuffAttribution(sealed))?.token).toBe(token) |
| 64 | + expect(await readFreebuffAttribution(`${sealed}00`)).toBeNull() |
| 65 | + vi.useFakeTimers() |
| 66 | + vi.setSystemTime(Date.now() + 31 * 24 * 60 * 60 * 1000) |
| 67 | + expect(await readFreebuffAttribution(sealed)).toBeNull() |
| 68 | + vi.useRealTimers() |
| 69 | + }) |
| 70 | + |
| 71 | + it('retains signup identity on repeated login and rolls back uncommitted use', async () => { |
| 72 | + const sealed = await sealFreebuffAttribution(token) |
| 73 | + const createdAt = new Date() |
| 74 | + await bindFreebuffAttribution(userId, sealed, createdAt) |
| 75 | + await bindFreebuffAttribution(userId, sealed) |
| 76 | + const [association] = await db |
| 77 | + .select() |
| 78 | + .from(freebuffAttribution) |
| 79 | + .where(eq(freebuffAttribution.userId, userId)) |
| 80 | + expect(association.encryptedToken).not.toContain(token) |
| 81 | + const [signup] = await db.select().from(outboxEvent).where(eq(outboxEvent.id, ids[0])) |
| 82 | + expect(signup.payload).toMatchObject({ |
| 83 | + eventType: 'account_created', |
| 84 | + occurredAt: createdAt.toISOString(), |
| 85 | + }) |
| 86 | + await expect( |
| 87 | + db.transaction(async (tx) => { |
| 88 | + await enqueueFreebuffUse(tx, userId, executionId, new Date()) |
| 89 | + throw new Error('rollback fixture') |
| 90 | + }) |
| 91 | + ).rejects.toThrow('rollback fixture') |
| 92 | + expect(await db.select().from(outboxEvent).where(eq(outboxEvent.id, ids[1]))).toHaveLength(0) |
| 93 | + const occurredAt = new Date() |
| 94 | + await db.transaction(async (tx) => { |
| 95 | + await enqueueFreebuffUse(tx, userId, executionId, occurredAt) |
| 96 | + await enqueueFreebuffUse(tx, userId, executionId, new Date(occurredAt.getTime() + 1)) |
| 97 | + }) |
| 98 | + const uses = await db.select().from(outboxEvent).where(eq(outboxEvent.id, ids[1])) |
| 99 | + expect(uses).toHaveLength(1) |
| 100 | + expect(uses[0].payload).toMatchObject({ |
| 101 | + eventType: 'tool_used', |
| 102 | + occurredAt: occurredAt.toISOString(), |
| 103 | + }) |
| 104 | + }) |
| 105 | + |
| 106 | + it('retries with original identity and treats deduplicated delivery as success', async () => { |
| 107 | + await seedUse() |
| 108 | + const requests: Record<string, unknown>[] = [] |
| 109 | + let count = 0 |
| 110 | + vi.stubGlobal('fetch', async (_url: string, init: RequestInit) => { |
| 111 | + requests.push(JSON.parse(String(init.body))) |
| 112 | + expect(init.headers).not.toHaveProperty('Authorization') |
| 113 | + return new Response( |
| 114 | + JSON.stringify(++count === 1 ? { error: 'busy' } : { accepted: true, deduped: true }), |
| 115 | + { status: count === 1 ? 503 : 200, headers: { 'Content-Type': 'application/json' } } |
| 116 | + ) |
| 117 | + }) |
| 118 | + expect(await processOutboxEventById(ids[1], freebuffAgenticOutboxHandlers)).toBe('pending') |
| 119 | + await db |
| 120 | + .update(outboxEvent) |
| 121 | + .set({ availableAt: new Date(0) }) |
| 122 | + .where(eq(outboxEvent.id, ids[1])) |
| 123 | + expect(await processOutboxEventById(ids[1], freebuffAgenticOutboxHandlers)).toBe('completed') |
| 124 | + expect(requests).toHaveLength(2) |
| 125 | + expect(requests[1]).toEqual(requests[0]) |
| 126 | + expect(requests[0]).toMatchObject({ |
| 127 | + conversionToken: token, |
| 128 | + eventType: 'tool_used', |
| 129 | + eventId: `tool_used:${executionId}`, |
| 130 | + }) |
| 131 | + vi.unstubAllGlobals() |
| 132 | + }) |
| 133 | + |
| 134 | + it.each(['network', 'server'])( |
| 135 | + 'erases credentials after three exhausted %s attempts', |
| 136 | + async (failure) => { |
| 137 | + await seedUse() |
| 138 | + let attempts = 0 |
| 139 | + vi.stubGlobal('fetch', async () => { |
| 140 | + attempts++ |
| 141 | + if (failure === 'network') throw new Error('fixture network failure') |
| 142 | + return new Response('{}', { status: 503 }) |
| 143 | + }) |
| 144 | + for (let attempt = 0; attempt < 3; attempt++) { |
| 145 | + await db |
| 146 | + .update(outboxEvent) |
| 147 | + .set({ availableAt: new Date(0) }) |
| 148 | + .where(eq(outboxEvent.id, ids[1])) |
| 149 | + expect(await processOutboxEventById(ids[1], freebuffAgenticOutboxHandlers)).toBe( |
| 150 | + attempt === 2 ? 'dead_letter' : 'pending' |
| 151 | + ) |
| 152 | + } |
| 153 | + const [event] = await db.select().from(outboxEvent).where(eq(outboxEvent.id, ids[1])) |
| 154 | + expect(attempts).toBe(3) |
| 155 | + expect(event.payload).toMatchObject({ |
| 156 | + deliveryStatus: 'retry_exhausted', |
| 157 | + encryptedToken: null, |
| 158 | + }) |
| 159 | + } |
| 160 | + ) |
| 161 | + |
| 162 | + it('records a terminal rejection without retrying invalid credentials', async () => { |
| 163 | + await seedUse() |
| 164 | + vi.stubGlobal( |
| 165 | + 'fetch', |
| 166 | + async () => new Response('{"error":"invalid_conversion_token"}', { status: 401 }) |
| 167 | + ) |
| 168 | + expect(await processOutboxEventById(ids[0], freebuffAgenticOutboxHandlers)).toBe('completed') |
| 169 | + const [event] = await db.select().from(outboxEvent).where(eq(outboxEvent.id, ids[0])) |
| 170 | + expect(event.payload).toMatchObject({ deliveryStatus: 'rejected', httpStatus: 401 }) |
| 171 | + expect(event.payload).toHaveProperty('encryptedToken', null) |
| 172 | + vi.unstubAllGlobals() |
| 173 | + }) |
| 174 | +}) |
0 commit comments