Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

appservice: Fix tunnel proxy by using bearer auth #1536

Merged
merged 2 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions appservice/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion appservice/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@microsoft/vscode-azext-azureappservice",
"author": "Microsoft Corporation",
"version": "2.1.1",
"version": "2.1.2",
"description": "Common tools for developing Azure App Service extensions for VS Code",
"tags": [
"azure",
Expand Down
31 changes: 16 additions & 15 deletions appservice/src/TunnelProxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import type { User } from '@azure/arm-appservice';
import type { ServiceClient } from '@azure/core-client';
import { RestError, createPipelineRequest } from "@azure/core-rest-pipeline";
import { AzExtPipelineResponse, addBasicAuthenticationCredentialsToClient, createGenericClient } from '@microsoft/vscode-azext-azureutils';
import { IActionContext, IParsedError, UserCancelledError, nonNullProp, parseError } from '@microsoft/vscode-azext-utils';
import { RestError, bearerTokenAuthenticationPolicy, createPipelineRequest } from "@azure/core-rest-pipeline";
import { AzExtPipelineResponse, createGenericClient } from '@microsoft/vscode-azext-azureutils';
import { AzExtServiceClientCredentials, IActionContext, IParsedError, UserCancelledError, parseError } from '@microsoft/vscode-azext-utils';
import { Server, Socket, createServer } from 'net';
import { CancellationToken, Disposable, l10n } from 'vscode';
import * as ws from 'ws';
Expand Down Expand Up @@ -42,24 +41,25 @@ class RetryableTunnelStatusError extends Error { }
export class TunnelProxy {
private _port: number;
private _site: ParsedSite;
private _publishCredential: User;
private _server: Server;
private _openSockets: ws.WebSocket[];
private _isSsh: boolean;
private _credentials: AzExtServiceClientCredentials;

constructor(port: number, site: ParsedSite, publishCredential: User, isSsh: boolean = false) {
constructor(port: number, site: ParsedSite, credentials: AzExtServiceClientCredentials, isSsh: boolean = false) {
this._port = port;
this._site = site;
this._publishCredential = publishCredential;
this._server = createServer();
this._openSockets = [];
this._isSsh = isSsh;
this._credentials = credentials;
}

public async startProxy(context: IActionContext, token: CancellationToken): Promise<void> {
try {
await this.checkTunnelStatusWithRetry(context, token);
await this.setupTunnelServer(token);
const bearerToken = (await this._credentials.getToken() as { token: string }).token;
await this.setupTunnelServer(bearerToken, token);
} catch (error) {
this.dispose();
throw error;
Expand Down Expand Up @@ -95,16 +95,17 @@ export class TunnelProxy {
}

private async checkTunnelStatus(context: IActionContext): Promise<void> {
const publishingUserName: string = nonNullProp(this._publishCredential, 'publishingUserName');
const password: string = nonNullProp(this._publishCredential, 'publishingPassword');
const client: ServiceClient = await createGenericClient(context, undefined);
addBasicAuthenticationCredentialsToClient(client, publishingUserName, password);
client.pipeline.addPolicy(bearerTokenAuthenticationPolicy({
scopes: [],
credential: this._credentials
}));

let tunnelStatus: ITunnelStatus;
try {
const response: AzExtPipelineResponse = await client.sendRequest(createPipelineRequest({
method: 'GET',
url: `https://${this._site.kuduHostName}/AppServiceTunnel/Tunnel.ashx?GetStatus&GetStatusAPIVer=2`
url: `https://${this._site.kuduHostName}/AppServiceTunnel/Tunnel.ashx?GetStatus&GetStatusAPIVer=2`,
}));
ext.outputChannel.appendLog(`[Tunnel] Checking status, body: ${response.bodyAsText}`);
tunnelStatus = <ITunnelStatus>response.parsedBody;
Expand Down Expand Up @@ -159,7 +160,7 @@ export class TunnelProxy {
throw new Error(l10n.t('Unable to establish connection to application: Timed out'));
}

private async setupTunnelServer(token: CancellationToken): Promise<void> {
private async setupTunnelServer(bearerToken: string, token: CancellationToken): Promise<void> {
return new Promise<void>((resolve: () => void, reject: (err: Error) => void): void => {
const listener: Disposable = token.onCancellationRequested(() => {
reject(new UserCancelledError('setupTunnelServer'));
Expand All @@ -174,9 +175,9 @@ export class TunnelProxy {
headers: {
'User-Agent': 'vscode-azuretools',
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
Pragma: 'no-cache',
Authorization: `Bearer ${bearerToken}`,
},
auth: `${this._publishCredential.publishingUserName}:${this._publishCredential.publishingPassword}`,
}
);
this._openSockets.push(tunnelSocket);
Expand Down
26 changes: 16 additions & 10 deletions appservice/src/remoteDebug/startRemoteDebug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import type { SiteConfigResource, User } from '@azure/arm-appservice';
import type { SiteConfigResource } from '@azure/arm-appservice';
import { callWithTelemetryAndErrorHandling, findFreePort, IActionContext } from '@microsoft/vscode-azext-utils';
import * as vscode from 'vscode';
import { ParsedSite } from '../SiteClient';
import { TunnelProxy } from '../TunnelProxy';
import { reportMessage, setRemoteDebug } from './remoteDebugCommon';
import { AzExtGenericCredentials } from '@microsoft/vscode-azext-azureutils';

const remoteDebugLink: string = 'https://aka.ms/appsvc-remotedebug';

Expand All @@ -19,33 +20,38 @@ export enum RemoteDebugLanguage {
Python
}

export async function startRemoteDebug(context: IActionContext, site: ParsedSite, siteConfig: SiteConfigResource, language: RemoteDebugLanguage): Promise<void> {
interface StartRemoteDebuggingOptions {
credentials: AzExtGenericCredentials;
site: ParsedSite;
siteConfig: SiteConfigResource;
language: RemoteDebugLanguage;
}

export async function startRemoteDebug(context: IActionContext, options: StartRemoteDebuggingOptions): Promise<void> {
if (isRemoteDebugging) {
throw new Error(vscode.l10n.t('Azure Remote Debugging is currently starting or already started.'));
}

isRemoteDebugging = true;
try {
await startRemoteDebugInternal(context, site, siteConfig, language);
await startRemoteDebugInternal(context, options);
} catch (error) {
isRemoteDebugging = false;
throw error;
}
}

async function startRemoteDebugInternal(context: IActionContext, site: ParsedSite, siteConfig: SiteConfigResource, language: RemoteDebugLanguage): Promise<void> {
async function startRemoteDebugInternal(context: IActionContext, options: StartRemoteDebuggingOptions): Promise<void> {
await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, cancellable: true }, async (progress, token): Promise<void> => {
const localHostPortNumber: number = await findFreePort();
const debugConfig: vscode.DebugConfiguration = await getDebugConfiguration(language, localHostPortNumber);
const debugConfig: vscode.DebugConfiguration = await getDebugConfiguration(options.language, localHostPortNumber);

const confirmEnableMessage: string = vscode.l10n.t('The configuration will be updated to enable remote debugging. Would you like to continue? This will restart the app.');
await setRemoteDebug(context, true, confirmEnableMessage, undefined, site, siteConfig, progress, token, remoteDebugLink);
await setRemoteDebug(context, true, confirmEnableMessage, undefined, options.site, options.siteConfig, progress, token, remoteDebugLink);

reportMessage(vscode.l10n.t('Starting tunnel proxy...'), progress, token);

const client = await site.createClient(context);
const publishCredential: User = await client.getWebAppPublishCredential();
const tunnelProxy: TunnelProxy = new TunnelProxy(localHostPortNumber, site, publishCredential);
const tunnelProxy: TunnelProxy = new TunnelProxy(localHostPortNumber, options.site, options.credentials);
await callWithTelemetryAndErrorHandling('appService.remoteDebugStartProxy', async (startContext: IActionContext) => {
startContext.errorHandling.suppressDisplay = true;
startContext.errorHandling.rethrow = true;
Expand Down Expand Up @@ -73,7 +79,7 @@ async function startRemoteDebugInternal(context: IActionContext, site: ParsedSit

const confirmDisableMessage: string = vscode.l10n.t('Remaining in debugging mode may cause performance issues. Would you like to disable debugging? This will restart the app.');
await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, cancellable: true }, async (innerProgress, innerToken): Promise<void> => {
await setRemoteDebug(context, false, confirmDisableMessage, undefined, site, siteConfig, innerProgress, innerToken, remoteDebugLink);
await setRemoteDebug(context, false, confirmDisableMessage, undefined, options.site, options.siteConfig, innerProgress, innerToken, remoteDebugLink);
});
}
});
Expand Down