From fcec9918473eeeeb09d23bf89c65e08f2f452d28 Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Tue, 17 Nov 2026 02:15:11 +0000 Subject: [PATCH] fix(amazonq): check the URLs that chat opens for the subscription upgrade and source links The subscription upgrade now opens only an https URL on signin.aws.amazon.com, in normalized form, and the log records only the subscription status. Chat responses keep only http and https source links, and the chat client sends only those source links to the IDE. Adds tests. --- chat-client/src/client/messager.ts | 9 ++ chat-client/src/client/mynahUi.test.ts | 49 ++++++++ chat-client/src/client/mynahUi.ts | 8 +- .../agenticChat/agenticChatController.test.ts | 109 ++++++++++++++++++ .../agenticChat/agenticChatController.ts | 32 +++-- .../agenticChatEventParser.test.ts | 70 +++++++++++ .../agenticChat/agenticChatEventParser.ts | 15 ++- .../chat/chatEventParser.test.ts | 43 +++++++ .../language-server/chat/chatEventParser.ts | 15 ++- .../language-server/paidTier/paidTier.test.ts | 44 +++++++ .../src/language-server/paidTier/paidTier.ts | 29 +++++ .../src/shared/utils.test.ts | 48 ++++++++ .../aws-lsp-codewhisperer/src/shared/utils.ts | 17 +++ 13 files changed, 457 insertions(+), 31 deletions(-) create mode 100644 server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.test.ts diff --git a/chat-client/src/client/messager.ts b/chat-client/src/client/messager.ts index 27a0c60782..a5ec5e9484 100644 --- a/chat-client/src/client/messager.ts +++ b/chat-client/src/client/messager.ts @@ -224,6 +224,15 @@ export class Messager { onSourceLinkClick = (params: SourceLinkClickParams): void => { this.chatApi.sourceLinkClick(params) + this.onSourceLinkClickTelemetry(params) + } + + /** + * Records the telemetry of every source link click: the clicks that chat sends to the IDE (onSourceLinkClick) + * and the clicks that it does not send because the link is not http or https. The event carries the link, and + * the server records it as the interaction target, so the scheme tells them apart. + */ + onSourceLinkClickTelemetry = (params: SourceLinkClickParams): void => { this.chatApi.telemetry({ ...params, name: SOURCE_LINK_CLICK_TELEMETRY_EVENT }) } diff --git a/chat-client/src/client/mynahUi.test.ts b/chat-client/src/client/mynahUi.test.ts index 2cf211e021..a9ba6a939e 100644 --- a/chat-client/src/client/mynahUi.test.ts +++ b/chat-client/src/client/mynahUi.test.ts @@ -892,6 +892,55 @@ describe('MynahUI', () => { }) }) + describe('source link clicks', () => { + const props = () => (mynahUi as any).props + const sourceLinkTelemetry = () => + (outboundChatApi.telemetry as sinon.SinonStub).getCalls().filter(c => c.args[0].name === 'sourceLinkClick') + + it('sends an https or http source link to the IDE and records telemetry', () => { + props().onSourceLinkClick('tab-1', 'answer-1', 'https://example.com/doc', undefined, 'event-1') + props().onSourceLinkClick('tab-1', 'answer-1', 'http://example.com/page', undefined, 'event-2') + + const sourceLinkClick = outboundChatApi.sourceLinkClick as sinon.SinonStub + sinon.assert.calledTwice(sourceLinkClick) + deepStrictEqual(sourceLinkClick.firstCall.args[0], { + tabId: 'tab-1', + messageId: 'answer-1', + link: 'https://example.com/doc', + eventId: 'event-1', + }) + strictEqual(sourceLinkClick.secondCall.args[0].link, 'http://example.com/page') + strictEqual(sourceLinkTelemetry().length, 2) + sinon.assert.notCalled(notifySpy) + }) + + it('does not send a source link with another scheme or a local path, and tells the user', () => { + const links = [ + 'javascript:x', + 'file:///etc/hosts', + 'vscode://settings/x', + 'command:workbench.action.reloadWindow', + 'src/foo.ts', + '\\\\host\\share\\x', + '', + ] + for (const link of links) { + props().onSourceLinkClick('tab-1', 'answer-1', link, undefined, 'event-1') + } + + sinon.assert.notCalled(outboundChatApi.sourceLinkClick as sinon.SinonStub) + sinon.assert.notCalled(outboundChatApi.fileClick as sinon.SinonStub) + sinon.assert.notCalled(outboundChatApi.linkClick as sinon.SinonStub) + strictEqual(notifySpy.callCount, links.length) + strictEqual(notifySpy.firstCall.args[0].type, NotificationType.WARNING) + strictEqual(notifySpy.firstCall.args[0].title, 'Link not opened') + deepStrictEqual( + sourceLinkTelemetry().map(c => c.args[0].link), + links + ) + }) + }) + describe('onMessageDismiss', () => { it('acknowledges the deprecation card and removes it from every open and future new chat', () => { const updateTabDefaultsSpy = sinon.spy(mynahUi, 'updateTabDefaults') diff --git a/chat-client/src/client/mynahUi.ts b/chat-client/src/client/mynahUi.ts index 2ab3160c6c..73f24f8f87 100644 --- a/chat-client/src/client/mynahUi.ts +++ b/chat-client/src/client/mynahUi.ts @@ -550,7 +550,13 @@ export const createMynahUi = ( link, eventId, } - messager.onSourceLinkClick(payload) + // A source link comes from the service, so only an http or https URL goes to the IDE. + if (classifyChatLink(link).kind === 'link') { + messager.onSourceLinkClick(payload) + return + } + messager.onSourceLinkClickTelemetry(payload) + notifyUnsupportedLink() }, onInfoLinkClick: (tabId, link, mouseEvent, eventId) => { mouseEvent?.preventDefault() diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts index 192f41c013..d67e70d7fe 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.test.ts @@ -482,6 +482,115 @@ describe('AgenticChatController', () => { sinon.assert.calledOnce(getSubscriptionStatusStub) }) + + it('logs the subscription status without the subscription URL', async () => { + getSubscriptionStatusStub.resolves({ + status: 'none', + encodedVerificationUrl: 'https://signin.aws.amazon.com/oauth?activationToken=TOKEN-1234', + }) + + chatController.onTabAdd({ tabId: mockTabId }) + await new Promise(resolve => setTimeout(resolve, 0)) + + sinon.assert.calledWith( + testFeatures.logging.log as sinon.SinonStub, + 'setPaidTierMode: getSubscriptionStatus: none' + ) + sinon.assert.neverCalledWithMatch(testFeatures.logging.log as sinon.SinonStub, sinon.match('TOKEN-1234')) + }) + }) + + describe('onManageSubscription', () => { + // The form of the URL that the service returns. The activation token must not reach the log. + const activationToken = 'TOKEN-1234' + const signInUrl = `https://signin.aws.amazon.com/oauth?redirect_uri=https://us-east-1.console.aws.amazon.com/amazonq/developer/home?hashArgs=%23%2Fsubscriptions%2FbuilderId%3FactivationToken%3D${activationToken}&isauthcode=true®ion=us-east-1&response_type=code` + let getCodewhispererServiceStub: sinon.SinonStub + let getSubscriptionStatusStub: sinon.SinonStub + let waitUntilSubscriptionActiveStub: sinon.SinonStub + + const loggedText = () => + (['log', 'info', 'warn', 'error', 'debug'] as const) + .flatMap(level => (testFeatures.logging[level] as sinon.SinonStub).args) + .map(args => args.join(' ')) + .join('\n') + + // Runs the "Upgrade Q" flow of a free-tier user whose subscription status response has this URL + const manageSubscription = async (encodedVerificationUrl: string | undefined) => { + getSubscriptionStatusStub.resolves({ status: 'none', encodedVerificationUrl }) + await chatController.onManageSubscription(mockTabId) + // onManageSubscription handles the status response asynchronously + await new Promise(resolve => setTimeout(resolve, 0)) + } + + const upgradePendingUpdate = sinon.match({ paidTierMode: 'upgrade-pending' }) + + const assertRequestFailedMessage = () => { + sinon.assert.notCalled(testFeatures.lsp.window.showDocument as sinon.SinonStub) + sinon.assert.notCalled(waitUntilSubscriptionActiveStub) + sinon.assert.neverCalledWithMatch(testFeatures.chat.sendChatUpdate as sinon.SinonStub, upgradePendingUpdate) + sinon.assert.calledOnceWithExactly(testFeatures.lsp.window.showMessage as sinon.SinonStub, { + message: 'Subscription request failed.', + type: MessageType.Error, + }) + } + + beforeEach(() => { + getSubscriptionStatusStub = sinon.stub() + waitUntilSubscriptionActiveStub = sinon.stub().resolves(true) + getCodewhispererServiceStub = sinon + .stub(AmazonQTokenServiceManager.prototype, 'getCodewhispererService') + .returns({ + getSubscriptionStatus: getSubscriptionStatusStub, + waitUntilSubscriptionActive: waitUntilSubscriptionActiveStub, + } as any) + ;(testFeatures.lsp.window.showDocument as sinon.SinonStub).resolves({ success: true }) + testFeatures.lsp.window.showMessage = sinon.stub().resolves() + }) + + afterEach(() => { + getCodewhispererServiceStub.restore() + }) + + it('opens an https URL on the AWS sign-in host in the external browser without logging it', async () => { + await manageSubscription(signInUrl) + + sinon.assert.calledOnceWithExactly(testFeatures.lsp.window.showDocument as sinon.SinonStub, { + external: true, + uri: signInUrl, + }) + sinon.assert.calledWithMatch(testFeatures.chat.sendChatUpdate as sinon.SinonStub, upgradePendingUpdate) + sinon.assert.calledOnce(waitUntilSubscriptionActiveStub) + assert.ok(!loggedText().includes(activationToken)) + }) + + it('opens the URL in its normalized form', async () => { + await manageSubscription('HTTPS://SIGNIN.AWS.AMAZON.COM:443/oauth?state=1') + + sinon.assert.calledOnceWithExactly(testFeatures.lsp.window.showDocument as sinon.SinonStub, { + external: true, + uri: 'https://signin.aws.amazon.com/oauth?state=1', + }) + }) + + for (const uri of [ + `vscode://publisher.extension/path?activationToken=${activationToken}`, + `file:///tmp/file.txt?activationToken=${activationToken}`, + `http://signin.aws.amazon.com/oauth?activationToken=${activationToken}`, + `https://example.com/oauth?activationToken=${activationToken}`, + ]) { + it(`does not open ${uri.split('?')[0]} and shows an error without logging the URL`, async () => { + await manageSubscription(uri) + + assertRequestFailedMessage() + assert.ok(!loggedText().includes(activationToken)) + }) + } + + it('shows an error when the response has no URL', async () => { + await manageSubscription(undefined) + + assertRequestFailedMessage() + }) }) it('onTabRemove unsets tab id if current tab is removed and emits metrics', () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts index a23f31460b..466bc48082 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatController.ts @@ -251,6 +251,7 @@ import { onPaidTierLearnMore, paidTierManageSubscription, PaidTierMode, + parseSubscriptionUpgradeUrl, qProName, } from '../paidTier/paidTier' import { @@ -4852,9 +4853,8 @@ export class AgenticChatController implements ChatHandlers { ?.getCodewhispererService() .getSubscriptionStatus(true) .then(o => { - this.#log( - `setPaidTierMode: getSubscriptionStatus: ${o.status} ${o.encodedVerificationUrl}` - ) + // Log only the status: the subscription URL contains an activation token + this.#log(`setPaidTierMode: getSubscriptionStatus: ${o.status}`) this.setPaidTierMode(tabId, o.status !== 'none' ? 'paidtier' : 'freetier') }) .catch(err => { @@ -4922,7 +4922,8 @@ export class AgenticChatController implements ChatHandlers { client ?.getSubscriptionStatus() .then(o => { - this.#log(`onManageSubscription: getSubscriptionStatus: ${o.status} ${o.encodedVerificationUrl}`) + // Log only the status: the subscription URL contains an activation token + this.#log(`onManageSubscription: getSubscriptionStatus: ${o.status}`) if (o.status !== 'none') { // Paid-tier user: navigate them to the "Manage Subscriptions" AWS console page. @@ -4937,10 +4938,14 @@ export class AgenticChatController implements ChatHandlers { }) } else { // Free-tier user: navigate them to "Upgrade Q" flow in AWS console. - const uri = o.encodedVerificationUrl + // The client opens the URL in the external browser, so it must be on the AWS sign-in host. + const uri = parseSubscriptionUpgradeUrl(o.encodedVerificationUrl) if (!uri) { - this.#log('onManageSubscription: missing encodedVerificationUrl in server response') + const reason = o.encodedVerificationUrl + ? 'encodedVerificationUrl in server response is not an https URL on the AWS sign-in host' + : 'missing encodedVerificationUrl in server response' + this.#log(`onManageSubscription: ${reason}`) this.#features.lsp.window .showMessage({ message: 'Subscription request failed.', @@ -4949,21 +4954,10 @@ export class AgenticChatController implements ChatHandlers { .catch(e => { this.#log(`onManageSubscription: showMessage failed: ${(e as Error).message}`) }) - return 'missing encodedVerificationUrl in server response' + return reason } - try { - URI.parse(uri) - } catch (e) { - this.#log( - `onManageSubscription: invalid encodedVerificationUrl: '${uri}': ${(e as Error).message}` - ) - return 'invalid encodedVerificationUrl' - } - - this.#log( - `onManageSubscription: createSubscriptionToken status: ${o.status} encodedVerificationUrl: '${uri}'` - ) + this.#log(`onManageSubscription: createSubscriptionToken status: ${o.status}`) // Set UI to "progress" mode. this.setPaidTierMode(tabId, 'upgrade-pending') diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.test.ts index 0fb7640106..b41c1357fd 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.test.ts @@ -394,4 +394,74 @@ describe('AgenticChatEventParser', () => { assert.strictEqual(result.success, true) assert.strictEqual(result.data?.toolUses['tool-1'].stop, false) }) + + describe('source links', () => { + const webLink = (url: string | undefined, title = 'title') => ({ title, snippet: 'snippet', url }) + + it('keeps only http and https source links, in order and unchanged', () => { + const chatEventParser = new AgenticChatEventParser(mockMessageId, new Metric(), logging) + + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { + supplementaryWebLinks: [ + webLink('https://docs.example.com/guide?a=1#part', 'https link'), + webLink('javascript:x'), + webLink('HTTP://Example.com/Page', 'http link'), + webLink('data:text/html,hello'), + webLink('file:///etc/hosts'), + webLink('vscode://settings/x'), + webLink('command:workbench.action.reloadWindow'), + webLink('mailto:someone@example.com'), + webLink('//example.com/no-scheme'), + webLink('docs/relative.md'), + webLink('https://'), + webLink(''), + webLink(undefined), + ], + }, + }) + + const result = chatEventParser.getResult() + assert.deepStrictEqual(result.data?.chatResult.relatedContent, { + content: [ + { title: 'https link', url: 'https://docs.example.com/guide?a=1#part', body: 'snippet' }, + { title: 'http link', url: 'HTTP://Example.com/Page', body: 'snippet' }, + ], + }) + assert.strictEqual(chatEventParser.totalEvents.supplementaryWebLinksEvent, 1) + }) + + it('adds no related content when an event has no http or https link', () => { + const chatEventParser = new AgenticChatEventParser(mockMessageId, new Metric(), logging) + + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { + supplementaryWebLinks: [webLink('javascript:x'), webLink('file:///etc/hosts')], + }, + }) + + assert.strictEqual(chatEventParser.getResult().data?.chatResult.relatedContent, undefined) + assert.strictEqual(chatEventParser.totalEvents.supplementaryWebLinksEvent, 1) + }) + + it('keeps the links of earlier events when a later event has no web link', () => { + const chatEventParser = new AgenticChatEventParser(mockMessageId, new Metric(), logging) + + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { supplementaryWebLinks: [webLink('https://a.example.com/')] }, + }) + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { supplementaryWebLinks: [webLink('vbscript:x')] }, + }) + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { supplementaryWebLinks: [webLink('http://b.example.com/x')] }, + }) + + assert.deepStrictEqual( + chatEventParser.getResult().data?.chatResult.relatedContent?.content.map(link => link.url), + ['https://a.example.com/', 'http://b.example.com/x'] + ) + assert.strictEqual(chatEventParser.totalEvents.supplementaryWebLinksEvent, 3) + }) + }) }) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.ts index 12da3654e7..bd7c97ccab 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/agenticChatEventParser.ts @@ -16,6 +16,7 @@ import { AddMessageEvent } from '../../shared/telemetry/types' import { Metric } from '../../shared/telemetry/metric' import { Features } from '@aws/language-server-runtimes/server-interface/server' import { loggingUtils } from '@aws/lsp-core' +import { isWebUrl } from '../../shared/utils' export type ChatResultWithMetadata = { chatResult: ChatResult @@ -180,13 +181,15 @@ export class AgenticChatEventParser implements ChatResult { supplementaryWebLinksEvent.supplementaryWebLinks.length > 0 ) { this.#totalEvents.supplementaryWebLinksEvent += 1 - const sourceLinks = supplementaryWebLinksEvent.supplementaryWebLinks.map( - AgenticChatEventParser.mapRelatedData - ) + const sourceLinks = supplementaryWebLinksEvent.supplementaryWebLinks + .filter(link => isWebUrl(link.url)) + .map(AgenticChatEventParser.mapRelatedData) - this.relatedContent = { - ...this.relatedContent, - content: [...(this.relatedContent?.content ?? []), ...sourceLinks], + if (sourceLinks.length > 0) { + this.relatedContent = { + ...this.relatedContent, + content: [...(this.relatedContent?.content ?? []), ...sourceLinks], + } } } else if (codeReferenceEvent?.references && codeReferenceEvent.references.length > 0) { this.#totalEvents.codeReferenceEvent += 1 diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.test.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.test.ts index 4a9b2c0e97..387db953c1 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.test.ts @@ -270,4 +270,47 @@ describe('ChatEventParser', () => { assert.deepStrictEqual(chatEventParser.getResult(), { success: true, data: expectedData }) }) + + describe('source links', () => { + const webLink = (url: string | undefined, title = 'title') => ({ title, snippet: 'snippet', url }) + + it('keeps only http and https source links, in order and unchanged', () => { + const chatEventParser = new ChatEventParser(mockMessageId, new Metric()) + + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { + supplementaryWebLinks: [ + webLink('javascript:x'), + webLink('https://docs.example.com/guide', 'https link'), + webLink('file:///etc/hosts'), + webLink('http://example.com/page', 'http link'), + webLink('vscode://settings/x'), + webLink('https://'), + webLink(undefined), + ], + }, + }) + + assert.deepStrictEqual(chatEventParser.getResult().data?.chatResult.relatedContent, { + content: [ + { title: 'https link', url: 'https://docs.example.com/guide', body: 'snippet' }, + { title: 'http link', url: 'http://example.com/page', body: 'snippet' }, + ], + }) + assert.strictEqual(chatEventParser.totalEvents.supplementaryWebLinksEvent, 1) + }) + + it('adds no related content when an event has no http or https link', () => { + const chatEventParser = new ChatEventParser(mockMessageId, new Metric()) + + chatEventParser.processPartialEvent({ + supplementaryWebLinksEvent: { + supplementaryWebLinks: [webLink('data:text/html,hello'), webLink('command:x')], + }, + }) + + assert.strictEqual(chatEventParser.getResult().data?.chatResult.relatedContent, undefined) + assert.strictEqual(chatEventParser.totalEvents.supplementaryWebLinksEvent, 1) + }) + }) }) diff --git a/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.ts b/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.ts index c6837427ef..119f44a749 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/chat/chatEventParser.ts @@ -13,6 +13,7 @@ import { import { Result } from '../types' import { AddMessageEvent } from '../../shared/telemetry/types' import { Metric } from '../../shared/telemetry/metric' +import { isWebUrl } from '../../shared/utils' export type ChatResponseStream = ChatResponseStreamCodeWhispererStreaming | ChatResponseStreamQDeveloperStreaming export type ChatResultWithMetadata = { @@ -126,11 +127,15 @@ export class ChatEventParser implements ChatResult { supplementaryWebLinksEvent.supplementaryWebLinks.length > 0 ) { this.#totalEvents.supplementaryWebLinksEvent += 1 - const sourceLinks = supplementaryWebLinksEvent.supplementaryWebLinks.map(ChatEventParser.mapRelatedData) - - this.relatedContent = { - ...this.relatedContent, - content: [...(this.relatedContent?.content ?? []), ...sourceLinks], + const sourceLinks = supplementaryWebLinksEvent.supplementaryWebLinks + .filter(link => isWebUrl(link.url)) + .map(ChatEventParser.mapRelatedData) + + if (sourceLinks.length > 0) { + this.relatedContent = { + ...this.relatedContent, + content: [...(this.relatedContent?.content ?? []), ...sourceLinks], + } } } else if (codeReferenceEvent?.references && codeReferenceEvent.references.length > 0) { this.#totalEvents.codeReferenceEvent += 1 diff --git a/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.test.ts b/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.test.ts new file mode 100644 index 0000000000..139f6d72b8 --- /dev/null +++ b/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.test.ts @@ -0,0 +1,44 @@ +import { expect } from 'chai' +import { parseSubscriptionUpgradeUrl } from './paidTier' + +describe('parseSubscriptionUpgradeUrl', () => { + // The form of the URL that the service returns + const signInUrl = + 'https://signin.aws.amazon.com/oauth?redirect_uri=https://us-east-1.console.aws.amazon.com/amazonq/developer/home?hashArgs=%23%2Fsubscriptions&isauthcode=true®ion=us-east-1&client_id=arn:aws:signin:::console/codewhisperer&response_type=code' + + const accepted: Array<[string, string]> = [ + [signInUrl, signInUrl], + ['HTTPS://SIGNIN.AWS.AMAZON.COM/oauth', 'https://signin.aws.amazon.com/oauth'], + ['https://signin.aws.amazon.com:443/oauth', 'https://signin.aws.amazon.com/oauth'], + ] + for (const [input, expected] of accepted) { + it(`accepts ${input.slice(0, 60)} and returns it in normalized form`, () => { + expect(parseSubscriptionUpgradeUrl(input)).to.equal(expected) + }) + } + + const rejected: Array = [ + undefined, + '', + 'not a url', + 'http://signin.aws.amazon.com/oauth', + 'vscode://publisher.extension/path', + 'file:///tmp/file.txt', + 'data:text/plain,hello', + 'https://example.com/oauth', + 'https://signin.aws.amazon.com.example.com/oauth', + 'https://examplesignin.aws.amazon.com/oauth', + 'https://example.signin.aws.amazon.com/console', + 'https://us-east-1.signin.aws.amazon.com/oauth', + 'https://us-east-1.console.aws.amazon.com/amazonq/developer/home', + 'https://user:password@signin.aws.amazon.com/oauth', + 'https://example.com\\@signin.aws.amazon.com/oauth', + 'https://signin.aws.amazon.com:8443/oauth', + 'https://signin.aws.amazon.com./oauth', + ] + for (const input of rejected) { + it(`rejects ${JSON.stringify(input)}`, () => { + expect(parseSubscriptionUpgradeUrl(input)).to.be.undefined + }) + } +}) diff --git a/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.ts b/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.ts index 6d62fbd9e3..9ba053abc9 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/paidTier/paidTier.ts @@ -8,6 +8,35 @@ export const paidTierManageSubscription = 'https://us-east-1.console.aws.amazon.com/amazonq/developer/home?region=us-east-1#/subscriptions' export const freeTierLimitUserMsg = `Monthly request limit reached. Connect your Builder ID to an AWS account to upgrade to ${qProName} and increase your monthly limits.` +// The service builds the subscription upgrade URL on https://signin.aws.amazon.com/oauth. Only this host is +// accepted, not its subdomains. +const SUBSCRIPTION_UPGRADE_HOST = 'signin.aws.amazon.com' + +/** + * The subscription upgrade URL from the service response, in normalized form. The client opens it in the external + * browser, so anything other than an https URL on the AWS sign-in host (another scheme or host, a user name or + * password, a non-default port) is rejected, and the result is undefined. + */ +export function parseSubscriptionUpgradeUrl(uri: string | undefined): string | undefined { + if (!uri) { + return undefined + } + + let url: URL + try { + url = new URL(uri) + } catch { + return undefined + } + + // URL lowercases the host and reports the default https port as ''. + if (url.protocol !== 'https:' || url.username || url.password || url.port) { + return undefined + } + + return url.hostname === SUBSCRIPTION_UPGRADE_HOST ? url.href : undefined +} + export function onPaidTierLearnMore(lsp: awsLsp.Lsp, log: awsLsp.Logging) { lsp.window .showDocument({ diff --git a/server/aws-lsp-codewhisperer/src/shared/utils.test.ts b/server/aws-lsp-codewhisperer/src/shared/utils.test.ts index 65f41d6da0..32f41a9ee0 100644 --- a/server/aws-lsp-codewhisperer/src/shared/utils.test.ts +++ b/server/aws-lsp-codewhisperer/src/shared/utils.test.ts @@ -31,6 +31,7 @@ import { isUsingIAMAuth, getBearerTokenFromProviderWithType, sanitizeLogInput, + isWebUrl, } from './utils' import { promises as fsPromises } from 'fs' @@ -1083,3 +1084,50 @@ describe('sanitizeRequestInput', () => { }) }) }) + +describe('isWebUrl', () => { + for (const url of [ + 'https://example.com', + 'https://docs.example.com/guide?a=1#part', + 'http://example.com:8080/x', + 'HTTPS://EXAMPLE.COM/', + 'https://user:pass@example.com/', + 'https://127.0.0.1/', + 'https://[::1]/', + ' https://example.com/ ', + ]) { + it(`accepts ${JSON.stringify(url)}`, () => { + assert.strictEqual(isWebUrl(url), true) + }) + } + + for (const url of [ + undefined, + '', + 'javascript:x', + 'JavaScript:x', + ' javascript:x', + '\u0000javascript:x', + 'java\nscript:x', + 'data:text/html,hello', + 'vbscript:x', + 'file:///etc/hosts', + 'file://server/share/x', + 'vscode://settings/x', + 'command:workbench.action.reloadWindow', + 'mailto:someone@example.com', + 'ftp://example.com/x', + 'ws://example.com/', + 'about:blank', + 'blob:https://example.com/id', + 'https://', + '//example.com/x', + '/etc/hosts', + 'docs/relative.md', + 'not a url', + ]) { + it(`rejects ${JSON.stringify(url)}`, () => { + assert.strictEqual(isWebUrl(url), false) + }) + } +}) diff --git a/server/aws-lsp-codewhisperer/src/shared/utils.ts b/server/aws-lsp-codewhisperer/src/shared/utils.ts index 374e1216af..677f7212b8 100644 --- a/server/aws-lsp-codewhisperer/src/shared/utils.ts +++ b/server/aws-lsp-codewhisperer/src/shared/utils.ts @@ -697,3 +697,20 @@ export function sanitizeRequestInput(input: any): any { } return input } + +/** + * Whether `url` is an absolute http or https URL with a host name. The chat UI shows the source links of a + * response and the IDE opens them, so a source link with any other URL is dropped. + */ +export function isWebUrl(url: string | undefined): boolean { + if (!url) { + return false + } + try { + // `URL` rejects an http or https URL without a host. + const { protocol } = new URL(url) + return protocol === 'http:' || protocol === 'https:' + } catch { + return false + } +}