Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(models): der Suchschluessel steht nicht mehr in der URL und nicht mehr im Log

purple0e17935dcd9f
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rs
index 0f9af017..1be52600 100644
--- a/src-tauri/src/commands/proxy.rs
+++ b/src-tauri/src/commands/proxy.rs
@@ -52,10 +52,37 @@ fn validate_external_url(raw: &str) -> Result<(), String> {
Ok(())
}
+/// A URL fit to appear in an error message or a log line.
+///
+/// The query string is dropped, and so is any userinfo. A secret in a URL is a
+/// secret in every log that ever quotes the URL, and the log scrubber cannot
+/// see a token that is just another substring of a URL. The CivitAI search used
+/// to put the user's API key there, and this function is the second half of
+/// closing that: the first half is not putting it there at all.
+pub(crate) fn redact_url(raw: &str) -> String {
+ match url::Url::parse(raw) {
+ Ok(mut u) => {
+ u.set_query(None);
+ u.set_fragment(None);
+ let _ = u.set_username("");
+ let _ = u.set_password(None);
+ u.to_string()
+ }
+ // Unparseable: say nothing rather than echo whatever it was.
+ Err(_) => "the requested URL".to_string(),
+ }
+}
+
/// Generic HTTP proxy — fetch any external URL and return body as string.
/// Used for CivitAI API calls, workflow JSON downloads, etc.
+///
+/// `authToken` is the user's CivitAI API key and is sent as a Bearer header,
+/// ONLY to a CivitAI host, exactly like the download path. It is not a generic
+/// "send this to whatever host" parameter: a bearer that follows any URL a
+/// catalogue hands us is a credential leak waiting for a redirect.
+#[allow(non_snake_case)]
#[tauri::command]
-pub async fn fetch_external(url: String) -> Result<String, String> {
+pub async fn fetch_external(url: String, authToken: Option<String>) -> Result<String, String> {
validate_public_url(&url)?;
let client = reqwest::Client::builder()
@@ -65,13 +92,22 @@ pub async fn fetch_external(url: String) -> Result<String, String> {
.build()
.map_err(|e| os_error::english(&e))?;
- let resp = client.get(&url)
+ let mut request = client.get(&url);
+ if let Some(t) = authToken
+ .as_deref()
+ .map(str::trim)
+ .filter(|t| !t.is_empty() && crate::commands::download::is_civitai_host(&url))
+ {
+ request = request.bearer_auth(t);
+ }
+
+ let resp = request
.send()
.await
.map_err(|e| format!("fetch_external: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
- return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));
+ return Err(format!("HTTP {}: {}", resp.status().as_u16(), redact_url(&url)));
}
resp.text().await.map_err(|e| os_error::english(&e))
@@ -96,7 +132,7 @@ pub async fn fetch_external_bytes(url: String) -> Result<Vec<u8>, String> {
.map_err(|e| format!("fetch_external_bytes: {}", os_error::english(&e)))?;
if !resp.status().is_success() {
- return Err(format!("HTTP {}: {}", resp.status().as_u16(), url));
+ return Err(format!("HTTP {}: {}", resp.status().as_u16(), redact_url(&url)));
}
resp.bytes().await.map(|b| b.to_vec()).map_err(|e| os_error::english(&e))
@@ -1205,6 +1241,35 @@ mod tests {
assert!(!is_blocked_proxy_host("2606:4700::1111"));
}
+ /// goonerforporn's key used to ride in the search URL as `&token=`, and
+ /// this function is what quotes that URL back into an error the app then
+ /// logs. The scrubber cannot see a secret that is only a substring of a
+ /// URL, so the query goes.
+ #[test]
+ fn a_url_in_an_error_carries_no_query_and_no_userinfo() {
+ assert_eq!(
+ redact_url("https://civitai.com/api/v1/models?query=x&token=SECRET"),
+ "https://civitai.com/api/v1/models",
+ );
+ assert_eq!(
+ redact_url("https://civitai.com/api/v1/models?token=SECRET#frag"),
+ "https://civitai.com/api/v1/models",
+ );
+ assert!(!redact_url("https://user:[email protected]/x?token=SECRET").contains("pw"));
+ assert!(!redact_url("https://user:[email protected]/x?token=SECRET").contains("SECRET"));
+ }
+
+ /// Negative control: a plain URL is left alone, so the message still says
+ /// which resource failed, and an unparseable one is not echoed at all.
+ #[test]
+ fn a_plain_url_survives_and_a_broken_one_is_not_echoed() {
+ assert_eq!(
+ redact_url("https://huggingface.co/repo/resolve/main/m.gguf"),
+ "https://huggingface.co/repo/resolve/main/m.gguf",
+ );
+ assert_eq!(redact_url("token=SECRET"), "the requested URL");
+ }
+
#[test]
fn validate_public_url_blocks_private_and_loopback() {
for u in [
diff --git a/src/api/__tests__/civitai-api-key.test.ts b/src/api/__tests__/civitai-api-key.test.ts
index df7c2ba5..4b8263fc 100644
--- a/src/api/__tests__/civitai-api-key.test.ts
+++ b/src/api/__tests__/civitai-api-key.test.ts
@@ -18,14 +18,20 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
const backendCall = vi.fn()
+const fetchExternal = vi.fn()
vi.mock('../backend', () => ({
backendCall: (...args: unknown[]) => backendCall(...args),
- fetchExternal: vi.fn(),
+ fetchExternal: (...args: unknown[]) => fetchExternal(...args),
isTauri: () => true,
isMacOS: () => false,
+ secretGet: vi.fn().mockRejectedValue(new Error('no keychain here')),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
}))
-import { isCivitaiUrl, civitaiAuthToken, startModelDownload, resumeDownload } from '../discover'
+import {
+ isCivitaiUrl, civitaiAuthToken, startModelDownload, resumeDownload, searchCivitaiModels,
+} from '../discover'
import { useWorkflowStore } from '../../stores/workflowStore'
const KEY = 'civitai-key-abcdef'
@@ -34,7 +40,9 @@ const HUGGINGFACE = 'https://huggingface.co/TheDrummer/Cydonia/resolve/main/mode
beforeEach(() => {
backendCall.mockReset()
+ fetchExternal.mockReset()
backendCall.mockResolvedValue({ status: 'started', id: 'x' })
+ fetchExternal.mockResolvedValue(JSON.stringify({ items: [] }))
useWorkflowStore.setState({ civitaiApiKey: KEY })
})
@@ -106,3 +114,32 @@ describe('the download carries it', () => {
})
})
})
+
+describe('the search does not put the key in the URL', () => {
+ it('sends the key beside the URL, not inside it', async () => {
+ await searchCivitaiModels('pony', 'Checkpoint', KEY)
+ const [url, token] = fetchExternal.mock.calls[0]
+ // The URL is what an error message and a log line quote, and the scrubber
+ // cannot see a secret that is only another substring of a URL.
+ expect(url).not.toContain(KEY)
+ expect(url).not.toContain('token=')
+ expect(url).toContain('https://civitai.com/api/v1/models?')
+ expect(token).toBe(KEY)
+ })
+
+ // Negative control: no key is still a valid, anonymous search, and the query
+ // the user typed still goes out.
+ it('searches without a key just as it did', async () => {
+ await searchCivitaiModels('pony')
+ const [url, token] = fetchExternal.mock.calls[0]
+ expect(url).toContain('query=pony')
+ expect(url).not.toContain('token')
+ expect(token).toBeNull()
+ })
+
+ // Negative control: the mirror is still honoured (GH #53).
+ it('still asks the mirror when one is chosen', async () => {
+ await searchCivitaiModels('pony', 'LORA', KEY, 'civitai.red')
+ expect(fetchExternal.mock.calls[0][0]).toContain('https://civitai.red/api/v1/models?')
+ })
+})
diff --git a/src/api/backend.ts b/src/api/backend.ts
index aa24ae8c..9d0ded50 100644
--- a/src/api/backend.ts
+++ b/src/api/backend.ts
@@ -753,10 +753,15 @@ export async function oauthWait(port: number, timeoutSecs: number): Promise<stri
}
/** Fetch an external URL as text — works in both Tauri and dev mode */
-export async function fetchExternal(url: string): Promise<string> {
+export async function fetchExternal(url: string, authToken?: string | null): Promise<string> {
if (isTauri()) {
const invoke = await getInvoke();
- return invoke('fetch_external', { url }) as Promise<string>;
+ // Rust sends this as a Bearer header and only to a CivitAI host. The web
+ // path below deliberately sends NO token: the dev proxy takes the URL as a
+ // query parameter, and a credential in a query parameter is a credential in
+ // every log that quotes it. An anonymous CivitAI search still works, it is
+ // only filtered and rate limited.
+ return invoke('fetch_external', { url, authToken: authToken ?? null }) as Promise<string>;
}
const res = await fetch(`/local-api/proxy-download?url=${encodeURIComponent(url)}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
diff --git a/src/api/discover.ts b/src/api/discover.ts
index bbf4c143..bcd35413 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -2451,10 +2451,13 @@ export async function searchCivitaiModels(
// back near-empty for users who expected to find e.g. unfiltered SDXL forks.
nsfw: 'true',
})
- // Adding the user's API key as a bearer token unlocks the full catalog and
- // lifts the per-IP rate limit. Falls back to anon access if no key is set.
- const url = `https://${host}/api/v1/models?${params}${apiKey ? `&token=${encodeURIComponent(apiKey)}` : ''}`
- const text = await fetchExternal(url)
+ // The user's API key unlocks the full catalog and lifts the per-IP rate
+ // limit. It travels as an Authorization header, NOT as `&token=` in the
+ // URL: the URL is what the error text and the log line quote, and the log
+ // scrubber cannot see a secret that is just another substring of a URL.
+ // No key set is still a valid, anonymous search.
+ const url = `https://${host}/api/v1/models?${params}`
+ const text = await fetchExternal(url, apiKey ?? null)
const data = JSON.parse(text)
const items: any[] = data.items ?? []