import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' // Mock config before any module imports 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 v1Sessions from '../routes/v1/sessions' import { storeReset, storeCreateEnvironment, storeGetEnvironment, storeRebindSessionEnvironment, storeUpdateEnvironment, } from '../store' import { initDatabase, resetDbSingleton, getDb } from '../db/sqlite' import { issueSessionToken } from '../auth/session' import { createUserDirectly } from './helpers/fixtures' import { createSession } from '../services/session' import { storeBindSession } from '../store' import { createWorkItem } from '../services/work-dispatch' /** * Session Attach endpoints (P1): * * - POST /v1/sessions/:id/attach — bind an existing session to a CLI env. * Ownership via canManageSession (G9), occupancy via work items, env * ownership + repl single-session cap enforced, idempotent re-entry. * - GET /v1/sessions/attachable — manageable, non-ACP, open sessions. * - GET /v1/sessions/:id/events — merged persisted + bus history for CLI * hydration (bridge auth, management rights required). */ function freshDb(): Database { try { resetDbSingleton() } catch {} const path = resolve( tmpdir(), `rcs-attach-${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 } } /** 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' } const JSON_HDRS = { 'Content-Type': 'application/json' } function createApp() { const app = new Hono() app.route('/v1/sessions', v1Sessions) return app } interface World { owner: { id: string; username: string } stranger: { id: string; username: string } envId: string sessionId: string } /** * Seed: owner user + own env (owner_user_id = owner) + own session bound to * the owner and the env. */ function seedWorld(db: Database, envWorkerType = 'repl'): World { const owner = createUser(db) const stranger = createUser(db) const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', workerType: envWorkerType, ownerUserId: owner.id, }) const session = createSession({ environment_id: env.id, title: 'Existing session', source: 'web', }) storeBindSession(session.id, owner.id, 'user') return { owner, stranger, envId: env.id, sessionId: session.id } } describe('POST /v1/sessions/:id/attach', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createApp() }) test('happy path: owner attaches own session to own env → 200 + work item + rebind', async () => { const world = seedWorld(db) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(200) const body = (await res.json()) as { status: string session_id: string work_item_id: string rebind: boolean } expect(body.status).toBe('attached') expect(body.session_id).toBe(world.sessionId) expect(body.work_item_id).toMatch(/^work_/) // Rebind persisted to SQLite. const row = db .query('SELECT environment_id FROM sessions WHERE id = $id') .get({ $id: world.sessionId }) as { environment_id: string } expect(row.environment_id).toBe(world.envId) }) test('idempotent re-entry: second attach on same env returns the existing work item', async () => { const world = seedWorld(db) const attach = () => app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) const first = await attach() expect(first.status).toBe(200) const firstBody = (await first.json()) as { work_item_id: string } const second = await attach() expect(second.status).toBe(200) const secondBody = (await second.json()) as { work_item_id: string idempotent: boolean } expect(secondBody.idempotent).toBe(true) expect(secondBody.work_item_id).toBe(firstBody.work_item_id) }) test('session_busy: active work item on a different env → 409', async () => { const world = seedWorld(db) const otherEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac2', ownerUserId: world.owner.id, }) // A worker already holds the lease on the other env. await createWorkItem(otherEnv.id, world.sessionId) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(409) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('session_busy') }) test('stale lease on a dead env does NOT occupy: crashed attach CLI is re-attachable', async () => { const world = seedWorld(db) const crashedEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'crashed', ownerUserId: world.owner.id, }) // kill -9 before deregister: the acked item stays on the now-dead env. // (The session itself is bound to world.envId — seedWorld — so a // successful attach here proves the dead-env lease was not honored.) await createWorkItem(crashedEnv.id, world.sessionId) storeUpdateEnvironment(crashedEnv.id, { status: 'disconnected' }) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(200) const body = (await res.json()) as { status: string rebind: boolean idempotent: boolean } expect(body.status).toBe('attached') // Session already points at the target env — no rebind, and a FRESH work // item (not the same-env idempotent path, which would return the dead // env's stale item). expect(body.rebind).toBe(false) expect(body.idempotent).toBeUndefined() }) test('idempotent re-entry bypasses manage-rights check for the env owner (doReconnect re-bind)', async () => { // Wait-mode scenario: a team admin bound the session to the CLI worker's // env; the worker itself has no manage rights on the session. The re-bind // after env loss must still succeed via the same-env idempotent path — // gated on env ownership (the worker owns its env), not session rights. const world = seedWorld(db) const cliOwner = createUser(db) const cliEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'cli-worker', ownerUserId: cliOwner.id, }) // The team-admin bind: the session is re-pointed to the CLI env with a // live work item (bare admin API key performs the attach). const first = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, ...ADMIN_KEY }, body: JSON.stringify({ environment_id: cliEnv.id }), }) expect(first.status).toBe(200) const { work_item_id } = (await first.json()) as { work_item_id: string } // Re-entry as the CLI owner (no manage rights, owns the env) → 200 with // the SAME work item. const second = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(cliOwner.id) }, body: JSON.stringify({ environment_id: cliEnv.id }), }) expect(second.status).toBe(200) const body = (await second.json()) as { idempotent: boolean work_item_id: string } expect(body.idempotent).toBe(true) expect(body.work_item_id).toBe(work_item_id) }) test('idempotent re-entry by a non-owner who knows session+env IDs → 403', async () => { // The idempotent path echoes the work-item id; a random authenticated // caller must not be able to probe bindings. Falls through to the full // checks → manage-rights 403. const world = seedWorld(db) const first = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(first.status).toBe(200) const second = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.stranger.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(second.status).toBe(403) }) test("stranger's rct token → 403 (canManageSession, G9)", async () => { const world = seedWorld(db) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.stranger.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(403) }) test('env owned by another user → 403 even for the session owner', async () => { const world = seedWorld(db) const foreignEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'foreign', ownerUserId: world.stranger.id, }) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: foreignEnv.id }), }) expect(res.status).toBe(403) }) test('unowned env → 409 environment_unowned (claim flow pending)', async () => { const owner = createUser(db) const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'unclaimed', }) const session = createSession({ environment_id: null, title: 'Web session', source: 'web', }) storeBindSession(session.id, owner.id, 'user') const res = await app.request(`/v1/sessions/${session.id}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(owner.id) }, body: JSON.stringify({ environment_id: env.id }), }) expect(res.status).toBe(409) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('environment_unowned') }) test('bare admin API key attaches to an unowned env (documented worker setup)', async () => { // Self-hosted workers connect with SALUZI_BRIDGE_OAUTH_TOKEN= // and no SALUZI_BRIDGE_USERNAME — the env they register is unowned until // claimed, and the direct-attach path never prints a claim URL. A hard // 409 here made `/rc --attach ` fail out of the box. Bare admin keys // are trusted credentials (ensureAttachAccess already audited their // session-manage bypass) — the bind is allowed. const owner = createUser(db) const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'cli-worker', }) const session = createSession({ environment_id: null, title: 'Web session', source: 'web', }) storeBindSession(session.id, owner.id, 'user') const res = await app.request(`/v1/sessions/${session.id}/attach`, { method: 'POST', headers: { ...JSON_HDRS, ...ADMIN_KEY }, body: JSON.stringify({ environment_id: env.id }), }) expect(res.status).toBe(200) const body = (await res.json()) as { status: string session_id: string work_item_id: string rebind: boolean } expect(body.status).toBe('attached') expect(body.session_id).toBe(session.id) expect(body.work_item_id).toMatch(/^work_/) expect(body.rebind).toBe(true) }) test('archived session → 409 session_closed', async () => { const world = seedWorld(db) const { archiveSession } = await import('../services/session') archiveSession(world.sessionId) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(409) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('session_closed') }) test('ACP session → 409 acp_session', async () => { const world = seedWorld(db) // ACP env with its own auto-created session. const acpEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'acp-agent', workerType: 'acp', ownerUserId: world.owner.id, }) const acpSession = createSession({ environment_id: acpEnv.id, title: 'ACP Agent', source: 'acp', }) storeBindSession(acpSession.id, world.owner.id, 'user') const res = await app.request(`/v1/sessions/${acpSession.id}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(409) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('acp_session') }) test('repl env at capacity → 409 worker_at_capacity', async () => { const world = seedWorld(db) // A second open session already lives on the repl env. const other = createSession({ environment_id: world.envId, title: 'Other session', source: 'web', }) storeBindSession(other.id, world.owner.id, 'user') const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(409) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('worker_at_capacity') }) test('missing environment_id → 400', async () => { const world = seedWorld(db) const res = await app.request(`/v1/sessions/${world.sessionId}/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({}), }) expect(res.status).toBe(400) }) test('unknown session id → 404', async () => { const world = seedWorld(db) const res = await app.request(`/v1/sessions/ses_does_not_exist/attach`, { method: 'POST', headers: { ...JSON_HDRS, Authorization: rctAuth(world.owner.id) }, body: JSON.stringify({ environment_id: world.envId }), }) expect(res.status).toBe(404) }) }) describe('GET /v1/sessions/attachable', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createApp() }) test('returns own manageable sessions, excludes ACP and closed', async () => { const world = seedWorld(db) // ACP session on an acp env — must be excluded. const acpEnv = storeCreateEnvironment({ secret: 'test-api-key', workerType: 'acp', ownerUserId: world.owner.id, }) createSession({ environment_id: acpEnv.id, title: 'ACP', source: 'acp' }) // Stranger's session — must be excluded. createSession({ environment_id: null, title: 'Stranger session', source: 'web', }) const res = await app.request('/v1/sessions/attachable', { headers: { Authorization: rctAuth(world.owner.id) }, }) expect(res.status).toBe(200) const list = (await res.json()) as Array<{ id: string; source: string }> expect(list).toHaveLength(1) expect(list[0]!.id).toBe(world.sessionId) expect(list[0]!.source).toBe('web') }) test('bare admin API key sees all non-ACP sessions', async () => { const world = seedWorld(db) const res = await app.request('/v1/sessions/attachable', { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(200) const list = (await res.json()) as Array<{ id: string }> expect(list.some(s => s.id === world.sessionId)).toBe(true) }) test('admin API key + unresolvable X-Username → 403 (consistent with attach)', async () => { // An explicit-but-unknown identity is a misconfiguration, not "see // everything" — the listing must be exactly as strict as // POST /:id/attach's ensureAttachAccess. await seedWorld(db) const res = await app.request('/v1/sessions/attachable', { headers: { ...ADMIN_KEY, 'X-Username': 'no_such_user_xyz' }, }) expect(res.status).toBe(403) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('forbidden') }) }) describe('GET /v1/sessions/:id/events (bridge auth)', () => { let app: Hono let db: Database beforeEach(() => { db = freshDb() storeReset() app = createApp() }) test('merges bus events chronologically for the session manager', async () => { const world = seedWorld(db) const { publishSessionEvent: publish } = await import( '../services/transport' ) publish( world.sessionId, 'user', { type: 'user', uuid: 'u-1', message: { role: 'user', content: 'hello' }, }, 'inbound', ) publish( world.sessionId, 'assistant', { type: 'assistant', uuid: 'a-1', message: { role: 'assistant', content: [{ type: 'text', text: 'hi' }] }, }, 'inbound', ) const res = await app.request(`/v1/sessions/${world.sessionId}/events`, { headers: { Authorization: rctAuth(world.owner.id) }, }) expect(res.status).toBe(200) const body = (await res.json()) as { events: Array<{ type: string; payload: { uuid?: string } }> } const kinds = body.events.map(e => e.type) expect(kinds).toContain('user') expect(kinds).toContain('assistant') const userEvent = body.events.find(e => e.type === 'user') expect(userEvent?.payload.uuid).toBe('u-1') }) test("stranger's rct token → 403", async () => { const world = seedWorld(db) const res = await app.request(`/v1/sessions/${world.sessionId}/events`, { headers: { Authorization: rctAuth(world.stranger.id) }, }) expect(res.status).toBe(403) }) test('env-owner relaxation: caller owning the bound env can read events (wait-mode hydration)', async () => { // P0-1b: a team admin binds a session to someone else's CLI env; that // CLI (no manage rights on the session) must still hydrate. const world = seedWorld(db) const cliOwner = createUser(db) // Re-point the session to the CLI owner's env via attach (admin mints). const cliEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'cli-worker', ownerUserId: cliOwner.id, }) const { storeRebindSessionEnvironment: rebind } = await import('../store') rebind(world.sessionId, cliEnv.id) const res = await app.request(`/v1/sessions/${world.sessionId}/events`, { headers: { Authorization: rctAuth(cliOwner.id) }, }) expect(res.status).toBe(200) }) }) describe('storeRebindSessionEnvironment', () => { test('re-points the session and persists the change', () => { const db = freshDb() storeReset() const world = seedWorld(db) const newEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac2', ownerUserId: world.owner.id, }) expect(storeRebindSessionEnvironment(world.sessionId, newEnv.id)).toBe(true) const record = storeGetEnvironment(newEnv.id) expect(record).toBeDefined() const row = db .query('SELECT environment_id FROM sessions WHERE id = $id') .get({ $id: world.sessionId }) as { environment_id: string } expect(row.environment_id).toBe(newEnv.id) }) test('returns false for unknown sessions', () => { const db = freshDb() storeReset() expect(storeRebindSessionEnvironment('ses_missing', 'env_x')).toBe(false) }) test('rebinding to null clears the binding (dispatch-failure rollback)', () => { const db = freshDb() storeReset() const world = seedWorld(db) const web = createSession({ environment_id: null, title: 'Web session', source: 'web', }) expect(storeRebindSessionEnvironment(web.id, world.envId)).toBe(true) expect(storeRebindSessionEnvironment(web.id, null)).toBe(true) const row = db .query('SELECT environment_id FROM sessions WHERE id = $id') .get({ $id: web.id }) as { environment_id: string | null } expect(row.environment_id).toBeNull() }) })