From 761bd0de8d7df0c6e4aada254793b15542a23265 Mon Sep 17 00:00:00 2001 From: Thomas Kaul <4159106+dtslvr@users.noreply.github.com> Date: Sat, 31 Oct 2026 17:24:37 +0100 Subject: [PATCH] Improve redaction and rejection reason in logging of web_fetch tool --- .../src/services/fetch/fetch.service.spec.ts | 105 +++++++++++++++++- apps/api/src/services/fetch/fetch.service.ts | 53 ++++++--- 2 files changed, 137 insertions(+), 21 deletions(-) diff --git a/apps/api/src/services/fetch/fetch.service.spec.ts b/apps/api/src/services/fetch/fetch.service.spec.ts index b5ccd822a0..e53fe4587b 100644 --- a/apps/api/src/services/fetch/fetch.service.spec.ts +++ b/apps/api/src/services/fetch/fetch.service.spec.ts @@ -2,6 +2,7 @@ import { PropertyService } from '@ghostfolio/api/services/property/property.serv import { PROPERTY_API_KEY_OPENROUTER, PROPERTY_OPENROUTER_ENGINE_WEB_FETCH, + PROPERTY_OPENROUTER_MODEL, PROPERTY_OPENROUTER_MODEL_WEB_FETCH, PROPERTY_WEB_FETCH_ROUTES } from '@ghostfolio/common/config'; @@ -292,12 +293,49 @@ describe('FetchService', () => { expect(warn).not.toHaveBeenCalled(); }); + it.each(['apikey', 'APIKEY', 'api_token', 'key', 'token'])( + 'should redact the query parameter %s in the log of a successful web fetch', + async (name) => { + mockGenerateText({ text: BODY }); + + await fetchService.fetch(`${URL_WITH_ROUTE}?${name}=secret&a=b`); + + expect(log.mock.calls[0][0]).toContain(`${name}=*******&a=b`); + expect(log.mock.calls[0][0]).not.toContain('secret'); + } + ); + it.each([ [ 'a failure message', { text: FAILURE_MESSAGE }, 'reason=failure_message error="HTTP 405: Method Not Allowed"' ], + [ + 'a failure message with an empty error', + { text: '{"url":"u","status":"failed","error":""}' }, + 'reason=failure_message error="(empty)"' + ], + [ + 'a failure message of a source before a text without JSON', + { + sources: [ + { providerMetadata: { openrouter: { content: FAILURE_MESSAGE } } } + ], + text: 'Sorry.' + }, + 'reason=failure_message error="HTTP 405: Method Not Allowed"' + ], + [ + 'a failure message after a source without JSON', + { + sources: [ + { providerMetadata: { openrouter: { content: 'Sorry.' } } } + ], + text: FAILURE_MESSAGE + }, + 'reason=failure_message error="HTTP 405: Method Not Allowed"' + ], ['a text without JSON', { text: 'Sorry.' }, 'reason=invalid_body'], ['an empty text', { text: '' }, 'reason=empty_body'], [ @@ -320,9 +358,34 @@ describe('FetchService', () => { expect(log).not.toHaveBeenCalled(); }); - it('should redact the API keys in the error of a failure message', async () => { + it.each([ + ['https://www.example.com?unknown=secret', 'No access to [url]'], + [ + 'https://www.example.com?u=https%3A%2F%2Fx%3Fapikey%3Dsecret', + 'No access to [url]' + ], + ['HTTPS://www.example.com?apikey=secret', 'No access to [url]'] + ])( + 'should replace the URL %s in the error of a failure message', + async (url, expected) => { + mockGenerateText({ + text: JSON.stringify({ + error: `No access to ${url}`, + status: 'failed', + url: 'https://www.example.com' + }) + }); + + await fetchService.fetch(URL_WITH_ROUTE); + + expect(warn.mock.calls[0][0]).toContain(`error="${expected}"`); + expect(warn.mock.calls[0][0]).not.toContain('secret'); + } + ); + + it('should redact the API keys outside of a URL in the error of a failure message', async () => { mockGenerateText({ - text: '{"url":"https://www.example.com","status":"failed","error":"No access to https://www.example.com?apikey=secret"}' + text: '{"url":"https://www.example.com","status":"failed","error":"Invalid apikey=secret"}' }); await fetchService.fetch(URL_WITH_ROUTE); @@ -342,15 +405,49 @@ describe('FetchService', () => { ); }); - it('should log a missing configuration without the API key', async () => { + it('should log the name of a missing model', async () => { delete properties[PROPERTY_OPENROUTER_MODEL_WEB_FETCH]; await fetchService.fetch(URL_WITH_ROUTE); expect(warn).toHaveBeenCalledTimes(1); - expect(warn.mock.calls[0][0]).toContain('reason=missing_configuration'); + expect(warn.mock.calls[0][0]).toContain( + `reason=missing_configuration missing=${PROPERTY_OPENROUTER_MODEL})` + ); expect(warn.mock.calls[0][0]).not.toContain('api-key'); }); + + it('should log the name of a missing API key', async () => { + delete properties[PROPERTY_API_KEY_OPENROUTER]; + + await fetchService.fetch(URL_WITH_ROUTE); + + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0][0]).toContain( + `reason=missing_configuration missing=${PROPERTY_API_KEY_OPENROUTER})` + ); + }); + + it('should log the names of a missing API key and model', async () => { + delete properties[PROPERTY_API_KEY_OPENROUTER]; + delete properties[PROPERTY_OPENROUTER_MODEL_WEB_FETCH]; + + await fetchService.fetch(URL_WITH_ROUTE); + + expect(warn.mock.calls[0][0]).toContain( + `missing=${PROPERTY_API_KEY_OPENROUTER},${PROPERTY_OPENROUTER_MODEL})` + ); + }); + + it('should log a missing configuration only one time', async () => { + delete properties[PROPERTY_API_KEY_OPENROUTER]; + + await fetchService.fetch(URL_WITH_ROUTE); + await fetchService.fetch(URL_WITH_ROUTE); + + expect(warn).toHaveBeenCalledTimes(1); + expect(directFetch).toHaveBeenCalledTimes(2); + }); }); describe('validation of the routes', () => { diff --git a/apps/api/src/services/fetch/fetch.service.ts b/apps/api/src/services/fetch/fetch.service.ts index 1f17ddf71b..9e1791cf3c 100644 --- a/apps/api/src/services/fetch/fetch.service.ts +++ b/apps/api/src/services/fetch/fetch.service.ts @@ -1,4 +1,3 @@ -import { redactPaths } from '@ghostfolio/api/helper/object.helper'; import { getWebFetchBody, getWebFetchError @@ -29,9 +28,15 @@ export class FetchService implements OnModuleInit { private readonly logger = new Logger(FetchService.name); private static readonly BODY_PREVIEW_LENGTH = 500; - private static readonly REDACTED_QUERY_PARAM_NAMES = ['apikey', 'api_token']; + private static readonly REDACTED_QUERY_PARAM_NAMES = [ + 'apikey', + 'api_token', + 'key', + 'token' + ]; private static readonly WEB_FETCH_TIMEOUT = ms('30 seconds'); + private hasLoggedMissingConfiguration = false; private proxyRoutes: ProxyRoute[] = []; private webFetchRoutes: WebFetchRoute[] = []; @@ -120,11 +125,21 @@ export class FetchService implements OnModuleInit { const model = openRouterModelWebFetch || openRouterModel; if (!model || !openRouterApiKey) { - this.logger.warn( - `Web fetch tool is not available for ${this.redactUrl(url)} (${this.getWebFetchLogDetails( - { engine, reason: 'missing_configuration' } - )})` - ); + if (!this.hasLoggedMissingConfiguration) { + const missing = [ + ...(openRouterApiKey ? [] : [PROPERTY_API_KEY_OPENROUTER]), + ...(model ? [] : [PROPERTY_OPENROUTER_MODEL]) + ].join(','); + + this.logger.warn( + `Web fetch tool is not available (${this.getWebFetchLogDetails({ + engine, + reason: `missing_configuration missing=${missing}` + })})` + ); + + this.hasLoggedMissingConfiguration = true; + } return undefined; } @@ -186,7 +201,13 @@ export class FetchService implements OnModuleInit { const body = getWebFetchBody({ candidate, isJson }); if (!body) { - rejectedBody = candidate.trim() || rejectedBody; + // A failure message tells more than the text of a later candidate + if ( + !rejectedBody || + getWebFetchError({ candidate: rejectedBody }) === undefined + ) { + rejectedBody = candidate.trim() || rejectedBody; + } continue; } @@ -329,8 +350,9 @@ export class FetchService implements OnModuleInit { const error = getWebFetchError({ candidate: rejectedBody }); - return error - ? `failure_message error="${this.getBodyPreview(error)}"` + // The model can repeat the URL of the prompt, which can contain a secret + return error !== undefined + ? `failure_message error="${this.getBodyPreview(error.replace(/https?:\/\/\S+/gi, '[url]'))}"` : 'invalid_body'; } @@ -426,13 +448,10 @@ export class FetchService implements OnModuleInit { try { const url = new URL(rawUrl); - const redacted = redactPaths({ - object: Object.fromEntries(url.searchParams), - paths: FetchService.REDACTED_QUERY_PARAM_NAMES - }); - - for (const [key, value] of Object.entries(redacted)) { - if (value === null) { + for (const key of [...url.searchParams.keys()]) { + if ( + FetchService.REDACTED_QUERY_PARAM_NAMES.includes(key.toLowerCase()) + ) { url.searchParams.set(key, '*******'); } }