More azurecore cleanup (#22748)

* More azurecore cleanup

* convert to any

* Fix name
This commit is contained in:
Charles Gagnon
2023-04-17 10:29:49 -07:00
committed by GitHub
parent f66d3349b9
commit 4a4580e9ef
5 changed files with 61 additions and 61 deletions

View File

@@ -27,7 +27,7 @@ import { AzureAuthError } from './azureAuthError';
import { AccountInfo, AuthenticationResult, InteractionRequiredAuthError, PublicClientApplication } from '@azure/msal-node'; import { AccountInfo, AuthenticationResult, InteractionRequiredAuthError, PublicClientApplication } from '@azure/msal-node';
import { HttpClient } from './httpClient'; import { HttpClient } from './httpClient';
import { getProxyEnabledHttpClient } from '../../utils'; import { getProxyEnabledHttpClient } from '../../utils';
import { errorToPromptFailedResult } from './networkUtils';
const localize = nls.loadMessageBundle(); const localize = nls.loadMessageBundle();
export abstract class AzureAuth implements vscode.Disposable { export abstract class AzureAuth implements vscode.Disposable {
@@ -146,22 +146,14 @@ export abstract class AzureAuth implements vscode.Disposable {
} }
Logger.error(ex.originalMessageAndException); Logger.error(ex.originalMessageAndException);
} else { } else {
const message = ex.errorMessage || ex.message; const promptFailedResult = errorToPromptFailedResult(ex);
if (message) { if (promptFailedResult.errorMessage) {
loginComplete?.reject(new AzureAuthError(message, message, undefined)); loginComplete?.reject(new AzureAuthError(promptFailedResult.errorMessage, promptFailedResult.errorMessage, undefined));
return { return promptFailedResult;
canceled: false,
errorCode: ex.errorCode,
errorMessage: message
};
} }
Logger.error(ex); Logger.error(ex);
} }
return { return errorToPromptFailedResult(ex);
canceled: false,
errorCode: ex.errorCode,
errorMessage: ex.errorMessage || ex.message
};
} }
} }
@@ -373,12 +365,7 @@ export abstract class AzureAuth implements vscode.Disposable {
if (e.name === 'ClientAuthError') { if (e.name === 'ClientAuthError') {
Logger.verbose('[ClientAuthError] Failed to silently acquire token'); Logger.verbose('[ClientAuthError] Failed to silently acquire token');
} }
return { return errorToPromptFailedResult(e);
canceled: false,
name: e.name,
errorCode: e.errorCode,
errorMessage: e.errorMessage || e.message
}
} }
} }
} }
@@ -610,10 +597,10 @@ export abstract class AzureAuth implements vscode.Disposable {
Logger.error('No access token found'); Logger.error('No access token found');
return undefined; return undefined;
} }
const accessToken: AccessToken = JSON.parse(accessTokenString); const accessToken: AccessToken = JSON.parse(accessTokenString) as AccessToken;
let refreshToken: RefreshToken | undefined = undefined; let refreshToken: RefreshToken | undefined = undefined;
if (refreshTokenString) { if (refreshTokenString) {
refreshToken = JSON.parse(refreshTokenString); refreshToken = JSON.parse(refreshTokenString) as RefreshToken;
} }
Logger.piiSanitized('GetSavedToken ', [{ name: 'access', objOrArray: accessToken }, { name: 'refresh', objOrArray: refreshToken }], [], `expiresOn=${expiresOn}`); Logger.piiSanitized('GetSavedToken ', [{ name: 'access', objOrArray: accessToken }, { name: 'refresh', objOrArray: refreshToken }], [], `expiresOn=${expiresOn}`);
return { return {

View File

@@ -8,7 +8,7 @@ import { INetworkModule, NetworkRequestOptions, NetworkResponse } from '@azure/m
import * as http from 'http'; import * as http from 'http';
import * as https from 'https'; import * as https from 'https';
import { TextEncoder } from 'util'; import { TextEncoder } from 'util';
import { NetworkUtils } from './networkUtils'; import { getNetworkResponse, urlToHttpOptions } from './networkUtils';
/** /**
* http methods * http methods
@@ -247,7 +247,7 @@ const networkRequestViaProxy = <T>(
}); });
const parsedHeaders = Object.fromEntries(entries) as Record<string, string>; const parsedHeaders = Object.fromEntries(entries) as Record<string, string>;
const networkResponse = NetworkUtils.getNetworkResponse( const networkResponse = getNetworkResponse(
parsedHeaders, parsedHeaders,
parseBody(httpStatusCode, statusMessage, parsedHeaders, body) as T, parseBody(httpStatusCode, statusMessage, parsedHeaders, body) as T,
httpStatusCode httpStatusCode
@@ -293,7 +293,7 @@ const networkRequestViaHttps = <T>(
let customOptions: https.RequestOptions = { let customOptions: https.RequestOptions = {
method: httpMethod, method: httpMethod,
headers: optionHeaders, headers: optionHeaders,
...NetworkUtils.urlToHttpOptions(url) ...urlToHttpOptions(url)
}; };
if (timeout) { if (timeout) {
@@ -343,7 +343,7 @@ const networkRequestViaHttps = <T>(
const dataBody = Buffer.concat([...data]).toString(); const dataBody = Buffer.concat([...data]).toString();
const parsedHeaders = headers as Record<string, string>; const parsedHeaders = headers as Record<string, string>;
const networkResponse = NetworkUtils.getNetworkResponse( const networkResponse = getNetworkResponse(
parsedHeaders, parsedHeaders,
parseBody(statusCode, statusMessage, parsedHeaders, dataBody) as T, parseBody(statusCode, statusMessage, parsedHeaders, dataBody) as T,
statusCode statusCode

View File

@@ -3,41 +3,54 @@
* Licensed under the Source EULA. See License.txt in the project root for license information. * Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as azdata from 'azdata';
import { NetworkResponse } from '@azure/msal-common'; import { NetworkResponse } from '@azure/msal-common';
import * as https from 'https'; import * as https from 'https';
export class NetworkUtils { export function getNetworkResponse<Body>(headers: Record<string, string>, body: Body, statusCode: number): NetworkResponse<Body> {
static getNetworkResponse<Body>(headers: Record<string, string>, body: Body, statusCode: number): NetworkResponse<Body> { return {
return { headers: headers,
headers: headers, body: body,
body: body, status: statusCode
status: statusCode };
}; }
}
/*
/* * Utility function that converts a URL object into an ordinary options object as expected by the
* Utility function that converts a URL object into an ordinary options object as expected by the * http.request and https.request APIs.
* http.request and https.request APIs. */
*/ export function urlToHttpOptions(url: URL): https.RequestOptions {
static urlToHttpOptions(url: URL): https.RequestOptions { const options: https.RequestOptions & Partial<Omit<URL, 'port'>> = {
const options: https.RequestOptions & Partial<Omit<URL, 'port'>> = { protocol: url.protocol,
protocol: url.protocol, hostname: url.hostname && url.hostname.startsWith('[') ?
hostname: url.hostname && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) :
url.hostname.slice(1, -1) : url.hostname,
url.hostname, hash: url.hash,
hash: url.hash, search: url.search,
search: url.search, pathname: url.pathname,
pathname: url.pathname, path: `${url.pathname || ''}${url.search || ''}`,
path: `${url.pathname || ''}${url.search || ''}`, href: url.href
href: url.href };
}; if (url.port !== '') {
if (url.port !== '') { options.port = Number(url.port);
options.port = Number(url.port); }
} if (url.username || url.password) {
if (url.username || url.password) { options.auth = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
options.auth = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`; }
} return options;
return options; }
}
/**
* Takes an error and converts it into a PromptFailedResult object with data from the original error about the failure
* @param err The error to convert into a PromptFailedResult
* @returns The PromptFailedResult object
*/
export function errorToPromptFailedResult(err: any): azdata.PromptFailedResult {
return {
canceled: false,
name: err.name as string,
errorCode: err.errorCode as string,
errorMessage: err.errorMessage as string || err.message as string
};
} }

View File

@@ -260,7 +260,7 @@ export async function runResourceQuery<T extends azureResource.AzureGraphResourc
skipToken: skipToken skipToken: skipToken
} }
}); });
const resources: T[] = response.data; const resources: T[] = response.data as T[];
totalProcessed += resources.length; totalProcessed += resources.length;
allResources.push(...resources); allResources.push(...resources);
if (response.skipToken && totalProcessed < response.totalRecords) { if (response.skipToken && totalProcessed < response.totalRecords) {

View File

@@ -64,7 +64,7 @@ export class Logger {
* @param stringsToShorten Set of strings to shorten * @param stringsToShorten Set of strings to shorten
* @param vals Any other values to add on to the end of the log message * @param vals Any other values to add on to the end of the log message
*/ */
static piiSanitized(msg: any, objsToSanitize: { name: string, objOrArray: any | any[] }[], stringsToShorten: { name: string, value: string }[], ...vals: any[]) { static piiSanitized(msg: any, objsToSanitize: { name: string, objOrArray: any }[], stringsToShorten: { name: string, value: string }[], ...vals: any[]) {
if (this.piiLogging) { if (this.piiLogging) {
msg = [ msg = [
msg, msg,