import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' mock.module('../config', () => mockConfigModule()) import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' import { tmpdir } from 'node:os' import { resolve } from 'node:path' import { unlinkSync, existsSync } from 'node:fs' import v1Environments from '../routes/v1/environments' import webEnvironments from '../routes/web/environments' import { storeReset } from '../store' import { initDatabase, resetDbSingleton, getDb } from '../db/sqlite' import { issueSessionToken } from '../auth/session' import { createUserDirectly } from './helpers/fixtures' /** * POST /v1/environments/bridge identity semantics (Fix 1 + Fix 2): * * - X-User-Id is resolved through resolveUserIdUuid — a raw value with no * matching users row fails loudly (400) instead of being stored verbatim * and silently mismatching the Web UI's owner_user_id === users.id check. * - Only an admin API key may register on behalf of another user; personal * rct_* tokens may only claim themselves (403 otherwise). * - X-Team-Id existence is checked unconditionally (400 instead of a * downstream FK error masquerading as 503); membership is enforced * whenever the caller resolves to a real user. */ function freshDb(): Database { try { resetDbSingleton() } catch {} const path = resolve( tmpdir(), `rcs-ownership-${randomUUID().replace(/-/g, '').slice(0, 8)}.db`, ) return initDatabase(path) } function createUser( db: Database, role = 'member', ): { id: string; username: string } { const username = `user_${randomUUID().slice(0, 6)}` const user = createUserDirectly(db, { username, role }) return { id: user.id, username: user.username } } function createTeam(db: Database, createdBy: string): string { const id = `team_${randomUUID().replace(/-/g, '')}` const now = new Date().toISOString() db.query( `INSERT INTO teams (id, name, slug, created_by, created_at, updated_at) VALUES ($id, $n, $s, $by, $now, $now)`, ).run({ $id: id, $n: 'Eng', $s: `eng-${id.slice(0, 6)}`, $by: createdBy, $now: now, }) db.query( `INSERT INTO team_members (team_id, user_id, role, added_at, added_by) VALUES ($t, $u, 'owner', $now, $by)`, ).run({ $t: id, $u: createdBy, $now: now, $by: createdBy }) return id } /** Bearer header with a SQLite rct_* token resolving to the users.id. */ function rctAuth(userId: string): string { return `Bearer ${issueSessionToken(userId, getDb()).accessToken}` } const ADMIN_KEY = { Authorization: 'Bearer test-api-key' } function createApp() { const app = new Hono() app.route('/v1/environments', v1Environments) app.route('/web', webEnvironments) return app } describe('POST /v1/environments/bridge — X-User-Id resolution (Fix 1)', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createApp() }) test('unresolvable X-User-Id → 400 with actionable message', async () => { const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ machine_name: 'mac1' }), }) // No header at all → claim flow, not an error. Use a garbage value: const bad = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json', 'X-User-Id': 'no-such-user', }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(200) expect(bad.status).toBe(400) const body = (await bad.json()) as { error: { message: string } } expect(body.error.message).toContain('no-such-user') expect(body.error.message).toContain('usr_') }) test('X-User-Id with a valid username resolves to the users.id UUID', async () => { const user = createUser(db) const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json', 'X-User-Id': user.username, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(200) // The stored owner is the UUID — visible through the Web UI filter. const webRes = await app.request('/web/environments', { headers: { Authorization: rctAuth(user.id) }, }) expect(webRes.status).toBe(200) const envs = (await webRes.json()) as Array<{ machine_name: string }> expect(envs).toHaveLength(1) expect(envs[0]!.machine_name).toBe('mac1') const row = db.query('SELECT owner_user_id FROM environments').get() as { owner_user_id: string } expect(row.owner_user_id).toBe(user.id) }) test('personal rct_* token + X-User-Id of another user → 403', async () => { const alice = createUser(db) const bob = createUser(db) const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { Authorization: rctAuth(alice.id), 'Content-Type': 'application/json', 'X-User-Id': bob.id, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(403) }) test('personal rct_* token + own X-User-Id → 200', async () => { const alice = createUser(db) const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { Authorization: rctAuth(alice.id), 'Content-Type': 'application/json', 'X-User-Id': alice.id, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(200) const row = db.query('SELECT owner_user_id FROM environments').get() as { owner_user_id: string } expect(row.owner_user_id).toBe(alice.id) }) }) describe('POST /v1/environments/bridge — X-Team-Id validation (Fix 2)', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createApp() }) test('bare admin API key + nonexistent team → 400 (not 503)', async () => { const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ machine_name: 'mac1' }), }) // Sanity: registration without a team works (baseline before the bad-team call). expect(res.status).toBe(200) const bad = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json', 'X-Team-Id': 'team_nope', }, body: JSON.stringify({ machine_name: 'mac2' }), }) expect(bad.status).toBe(400) const body = (await bad.json()) as { error: { type: string; message: string } } expect(body.error.type).toBe('bad_request') expect(body.error.message).toContain('team_nope') }) test('bare admin API key + valid team → 200, team_environments row written', async () => { const owner = createUser(db) const teamId = createTeam(db, owner.id) const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json', 'X-Team-Id': teamId, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(200) const { environment_id } = (await res.json()) as { environment_id: string } const row = db .query('SELECT team_id FROM team_environments WHERE environment_id = $e') .get({ $e: environment_id }) as { team_id: string } expect(row.team_id).toBe(teamId) }) test('X-Username provided but unresolvable + valid team → 403 (no silent relaxation)', async () => { const owner = createUser(db) const teamId = createTeam(db, owner.id) const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'X-Username': 'ghost-user', 'Content-Type': 'application/json', 'X-Team-Id': teamId, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(403) const body = (await res.json()) as { error: { message: string } } expect(body.error.message).toBe('User not found') }) test('non-member rct_* token + valid team → 403', async () => { const owner = createUser(db) const outsider = createUser(db) const teamId = createTeam(db, owner.id) const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { Authorization: rctAuth(outsider.id), 'Content-Type': 'application/json', 'X-Team-Id': teamId, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(403) const body = (await res.json()) as { error: { message: string } } expect(body.error.message).toBe('User is not a member of this team') }) test('offline ACP reuse + first-time X-Team-Id → session team binding backfilled', async () => { // The ACP reuse path re-creates its session binding from env ownership // read BEFORE the route writes the team_environments link — so a worker // restarted with X-Team-Id for the first time would leave its session // without a team owner. The route must backfill session_owners('team'). const member = createUser(db) const teamId = createTeam(db, member.id) const bridgeId = `grp_${randomUUID().slice(0, 8)}` // 1. First registration without a team → session bound to user only. const first = await app.request('/v1/environments/bridge', { method: 'POST', headers: { Authorization: rctAuth(member.id), 'Content-Type': 'application/json', }, body: JSON.stringify({ machine_name: 'acp1', worker_type: 'acp', bridge_id: bridgeId, }), }) expect(first.status).toBe(200) const { environment_id, session_id } = (await first.json()) as { environment_id: string session_id: string } const teamOwnerBefore = db .query( `SELECT 1 FROM session_owners WHERE session_id = $s AND owner_type = 'team'`, ) .get({ $s: session_id }) expect(teamOwnerBefore).toBeNull() // 2. Simulate disconnect → the env becomes reusable offline state. const { storeUpdateEnvironment } = await import('../store') storeUpdateEnvironment(environment_id, { status: 'offline' }) // 3. Re-register with X-Team-Id → reuse path hands back the same // env/session ids; the route then links the team and backfills. const second = await app.request('/v1/environments/bridge', { method: 'POST', headers: { Authorization: rctAuth(member.id), 'Content-Type': 'application/json', 'X-Team-Id': teamId, }, body: JSON.stringify({ machine_name: 'acp1', worker_type: 'acp', bridge_id: bridgeId, }), }) expect(second.status).toBe(200) const reused = (await second.json()) as { environment_id: string session_id: string } expect(reused.environment_id).toBe(environment_id) expect(reused.session_id).toBe(session_id) const teamOwner = db .query( `SELECT 1 FROM session_owners WHERE session_id = $s AND owner_type = 'team' AND owner_id = $t`, ) .get({ $s: session_id, $t: teamId }) expect(teamOwner).not.toBeNull() const link = db .query('SELECT 1 FROM team_environments WHERE environment_id = $e') .get({ $e: environment_id }) expect(link).not.toBeNull() }) }) describe('POST /v1/environments/bridge — idempotent re-registration (Fix 6)', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createApp() }) test('reattach with environment_id returns the same env, ownership kept', async () => { const user = createUser(db) const first = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json', 'X-User-Id': user.username, }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(first.status).toBe(200) const { environment_id } = (await first.json()) as { environment_id: string } // Restart with the pointer's environment_id — must reattach, not fork. const second = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ environment_id, machine_name: 'mac1-renamed', }), }) expect(second.status).toBe(200) const body = (await second.json()) as { environment_id: string } expect(body.environment_id).toBe(environment_id) // No duplicate row; identity fields refreshed; ownership untouched. const count = db.query('SELECT COUNT(*) AS c FROM environments').get() as { c: number } expect(count.c).toBe(1) const row = db .query( 'SELECT machine_name, owner_user_id, status FROM environments WHERE id = $id', ) .get({ $id: environment_id }) as { machine_name: string owner_user_id: string status: string } expect(row.machine_name).toBe('mac1-renamed') expect(row.owner_user_id).toBe(user.id) expect(row.status).toBe('active') }) test('unknown environment_id falls through to fresh creation', async () => { const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ environment_id: 'env_does_not_exist', machine_name: 'mac1', }), }) expect(res.status).toBe(200) const body = (await res.json()) as { environment_id: string } expect(body.environment_id).not.toBe('env_does_not_exist') expect(body.environment_id).toMatch(/^env_/) }) test('deregistered environment_id falls through to fresh creation', async () => { const first = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ machine_name: 'mac1' }), }) const { environment_id } = (await first.json()) as { environment_id: string } await app.request(`/v1/environments/bridge/${environment_id}`, { method: 'DELETE', headers: ADMIN_KEY, }) const second = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ environment_id, machine_name: 'mac1' }), }) expect(second.status).toBe(200) const body = (await second.json()) as { environment_id: string } expect(body.environment_id).not.toBe(environment_id) }) test('rct_* token of a non-owner + foreign environment_id → 403', async () => { const owner = createUser(db) const attacker = createUser(db) const first = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json', 'X-User-Id': owner.username, }, body: JSON.stringify({ machine_name: 'mac1' }), }) const { environment_id } = (await first.json()) as { environment_id: string } const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { Authorization: rctAuth(attacker.id), 'Content-Type': 'application/json', }, body: JSON.stringify({ environment_id, machine_name: 'hijacked' }), }) expect(res.status).toBe(403) // The env is untouched. const row = db .query( 'SELECT machine_name, owner_user_id FROM environments WHERE id = $id', ) .get({ $id: environment_id }) as { machine_name: string } expect(row.machine_name).toBe('mac1') }) test('claim token continues across re-registration of an unowned env', async () => { // Bare API key, no identity, no team → claim flow mints token A. const first = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(first.status).toBe(200) const firstBody = (await first.json()) as { environment_id: string claim_token: string } expect(firstBody.claim_token).toMatch(/^clm_/) // Restart with the pointer → same claim token comes back (the printed // claim URL stays valid instead of pointing at a token never stored). const second = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...ADMIN_KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ environment_id: firstBody.environment_id, machine_name: 'mac1', }), }) expect(second.status).toBe(200) const secondBody = (await second.json()) as { claim_token: string } expect(secondBody.claim_token).toBe(firstBody.claim_token) // And the continued token is the one persisted in the DB. const row = db .query('SELECT claim_token FROM environments WHERE owner_user_id IS NULL') .get() as { claim_token: string } expect(row.claim_token).toBe(firstBody.claim_token) }) })