Files
streamline/control-server/test/eddy_crashes.integration.test.ts
2026-11-16 17:26:44 -08:00

108 lines
8.1 KiB
TypeScript

import './setup_env';
import { afterAll, expect, mock, test } from 'bun:test';
import { createHash, randomBytes } from 'node:crypto';
import { crashBody } from './fixtures/eddy_crash';
// Real PostgreSQL only; without TEST_DATABASE_URL nothing below is imported or mocked.
const run = process.env.TEST_DATABASE_URL ? test : test.skip;
const BASELINE = 'crash-fixture-' + randomBytes(4).toString('hex');
let ctx: any = null;
if (process.env.TEST_DATABASE_URL) {
mock.module('../src/sso', () => ({ resolveSsoEmail: async (h: Headers) =>
({ employee: 'crash-employee@bytedance.com', admin: 'crash-admin@bytedance.com' } as Record<string, string>)[h.get('x-tt-session-v2') || ''] ?? null }));
mock.module('../src/admin_db', () => ({ isAdminPrefix: async (p: string) => p === 'crash-admin', normPrefix: (s: string) => s.split('@')[0] }));
mock.module('../src/cluster', () => ({ allEnrichedNodes: async () => [], callNodeAbsolute: async () => { throw new Error('no satellites in this test'); } }));
const { eddyApi } = await import('../src/routes_eddy');
const { db, closePool } = await import('../src/db_client');
const s = await import('../src/schema');
const { eq, inArray } = await import('drizzle-orm');
const crashes = await import('../src/eddy_crashes');
ctx = { eddyApi, db, closePool, s, eq, inArray, crashes };
}
const post = (path: string, body: unknown, headers: Record<string, string> = {}) => ctx.eddyApi.request(path, {
method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body),
});
const admin = (path: string) => ctx.eddyApi.request(path, { headers: { 'x-tt-session-v2': 'admin' } });
async function eddySession() {
const verifier = randomBytes(32).toString('base64url');
const body = { state: randomBytes(32).toString('base64url'), code_challenge: createHash('sha256').update(verifier).digest('base64url'),
code_challenge_method: 'S256', redirect_uri: 'http://127.0.0.1:49152/eddy/sso/callback' };
const redirect = new URL((await (await post('/auth/authorize', body, { 'x-tt-session-v2': 'employee' })).json() as any).redirect);
const token: any = await (await post('/auth/token', { code: redirect.searchParams.get('code'), code_verifier: verifier, redirect_uri: body.redirect_uri })).json();
return token.access_token as string;
}
const report = (id: string, over: Record<string, unknown> = {}, files?: Record<string, string>) =>
crashBody({ id, baseline: BASELINE, ...over }, files);
const ids: string[] = [];
const newId = () => { const id = `crash-20261021T0841${String(ids.length).padStart(2, '0')}-${randomBytes(4).toString('hex')}`; ids.push(id); return id; };
run('X-Eddy-User alone stores nothing; an Eddy session stores a report and its reporter updates it', async () => {
const id = newId();
const signature = 'crash:EXC_BAD_ACCESS:0badf00d';
const anonymous = await post('/crashes', report(id), { 'x-eddy-user': 'someone' });
expect(anonymous.status).toBe(401);
expect((await anonymous.json() as any).code).toBe('eddy_login_required');
const headers = { authorization: 'Bearer ' + await eddySession() };
// Sent when it happened (task without edits): the supervisor's first guess.
const first = await post('/crashes', report(id, { class: 'devicesim', confidence: 'suspected', note: '', signature }), headers);
expect(first.status).toBe(200);
expect(await first.json()).toEqual({ id, duplicate: false, updated: false });
expect((await post('/crashes', report(newId(), { class: 'task-edit' }), headers)).status).toBe(400);
const [row] = await ctx.db.select().from(ctx.s.eddy_observations).where(ctx.eq(ctx.s.eddy_observations.id, id));
expect([row.user, row.signature, row.kind, row.macos, row.machine]).toEqual(['crash-employee', signature, 'crash', '26', '0123456789abcdef']);
expect(JSON.parse(row.payload).kind).toBe('crash-report');
// Grouped like any observation; the new problem takes the report's owner (DeviceSim repair can start).
const problem = async () => JSON.parse((await ctx.db.select().from(ctx.s.eddy_problems).where(ctx.eq(ctx.s.eddy_problems.baseline, BASELINE)))[0].knowledge);
expect(await problem()).toMatchObject({ category: 'devicesim', confidence: 'suspected', source: 'crash-report' });
// The agent confirms a different owner: the same reporter's resend updates the report and the problem.
const confirmed = report(id, { class: 'eddy', confidence: 'confirmed', note: '关掉 app_compat 后不再崩', signature });
expect(await (await post('/crashes', confirmed, headers)).json()).toEqual({ id, duplicate: true, updated: true });
const [updated] = await ctx.db.select().from(ctx.s.eddy_observations).where(ctx.eq(ctx.s.eddy_observations.id, id));
expect(JSON.parse(updated.payload).report).toMatchObject({ class: 'eddy', confidence: 'confirmed' });
expect(await problem()).toMatchObject({ category: 'eddy', confidence: 'confirmed', cause: '关掉 app_compat 后不再崩' });
// Someone else cannot rewrite it, and a weaker guess does not replace a confirmed owner.
const other = await post('/crashes', report(id, { class: 'app', signature }), { 'x-tt-session-v2': 'admin' });
expect(await other.json()).toEqual({ id, duplicate: true, updated: false });
await post('/crashes', report(id, { class: 'devicesim', confidence: 'suspected', signature }), headers);
expect(await problem()).toMatchObject({ category: 'eddy', confidence: 'confirmed' });
});
run('a classified problem keeps its classification', async () => {
const signature = 'missing-selector:KMPBridgeNUJExperimentManager:smallScreenOptEnabled';
const now = Date.now();
const knowledge = JSON.stringify({ category: 'app-compat', confidence: 'confirmed', summary: 'admin', cause: '', solution: '', validation: '', rollback: '', classifiedBy: 'crash-admin' });
await ctx.db.insert(ctx.s.eddy_problems).values({ signature, baseline: BASELINE, kind: 'missing-selector', status: 'open', scope: '{}', aliases: '[]', knowledge, firstSeen: now, lastSeen: now });
const headers = { authorization: 'Bearer ' + await eddySession() };
expect((await post('/crashes', report(newId(), { signature }), headers)).status).toBe(200);
const [problem] = await ctx.db.select().from(ctx.s.eddy_problems).where(ctx.eq(ctx.s.eddy_problems.signature, signature));
expect(problem.knowledge).toBe(knowledge);
});
run('maintainers list by class, open the whole report and download only its own files', async () => {
const headers = { authorization: 'Bearer ' + await eddySession() };
const id = newId();
expect((await post('/crashes', report(id, { class: 'eddy', signature: 'crash:EXC_CRASH:eddy0001' }), headers)).status).toBe(200);
expect((await ctx.eddyApi.request('/admin/crashes', { headers })).status).toBe(401); // an Eddy session is not an administrator
const listed: any = await (await admin(`/admin/crashes?class=eddy&baseline=${BASELINE}`)).json();
expect(listed.crashes.map((c: any) => c.id)).toEqual([id]);
expect(listed.crashes[0]).toMatchObject({ class: 'eddy', user: 'crash-employee', versions: { deviceSim: { version: '2026.10.21.1' } } });
const { crash }: any = await (await admin('/admin/crashes/' + id)).json();
expect(crash.report.launch.devicesim).toEqual({ DEVICESIM_CAMERA_MODE: 'mac' });
const devicesimLog = crash.files.find((f: any) => f.name === 'devicesim.log');
const download = await admin(devicesimLog.url.replace('/api/eddy', ''));
expect(Buffer.from(await download.arrayBuffer()).toString()).toBe('[devicesim] camera: dual');
const other = createHash('sha256').update('not in this report').digest('hex');
expect((await admin(`/admin/crashes/${id}/files/${other}`)).status).toBe(404);
expect((await admin('/admin/crashes/crash-nope')).status).toBe(404);
// What a DeviceSim repair agent receives with the problem.
const forRepair = await ctx.crashes.crashesFor(BASELINE, ['crash:EXC_CRASH:eddy0001']);
expect(forRepair.map((r: any) => r.id)).toEqual([id]);
});
afterAll(async () => {
if (!ctx) return;
await ctx.db.delete(ctx.s.eddy_observations).where(ctx.inArray(ctx.s.eddy_observations.id, ids));
await ctx.db.delete(ctx.s.eddy_problems).where(ctx.eq(ctx.s.eddy_problems.baseline, BASELINE));
await ctx.closePool();
});