Skip to content

Commit 16054f5

Browse files
authored
More fixes to proxy (#1237)
<!-- ELLIPSIS_HIDDEN --> > [!IMPORTANT] > Improved proxy handling in Rust and TypeScript by refining error messages, URL construction, and request routing logic. > > - **Rust Proxy Handling**: > - Improved error message in `to_base64_with_inferred_mime_type()` in `mod.rs` to include `media_url.url`. > - Refactored URL construction in `fetch_with_proxy()` in `mod.rs` to use `new_proxy_url` variable. > - **TypeScript Proxy Middleware**: > - Added logic in `extension.ts` to handle image GET requests by setting path to empty string. > - Removed trailing slashes from paths in `extension.ts`. > - Ensured `baml-original-url` header is used to route requests in `extension.ts`. > - **Miscellaneous**: > - Disabled ESLint rule `@typescript-eslint/no-misused-promises` in `extension.ts`. > > <sup>This description was created by </sup>[<img alt="Ellipsis" src="https://img.shields.io/badge/Ellipsis-blue?color=175173">](https://www.ellipsis.dev?ref=BoundaryML%2Fbaml&utm_source=github&utm_medium=referral)<sup> for e38f259. It will automatically update as commits are pushed.</sup> <!-- ELLIPSIS_HIDDEN -->
1 parent 859c699 commit 16054f5

File tree

2 files changed

+41
-41
lines changed
  • engine/baml-runtime/src/internal/llm_client/traits
  • typescript/vscode-ext/packages/vscode/src

2 files changed

+41
-41
lines changed

engine/baml-runtime/src/internal/llm_client/traits/mod.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -635,9 +635,10 @@ async fn to_base64_with_inferred_mime_type(
635635
Ok((base64, mime_type))
636636
} else {
637637
Err(anyhow::anyhow!(
638-
"Failed to fetch media: {}, {}",
638+
"Failed to fetch media: {} {}, {}",
639639
response.status(),
640-
response.text().await.unwrap_or_default()
640+
media_url.url,
641+
response.text().await.unwrap_or_default(),
641642
))
642643
}
643644
}
@@ -664,15 +665,14 @@ async fn fetch_with_proxy(
664665
let client = reqwest::Client::new();
665666

666667
let request = if let Some(proxy) = proxy_url {
667-
client
668-
.get(format!(
669-
"{}{}",
670-
proxy,
671-
url.parse::<url::Url>()
672-
.map_err(|e| anyhow::anyhow!("Failed to parse URL: {}", e))?
673-
.path()
674-
))
675-
.header("baml-original-url", url)
668+
let new_proxy_url = format!(
669+
"{}{}",
670+
proxy,
671+
url.parse::<url::Url>()
672+
.map_err(|e| anyhow::anyhow!("Failed to parse URL: {}", e))?
673+
.path()
674+
);
675+
client.get(new_proxy_url).header("baml-original-url", url)
676676
} else {
677677
client.get(url)
678678
};

typescript/vscode-ext/packages/vscode/src/extension.ts

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/* eslint-disable @typescript-eslint/no-misused-promises */
12
import * as vscode from 'vscode'
23
import axios from 'axios'
34
import glooLens from './LanguageToBamlCodeLensProvider'
@@ -193,11 +194,21 @@ export function activate(context: vscode.ExtensionContext) {
193194
createProxyMiddleware({
194195
changeOrigin: true,
195196
pathRewrite: (path, req) => {
196-
// Ensure the URL does not end with a slash
197+
console.log('reqmethod', req.method)
198+
199+
// Remove the path in the case of images. Since we request things differently for image GET requests, where we add the url to localhost:4500/actual-url.png
200+
// to prevent caching issues with Rust reqwest.
201+
// But for normal completion POST requests, we always call localhost:4500.
202+
// The original url is always in baml-original-url header.
203+
204+
// Check for file extensions and set path to empty string.
205+
if (/\.[a-zA-Z0-9]+$/.test(path) && req.method === 'GET') {
206+
return ''
207+
}
208+
// Remove trailing slash
197209
if (path.endsWith('/')) {
198210
return path.slice(0, -1)
199211
}
200-
console.log('pathRewrite', path, req)
201212
return path
202213
},
203214
router: (req) => {
@@ -209,11 +220,14 @@ export function activate(context: vscode.ExtensionContext) {
209220
delete req.headers['origin']
210221

211222
// Ensure the URL does not end with a slash
223+
console.log('originalUrl1', originalUrl)
212224
if (originalUrl.endsWith('/')) {
213225
originalUrl = originalUrl.slice(0, -1)
214226
}
215227
console.log('returning original url', originalUrl)
216-
return new URL(originalUrl).origin
228+
// return new URL(originalUrl).toString()
229+
230+
return originalUrl
217231
} else {
218232
console.log('baml-original-url header is missing or invalid')
219233
throw new Error('baml-original-url header is missing or invalid')
@@ -222,33 +236,19 @@ export function activate(context: vscode.ExtensionContext) {
222236
logger: console,
223237
on: {
224238
proxyReq: (proxyReq, req, res) => {
225-
console.log('proxying request')
226-
227-
try {
228-
const bamlOriginalUrl = req.headers['baml-original-url']
229-
if (bamlOriginalUrl === undefined) {
230-
return
231-
}
232-
const targetUrl = new URL(bamlOriginalUrl)
233-
// proxyReq.path = targetUrl.pathname
234-
// proxyReq.p
235-
// It is very important that we ONLY resolve against API_KEY_INJECTION_ALLOWED
236-
// by using the URL origin! (i.e. NOT using str.startsWith - the latter can still
237-
// leak API keys to malicious subdomains e.g. https://api.openai.com.evil.com)
238-
// const headers = API_KEY_INJECTION_ALLOWED[proxyOrigin]
239-
// if (headers === undefined) {
240-
// return
241-
// }
242-
// for (const [header, value] of Object.entries(headers)) {
243-
// proxyReq.setHeader(header, value)
244-
// }
245-
// proxyReq.removeHeader('origin')
246-
// proxyReq.setHeader('Origin', targetUrl.origin)
247-
console.info('Proxying an LLM request (to bypass CORS)', { proxyReq, req, res })
248-
} catch (err) {
249-
// This is not console.warn because it's not important
250-
console.log('baml-original-url is not parsable', err)
251-
}
239+
// const bamlOriginalUrl = req.headers['baml-original-url']
240+
// if (typeof bamlOriginalUrl === 'string') {
241+
// const targetUrl = new URL(bamlOriginalUrl)
242+
// // Copy all original headers except those we want to modify/remove
243+
// Object.entries(req.headers).forEach(([key, value]) => {
244+
// if (key !== 'host' && key !== 'origin' && key !== 'baml-original-url') {
245+
// proxyReq.setHeader(key, value)
246+
// }
247+
// })
248+
// // Set the correct origin and host headers
249+
// proxyReq.setHeader('origin', targetUrl.origin)
250+
// proxyReq.setHeader('host', targetUrl.host)
251+
// }
252252
},
253253
proxyRes: (proxyRes, req, res) => {
254254
proxyRes.headers['Access-Control-Allow-Origin'] = '*'

0 commit comments

Comments
 (0)