forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnowflake-cortex.test.ts
More file actions
278 lines (247 loc) · 9.67 KB
/
Copy pathsnowflake-cortex.test.ts
File metadata and controls
278 lines (247 loc) · 9.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { describe, expect, test } from "bun:test"
import { OAUTH_DUMMY_KEY } from "../../src/auth"
import { oauthScope, SnowflakeCortexAuthPlugin } from "../../src/plugin/snowflake-cortex"
function makeInput() {
let auth: any = {
type: "oauth",
access: "access-old",
refresh: "refresh-old",
expires: Date.now() + 3600_000,
accountId: "myorg-myaccount",
}
const setCalls: Array<Record<string, unknown>> = []
return {
getAuth: async () => auth,
setAuth: (next: any) => {
auth = next
},
input: {
client: {
auth: {
set: async (request: any) => {
setCalls.push(request)
auth = request.body
},
},
},
} as any,
setCalls,
}
}
describe("plugin.snowflake-cortex", () => {
test("oauthScope uses Snowflake-compatible scope values", () => {
expect(oauthScope(undefined)).toBe("refresh_token")
expect(oauthScope("PUBLIC")).toBe("refresh_token session:role:PUBLIC")
expect(oauthScope("AUTH SNOWFLAKE")).toBe("refresh_token session:role-encoded:AUTH%20SNOWFLAKE")
})
test("loader returns empty options when auth is not oauth", async () => {
const hooks = await SnowflakeCortexAuthPlugin({} as any)
const options = await hooks.auth!.loader!(async () => ({ type: "api", key: "token" }) as any, {} as any)
expect(options).toEqual({})
})
test("loader injects bearer header and preserves custom headers", async () => {
const { input, getAuth, setAuth } = makeInput()
setAuth({
type: "oauth",
access: "access-live",
refresh: "refresh-live",
expires: Date.now() + 60 * 60 * 1000,
accountId: "myorg-myaccount",
})
const hooks = await SnowflakeCortexAuthPlugin(input)
const options = await hooks.auth!.loader!(getAuth as any, {} as any)
expect(options.apiKey).toBe(OAUTH_DUMMY_KEY)
const originalFetch = globalThis.fetch
const captured: Headers[] = []
globalThis.fetch = (async (_request, init) => {
captured.push(new Headers(init?.headers))
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } })
}) as typeof fetch
try {
await options.fetch("https://example.test/v1/chat", {
headers: { Authorization: `Bearer ${OAUTH_DUMMY_KEY}`, "x-keep": "yes" },
})
} finally {
globalThis.fetch = originalFetch
}
expect(captured).toHaveLength(1)
expect(captured[0].get("authorization")).toBe("Bearer access-live")
expect(captured[0].get("x-keep")).toBe("yes")
expect(captured[0].get("user-agent")).toMatch(/^opencode\//)
})
test("loader refreshes expired token with single-flight and persists refreshed oauth", async () => {
const { input, getAuth, setCalls } = makeInput()
let refreshCalls = 0
const apiAuthHeaders: string[] = []
// Must mock fetch before calling loader because startup refresh triggers for expires: 0
const originalFetch = globalThis.fetch
globalThis.fetch = (async (request, init) => {
const url =
typeof request === "string" ? request : request instanceof URL ? request.toString() : String(request.url)
if (url.includes("/oauth/token-request")) {
refreshCalls += 1
const body = new URLSearchParams(String(init?.body ?? ""))
expect(body.get("grant_type")).toBe("refresh_token")
expect(body.get("refresh_token")).toBe("refresh-old")
expect(new Headers(init?.headers).get("authorization")).toMatch(/^Basic /)
await new Promise((resolve) => setTimeout(resolve, 20))
return Response.json({ access_token: "access-new", refresh_token: "refresh-new", expires_in: 3600 })
}
apiAuthHeaders.push(new Headers(init?.headers).get("authorization") || "")
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } })
}) as typeof fetch
try {
const hooks = await SnowflakeCortexAuthPlugin(input)
const options = await hooks.auth!.loader!(
async () =>
({
type: "oauth",
access: "access-expired",
refresh: "refresh-old",
expires: 0,
accountId: "myorg-myaccount",
}) as any,
{} as any,
)
await Promise.all([
options.fetch("https://example.test/v1/chat", { headers: {} }),
options.fetch("https://example.test/v1/chat", { headers: {} }),
])
} finally {
globalThis.fetch = originalFetch
}
expect(refreshCalls).toBe(1)
expect(apiAuthHeaders).toEqual(["Bearer access-new", "Bearer access-new"])
expect(setCalls).toHaveLength(1)
expect((setCalls[0] as any).body).toMatchObject({
type: "oauth",
access: "access-new",
refresh: "refresh-new",
accountId: "myorg-myaccount",
})
})
test("loader retries once after 401 by refreshing token", async () => {
const { input, getAuth, setCalls } = makeInput()
const hooks = await SnowflakeCortexAuthPlugin(input)
const options = await hooks.auth!.loader!(
async () =>
({
type: "oauth",
access: "access-stale",
refresh: "refresh-old",
expires: Date.now() + 60 * 60 * 1000,
accountId: "myorg-myaccount",
}) as any,
{} as any,
)
let apiCalls = 0
const seenAuth: string[] = []
const originalFetch = globalThis.fetch
globalThis.fetch = (async (request, init) => {
const url =
typeof request === "string" ? request : request instanceof URL ? request.toString() : String(request.url)
if (url.includes("/oauth/token-request")) {
return Response.json({ access_token: "access-fresh", refresh_token: "refresh-fresh", expires_in: 3600 })
}
apiCalls += 1
seenAuth.push(new Headers(init?.headers).get("authorization") || "")
if (apiCalls === 1) return new Response("unauthorized", { status: 401 })
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } })
}) as typeof fetch
try {
const response = await options.fetch("https://example.test/v1/chat", { headers: {} })
expect(response.status).toBe(200)
} finally {
globalThis.fetch = originalFetch
}
expect(apiCalls).toBe(2)
expect(seenAuth).toEqual(["Bearer access-stale", "Bearer access-fresh"])
expect(setCalls).toHaveLength(1)
expect((setCalls[0] as any).body).toMatchObject({
type: "oauth",
access: "access-fresh",
refresh: "refresh-fresh",
accountId: "myorg-myaccount",
})
})
test("loader converts max_tokens to max_completion_tokens in request body", async () => {
const { input, getAuth } = makeInput()
const hooks = await SnowflakeCortexAuthPlugin(input)
const options = await hooks.auth!.loader!(getAuth as any, {} as any)
let sentBody: string | undefined
const originalFetch = globalThis.fetch
globalThis.fetch = (async (request, init) => {
sentBody = typeof init?.body === "string" ? init.body : undefined
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } })
}) as typeof fetch
try {
await options.fetch("https://example.test/v1/chat", {
method: "POST",
body: JSON.stringify({ model: "claude-sonnet-4-5", max_tokens: 4096, messages: [] }),
})
} finally {
globalThis.fetch = originalFetch
}
expect(sentBody).toBeDefined()
const parsed = JSON.parse(sentBody!)
expect(parsed.max_completion_tokens).toBe(4096)
expect(parsed.max_tokens).toBeUndefined()
expect(parsed.model).toBe("claude-sonnet-4-5")
})
test("loader maps 400 'conversation complete' to 200 stop", async () => {
const { input, getAuth } = makeInput()
const hooks = await SnowflakeCortexAuthPlugin(input)
const options = await hooks.auth!.loader!(getAuth as any, {} as any)
const originalFetch = globalThis.fetch
globalThis.fetch = (async () => {
return new Response(JSON.stringify({ message: "Conversation complete" }), {
status: 400,
headers: { "content-type": "application/json" },
})
}) as unknown as typeof fetch
try {
const response = await options.fetch("https://example.test/v1/chat", {
method: "POST",
body: JSON.stringify({ model: "test", messages: [] }),
})
expect(response.status).toBe(200)
const body = await response.json()
expect(body.choices[0].finish_reason).toBe("stop")
} finally {
globalThis.fetch = originalFetch
}
})
test("loader fixes empty role in SSE stream", async () => {
const { input, getAuth } = makeInput()
const hooks = await SnowflakeCortexAuthPlugin(input)
const options = await hooks.auth!.loader!(getAuth as any, {} as any)
const originalFetch = globalThis.fetch
const sseChunk = `data: {"choices":[{"delta":{"role":"","content":"hello"}}]}\n\n`
globalThis.fetch = (async () => {
const stream = new ReadableStream({
start(ctrl) {
ctrl.enqueue(new TextEncoder().encode(sseChunk))
ctrl.close()
},
})
return new Response(stream, {
status: 200,
headers: { "content-type": "text/event-stream" },
})
}) as unknown as typeof fetch
try {
const response = await options.fetch("https://example.test/v1/chat", {
method: "POST",
body: JSON.stringify({ model: "test", messages: [], stream: true }),
})
expect(response.status).toBe(200)
const reader = response.body!.getReader()
const { value } = await reader.read()
const text = new TextDecoder().decode(value)
expect(text).not.toContain('"role":""')
expect(text).toContain('"role":"assistant"')
} finally {
globalThis.fetch = originalFetch
}
})
})