import './setup_env'; import { afterAll, expect, mock, test } from 'bun:test'; import { createHash, randomBytes } from 'node:crypto'; mock.module('../src/cluster', () => ({ allEnrichedNodes: async () => [], callNodeAbsolute: async () => { throw new Error('no runtime execution'); } })); mock.module('../src/sso', () => ({ resolveSsoEmail: async (h: Headers) => { const token = h.get('x-tt-session-v2'); return token === 'fixture-employee' ? 'sso-employee@bytedance.com' : token === 'fixture-admin' ? 'sso-admin@bytedance.com' : null; } })); mock.module('../src/admin_db', () => ({ isAdminPrefix: async (s: string) => s === 'sso-admin', normPrefix: (s: string) => s.split('@')[0] })); const run = process.env.TEST_DATABASE_URL ? test : test.skip; 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 { callbackUrl, authorizeInput } = await import('../src/eddy_sso'); const ids: string[] = []; const post = (path: string, body: unknown, headers = {}) => eddyApi.request(path, { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify(body), }); function request() { const verifier = randomBytes(32).toString('base64url'); return { verifier, 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' } }; } async function grant(who = 'employee') { const input = request(); const response = await post('/auth/authorize', input.body, { 'x-tt-session-v2': 'fixture-' + who }); expect(response.status).toBe(200); expect(response.headers.get('cache-control')).toBe('no-store'); const redirect = new URL((await response.json() as any).redirect); expect(redirect.searchParams.get('state')).toBe(input.body.state); return { ...input, code: redirect.searchParams.get('code')! }; } async function exchange(g: Awaited>) { return post('/auth/token', { code: g.code, code_verifier: g.verifier, redirect_uri: g.body.redirect_uri }); } function knowledge() { const id = 'sso-' + crypto.randomUUID(); ids.push(id); return { document: { schema: 'eddy-knowledge-v1', id, title: 'SSO fixture', category: 'unknown', confidence: 'suspected', problem: { description: 'local fixture only' }, solution: { description: 'reference', kind: 'advice', validation: 'fixture', rollback: 'disable' }, observedEnvironment: {}, origin: {}, attachments: [] }, files: {} }; } test('callback must be an exact IPv4 loopback URI; PKCE and state are mandatory', () => { for (const uri of ['https://evil.example/eddy/sso/callback', 'http://localhost:49152/eddy/sso/callback', 'http://127.0.0.1:80/eddy/sso/callback', 'http://127.0.0.1:49152/other', 'http://127.0.0.1:49152/eddy/sso/callback?next=evil', 'http://user@127.0.0.1:49152/eddy/sso/callback', 'http://2130706433:49152/eddy/sso/callback']) expect(() => callbackUrl(uri)).toThrow(); expect(() => authorizeInput({ ...request().body, code_challenge_method: 'plain' })).toThrow(); }); run('ordinary SSO employee signs in, contributes and revises as the same author; session cannot administer or publish', async () => { expect((await post('/auth/authorize', request().body)).status).toBe(401); expect((await eddyApi.request('/auth/authorize', { method: 'POST', body: '{}' })).status).toBe(415); expect((await post('/auth/authorize', { ...request().body, state: 'bad' }, { 'x-tt-session-v2': 'fixture-employee' })).status).toBe(400); const g = await grant(); // Invalid exchanges do not consume a valid code. expect((await post('/auth/token', { code: g.code, code_verifier: 'x'.repeat(43), redirect_uri: g.body.redirect_uri })).status).toBe(400); expect((await post('/auth/token', { code: g.code, code_verifier: g.verifier, redirect_uri: g.body.redirect_uri.replace('49152', '49153') })).status).toBe(400); const exchangedAt = Date.now(); const response = await exchange(g); expect(response.status).toBe(200); const session: any = await response.json(); expect(session.email).toBe('sso-employee@bytedance.com'); expect(session.scope).toBe('eddy:knowledge:write'); expect(session.expires_at).toBeGreaterThanOrEqual(exchangedAt + 30 * 86400_000); expect(session.expires_at).toBeLessThanOrEqual(Date.now() + 30 * 86400_000); expect((await exchange(g)).status).toBe(400); const headers = { authorization: 'Bearer ' + session.access_token, 'x-eddy-user': 'spoofed-admin' }; const body = knowledge(); expect((await post('/knowledge', body, headers)).status).toBe(200); const { getKnowledge } = await import('../src/eddy_knowledge'); expect((await getKnowledge(body.document.id))?.author).toBe('sso-employee'); body.document.title = 'revision'; expect((await post('/knowledge', body, { 'x-tt-session-v2': 'fixture-employee' })).status).toBe(200); const duplicate: any = await (await post('/knowledge', body, headers)).json(); expect(duplicate.duplicate).toBe(true); for (const path of ['/admin/releases/example', '/admin/releases/example/state', '/admin/knowledge/' + body.document.id + '/state', '/telemetry', '/compat/candidates']) expect((await post(path, { enabled: false }, headers)).status).toBe(401); const stored = await db.select().from(s.eddy_sso_sessions); expect(JSON.stringify(stored)).not.toContain(session.access_token); expect((await eddyApi.request('/auth/session', { headers })).status).toBe(200); expect((await post('/auth/logout', {}, headers)).status).toBe(200); expect((await post('/knowledge', body, headers)).status).toBe(401); expect((await eddyApi.request('/auth/session', { headers })).status).toBe(401); }); run('expired codes/sessions, parallel exchange and administrator SSO produce no broader client rights', async () => { const expired = await grant(); await db.update(s.eddy_sso_codes).set({ expiresAt: 1 }).where(eq(s.eddy_sso_codes.codeHash, createHash('sha256').update(expired.code).digest('hex'))); expect((await exchange(expired)).status).toBe(400); const g = await grant('admin'); const concurrent = await Promise.all([exchange(g), exchange(g)]); expect(concurrent.map(r => r.status).sort()).toEqual([200, 400]); const session: any = await concurrent.find(r => r.status === 200)!.json(); const headers = { authorization: 'Bearer ' + session.access_token }; const body = knowledge(); expect((await post('/knowledge', body, headers)).status).toBe(200); expect((await post('/admin/releases/example', {}, headers)).status).toBe(401); expect((await post('/admin/knowledge/' + body.document.id + '/state', { enabled: false }, headers)).status).toBe(401); await db.update(s.eddy_sso_sessions).set({ expiresAt: 1 }).where(eq(s.eddy_sso_sessions.tokenHash, createHash('sha256').update(session.access_token).digest('hex'))); expect((await post('/knowledge', body, headers)).status).toBe(401); }); afterAll(async () => { if (process.env.TEST_DATABASE_URL) { for (const table of [s.eddy_knowledge_changes, s.eddy_knowledge_refs, s.eddy_knowledge_revisions]) if (ids.length) await db.delete(table).where(inArray(table.knowledgeId, ids)); if (ids.length) await db.delete(s.eddy_knowledge).where(inArray(s.eddy_knowledge.id, ids)); const emails = ['sso-employee@bytedance.com', 'sso-admin@bytedance.com']; await db.delete(s.eddy_sso_codes).where(inArray(s.eddy_sso_codes.email, emails)); await db.delete(s.eddy_sso_sessions).where(inArray(s.eddy_sso_sessions.email, emails)); } await closePool(); });