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

feat(vscode): Auto regenerate managed api connection keys #4982

Merged
merged 18 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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 apps/vs-code-designer/src/app/commands/pickFuncProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Platform, autoStartAzuriteSetting, defaultFuncPort, hostStartTaskName,
import { ext } from '../../extensionVariables';
import { localize } from '../../localize';
import { preDebugValidate } from '../debug/validatePreDebug';
import { verifyLocalConnectionKeys } from '../utils/appSettings/connectionKeys';
import { activateAzurite } from '../utils/azurite/activateAzurite';
import { getProjFiles } from '../utils/dotnet/dotnet';
import { getFuncPortFromTaskOrProject, isFuncHostTask, runningFuncTaskMap } from '../utils/funcCoreTools/funcHostTask';
Expand Down Expand Up @@ -35,17 +36,16 @@ export async function pickFuncProcess(context: IActionContext, debugConfig: vsco
await callWithTelemetryAndErrorHandling(autoStartAzuriteSetting, async (actionContext: IActionContext) => {
await runWithDurationTelemetry(actionContext, autoStartAzuriteSetting, async () => {
await activateAzurite(context);
await verifyLocalConnectionKeys(context);
JoaquimMalcampo marked this conversation as resolved.
Show resolved Hide resolved
});
});

const result: IPreDebugValidateResult = await preDebugValidate(context, debugConfig);

if (!result.shouldContinue) {
throw new UserCancelledError('preDebugValidate');
}

await waitForPrevFuncTaskToStop(result.workspace);

const projectFiles = await getProjFiles(context, ProjectLanguage.CSharp, result.workspace.uri.fsPath);
const isBundleProject: boolean = projectFiles.length > 0 ? false : true;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
} from '../../../utils/codeless/common';
import {
addConnectionData,
containsApiHubConnectionReference,
getConnectionsAndSettingsToUpdate,
getConnectionsFromFile,
getLogicAppProjectRoot,
Expand Down Expand Up @@ -255,20 +254,17 @@ export default class OpenDesignerForLocalProject extends OpenDesignerBase {
workflow.definition = definitionToSave;

if (connectionReferences) {
const projectPath = await getLogicAppProjectRoot(this.context, filePath);
const connectionsAndSettingsToUpdate = await getConnectionsAndSettingsToUpdate(
this.context,
filePath,
projectPath,
connectionReferences,
azureTenantId,
workflowBaseManagementUri,
parametersFromDefinition
);

await saveConnectionReferences(this.context, filePath, connectionsAndSettingsToUpdate);

if (containsApiHubConnectionReference(connectionReferences)) {
window.showInformationMessage(localize('keyValidity', 'The connection will be valid for 7 days only.'), 'OK');
}
await saveConnectionReferences(this.context, projectPath, connectionsAndSettingsToUpdate);
}

if (parametersFromDefinition) {
Expand Down
54 changes: 54 additions & 0 deletions apps/vs-code-designer/src/app/utils/appSettings/connectionKeys.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { isEmptyString } from '@microsoft/logic-apps-shared';
import { localize } from '../../../localize';
import { tryGetLogicAppProjectRoot } from '../verifyIsProject';
import { getWorkspaceFolder } from '../workspace';
import { getAzureConnectorDetailsForLocalProject } from '../codeless/common';
import { getParametersJson } from '../codeless/parameter';
import type { IActionContext } from '@microsoft/vscode-azext-utils';
import { workspace } from 'vscode';
import { ext } from '../../../extensionVariables';
import type { AzureConnectorDetails, ConnectionsData } from '@microsoft/vscode-extension-logic-apps';
import { getConnectionsAndSettingsToUpdate, getConnectionsJson, saveConnectionReferences } from '../codeless/connection';

export async function verifyLocalConnectionKeys(context: IActionContext): Promise<void> {
if (workspace.workspaceFolders && workspace.workspaceFolders.length > 0) {
const workspaceFolder = await getWorkspaceFolder(context);
const projectPath = await tryGetLogicAppProjectRoot(context, workspaceFolder);
let azureDetails: AzureConnectorDetails;

if (projectPath) {
azureDetails = await getAzureConnectorDetailsForLocalProject(context, projectPath);
try {
const connectionsJson = await getConnectionsJson(projectPath);
if (isEmptyString(connectionsJson)) {
return;
JoaquimMalcampo marked this conversation as resolved.
Show resolved Hide resolved
}
const connectionsData: ConnectionsData = JSON.parse(connectionsJson);
const parametersData = getParametersJson(projectPath);
const managedApiConnectionReferences = connectionsData.managedApiConnections;

if (connectionsData.managedApiConnections && !(Object.keys(managedApiConnectionReferences).length === 0)) {
const connectionsAndSettingsToUpdate = await getConnectionsAndSettingsToUpdate(
context,
projectPath,
managedApiConnectionReferences,
azureDetails.tenantId,
azureDetails.workflowManagementBaseUrl,
parametersData
);

await saveConnectionReferences(this.context, projectPath, connectionsAndSettingsToUpdate);
}
} catch (error) {
const errorMessage = localize(
'errorVerifyingConnectionKeys',
'Error while verifying existing managed api connections: {0}',
error.message ?? error
);
ext.outputChannel.appendLog(errorMessage);
context.telemetry.properties.error = errorMessage;
throw new Error(errorMessage);
}
}
}
}
39 changes: 33 additions & 6 deletions apps/vs-code-designer/src/app/utils/codeless/connection.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { azurePublicBaseUrl, connectionsFileName } from '../../../constants';
import { azurePublicBaseUrl, connectionsFileName, localSettingsFileName } from '../../../constants';
import { localize } from '../../../localize';
import { isCSharpProject } from '../../commands/initProjectForVSCode/detectProjectLanguage';
import { addOrUpdateLocalAppSettings } from '../appSettings/localSettings';
import { addOrUpdateLocalAppSettings, getLocalSettingsJson } from '../appSettings/localSettings';
import { writeFormattedJson } from '../fs';
import { sendAzureRequest } from '../requestUtils';
import { tryGetLogicAppProjectRoot } from '../verifyIsProject';
Expand All @@ -14,8 +14,10 @@ import { addNewFileInCSharpProject } from './updateBuildFile';
import { HTTP_METHODS, isString } from '@microsoft/logic-apps-shared';
import type { ParsedSite } from '@microsoft/vscode-azext-azureappservice';
import { nonNullValue } from '@microsoft/vscode-azext-utils';
import { JwtTokenHelper, JwtTokenConstants } from '../../../../../vs-code-react/src/app/designer/services/JwtHelper';
import type { IActionContext } from '@microsoft/vscode-azext-utils';
JoaquimMalcampo marked this conversation as resolved.
Show resolved Hide resolved
import type {
ILocalSettingsJson,
ServiceProviderConnectionModel,
ConnectionAndSettings,
ConnectionReferenceModel,
Expand Down Expand Up @@ -123,6 +125,15 @@ async function addConnectionDataInJson(
}
}

function isKeyExpired(jwtTokenHelper: JwtTokenHelper, connectionKey: string, bufferInHours: number): boolean {
const payload: Record<string, any> = jwtTokenHelper.extractJwtTokenPayload(connectionKey);
JoaquimMalcampo marked this conversation as resolved.
Show resolved Hide resolved
const secondsSinceEpoch = Math.round(Date.now() / 1000);
const buffer = bufferInHours * 3600; // convert to seconds
const expiry = payload[JwtTokenConstants.expiry];

return expiry - buffer <= secondsSinceEpoch;
}

async function getConnectionReference(
referenceKey: string,
reference: any,
Expand Down Expand Up @@ -168,20 +179,24 @@ async function getConnectionReference(
});
}

//change workflow file path to project root

JoaquimMalcampo marked this conversation as resolved.
Show resolved Hide resolved
export async function getConnectionsAndSettingsToUpdate(
context: IActionContext,
workflowFilePath: string,
projectPath: string,
connectionReferences: any,
azureTenantId: string,
workflowBaseManagementUri: string,
parametersFromDefinition: any
): Promise<ConnectionAndSettings> {
const projectPath = await getLogicAppProjectRoot(context, workflowFilePath);
const connectionsDataString = projectPath ? await getConnectionsJson(projectPath) : '';
const connectionsData = connectionsDataString === '' ? {} : JSON.parse(connectionsDataString);
const localSettingsPath: string = path.join(projectPath, localSettingsFileName);
const settings: ILocalSettingsJson = await getLocalSettingsJson(context, localSettingsPath);

const referencesToAdd = connectionsData.managedApiConnections || {};
const settingsToAdd: Record<string, string> = {};
const jwtTokenHelper: JwtTokenHelper = JwtTokenHelper.createInstance();
let accessToken: string | undefined;

for (const referenceKey of Object.keys(connectionReferences)) {
Expand All @@ -197,6 +212,19 @@ export async function getConnectionsAndSettingsToUpdate(
settingsToAdd,
parametersFromDefinition
);
} else if (
settings.Values[`${referenceKey}-connectionKey`] &&
isKeyExpired(jwtTokenHelper, settings.Values[`${referenceKey}-connectionKey`], 192)
) {
accessToken = accessToken ? accessToken : await getAuthorizationToken(/* credentials */ undefined, azureTenantId);
referencesToAdd[referenceKey] = await getConnectionReference(
referenceKey,
reference,
accessToken,
workflowBaseManagementUri,
settingsToAdd,
parametersFromDefinition
);
}
}

Expand All @@ -210,10 +238,9 @@ export async function getConnectionsAndSettingsToUpdate(

export async function saveConnectionReferences(
context: IActionContext,
workflowFilePath: string,
projectPath: string,
connectionAndSettingsToUpdate: ConnectionAndSettings
): Promise<void> {
const projectPath = await getLogicAppProjectRoot(context, workflowFilePath);
const { connections, settings } = connectionAndSettingsToUpdate;
const connectionsFilePath = path.join(projectPath, connectionsFileName);
const connectionsFileExists = fse.pathExistsSync(connectionsFilePath);
Expand Down
3 changes: 2 additions & 1 deletion apps/vs-code-designer/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { extensionCommand, logicAppFilter } from './constants';
import { ext } from './extensionVariables';
import { startOnboarding } from './onboarding';
import { registerAppServiceExtensionVariables } from '@microsoft/vscode-azext-azureappservice';
import { verifyLocalConnectionKeys } from './app/utils/appSettings/connectionKeys';
import {
callWithTelemetryAndErrorHandling,
createAzExtOutputChannel,
Expand Down Expand Up @@ -46,7 +47,6 @@ export async function activate(context: vscode.ExtensionContext) {
ext.context = context;

ext.outputChannel = createAzExtOutputChannel('Azure Logic Apps (Standard)', ext.prefix);

registerUIExtensionVariables(ext);
registerAppServiceExtensionVariables(ext);

Expand All @@ -58,6 +58,7 @@ export async function activate(context: vscode.ExtensionContext) {

await downloadExtensionBundle(activateContext);
promptParameterizeConnections(activateContext);
verifyLocalConnectionKeys(activateContext);
await startOnboarding(activateContext);

ext.extensionVersion = getExtensionVersion();
Expand Down
5 changes: 3 additions & 2 deletions apps/vs-code-react/src/app/designer/services/JwtHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class JwtTokenHelper {
private base64DecodeStringUrlSafe(base64String: string): string {
let tempString = base64String;
// html5 should support atob function for decoding
if (window.atob) {
if (typeof window !== 'undefined' && window && window.atob) {
// window.atob function decodes base64 string
// decodeURIComponent + escape function decodes UTF-8 string
// escape function is being deprecated but is still supported by all browsers
Expand All @@ -65,6 +65,7 @@ export class JwtTokenHelper {
return decodeURIComponent(window['escape'](window.atob(tempString)));
}

throw new Error('atob not supported');
const data = Buffer.from(base64String, 'base64').toString('binary');
return decodeURIComponent(data);
}
}
Loading