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 17 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
6 changes: 4 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 @@ -36,16 +37,17 @@ export async function pickFuncProcess(context: IActionContext, debugConfig: vsco
await runWithDurationTelemetry(actionContext, autoStartAzuriteSetting, async () => {
await activateAzurite(context);
});
await runWithDurationTelemetry(actionContext, autoStartAzuriteSetting, async () => {
JoaquimMalcampo marked this conversation as resolved.
Show resolved Hide resolved
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
55 changes: 55 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,55 @@
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)) {
ext.outputChannel.appendLog(localize('noConnectionKeysFound', 'No connection keys found to verify'));
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);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { isKeyExpired } from '../connection';
import { JwtTokenHelper } from '@microsoft/vscode-extension-logic-apps';
import { describe, it, expect } from 'vitest';

describe('isKeyExpired', () => {
it('should expose the isKeyExpired function'),
() => {
expect(isKeyExpired).toBeDefined();
};
});

describe('isKeyExpired with JWTs', () => {
const jwtTokenHelper: JwtTokenHelper = JwtTokenHelper.createInstance();
// expires June 17 2024 13:56:44
const expiredConnectionKey =
'eyJhbGciOiJSUzI1NiIsImtpZCI6IjU5NUZDMDdGQTI0RTEyQjdGRUIyMDU2M0FGNkJEMDQ5REU1ODdBMkQiLCJ4NXQiOiJXVl9BZjZKT0VyZi1zZ1ZqcjJ2UVNkNVllaTAiLCJ0eXAiOiJKV1QifQ.eyJ0cyI6IjcyZjk4OGJmLTg2ZjEtNDFhZi05MWFiLTJkN2NkMDExZGI0NyIsImNzIjoibG9naWMtYXBpcy1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VSVHnnptAQ';

it('should return true for a JWT with an expiry earlier than the test date', () => {
const testDate: number = Date.UTC(2024, 4); // May 1 2024 00:00:00
expect(isKeyExpired(jwtTokenHelper, testDate, expiredConnectionKey, 0)).toBeFalsy();
});

it('should return false for a JWT with an expiry later than the test date', () => {
const testDate: number = Date.UTC(2024, 6); // July 1 2024 00:00:00
expect(isKeyExpired(jwtTokenHelper, testDate, expiredConnectionKey, 0)).toBeTruthy();
});

it('should return true for a JWT with the test date in a 3 hour expiry buffer interval', () => {
const testDate: number = Date.UTC(2024, 5, 17, 12); // June 17 2024 12:00:00
expect(isKeyExpired(jwtTokenHelper, testDate, expiredConnectionKey, 3)).toBeFalsy();
});

it('should return false for a JWT with a 3 hour expiry buffer and a test date on the expiry date but outside the buffer interval', () => {
const testDate: number = Date.UTC(2024, 5, 17, 2); // June 17 2024 2:00:00
expect(isKeyExpired(jwtTokenHelper, testDate, expiredConnectionKey, 3)).toBeFalsy();
});
});
57 changes: 47 additions & 10 deletions apps/vs-code-designer/src/app/utils/codeless/connection.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
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';
import { getContainingWorkspace } from '../workspace';
import { getWorkflowParameters } from './common';
import { getAuthorizationToken } from './getAuthorizationToken';
import { getParametersJson, saveWorkflowParameterRecords } from './parameter';
import * as parameterizer from './parameterizer';
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 type { IActionContext } from '@microsoft/vscode-azext-utils';
import type {
ILocalSettingsJson,
ServiceProviderConnectionModel,
ConnectionAndSettings,
ConnectionReferenceModel,
Expand All @@ -24,10 +24,12 @@ import type {
ConnectionAndAppSetting,
Parameter,
} from '@microsoft/vscode-extension-logic-apps';
import { JwtTokenHelper, JwtTokenConstants, resolveConnectionsReferences } from '@microsoft/vscode-extension-logic-apps';
import axios from 'axios';
import * as fse from 'fs-extra';
import * as path from 'path';
import * as vscode from 'vscode';
import { parameterizeConnection } from './parameterizer';

export async function getConnectionsFromFile(context: IActionContext, workflowFilePath: string): Promise<string> {
const projectRoot: string = await getLogicAppProjectRoot(context, workflowFilePath);
Expand Down Expand Up @@ -113,7 +115,7 @@ async function addConnectionDataInJson(
return;
}

parameterizer.parameterizeConnection(connectionData, connectionKey, parametersData, settings);
parameterizeConnection(connectionData, connectionKey, parametersData, settings);

pathToSetConnectionsData[connectionKey] = connectionData;
await writeFormattedJson(connectionsFilePath, connectionsJson);
Expand All @@ -123,6 +125,25 @@ async function addConnectionDataInJson(
}
}

export function isKeyExpired(jwtTokenHelper: JwtTokenHelper, date: number, connectionKey: string, bufferInHours: number): boolean {
const payload: Record<string, any> = jwtTokenHelper.extractJwtTokenPayload(connectionKey);
const secondsSinceEpoch = Math.round(date / 1000);
const buffer = bufferInHours * 3600; // convert to seconds
const expiry = payload[JwtTokenConstants.expiry];

return expiry - buffer <= secondsSinceEpoch;
}

function formatSetting(setting: string): string {
if (setting.endsWith('/')) {
setting = setting.substring(0, setting.length - 1);
}
if (setting.startsWith('/')) {
setting = setting.substring(1);
}
return setting;
}

async function getConnectionReference(
referenceKey: string,
reference: any,
Expand All @@ -139,7 +160,7 @@ async function getConnectionReference(

return axios
.post(
`${workflowBaseManagementUri}/${connectionId}/listConnectionKeys?api-version=2018-07-01-preview`,
`${formatSetting(workflowBaseManagementUri)}/${formatSetting(connectionId)}/listConnectionKeys?api-version=2018-07-01-preview`,
{ validityTimeSpan: '7' },
{ headers: { authorization: accessToken } }
)
Expand All @@ -159,7 +180,7 @@ async function getConnectionReference(
connectionProperties,
};

parameterizer.parameterizeConnection(connectionReference, referenceKey, parametersToAdd, settingsToAdd);
parameterizeConnection(connectionReference, referenceKey, parametersToAdd, settingsToAdd);

return connectionReference;
})
Expand All @@ -170,18 +191,20 @@ async function getConnectionReference(

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 localSettings: 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 +220,21 @@ export async function getConnectionsAndSettingsToUpdate(
settingsToAdd,
parametersFromDefinition
);
} else if (
localSettings.Values[`${referenceKey}-connectionKey`] &&
isKeyExpired(jwtTokenHelper, Date.now(), localSettings.Values[`${referenceKey}-connectionKey`], 3)
) {
const resolvedConnectionReference = resolveConnectionsReferences(JSON.stringify(reference), undefined, localSettings.Values);

accessToken = accessToken ? accessToken : await getAuthorizationToken(/* credentials */ undefined, azureTenantId);
referencesToAdd[referenceKey] = await getConnectionReference(
referenceKey,
resolvedConnectionReference,
accessToken,
workflowBaseManagementUri,
settingsToAdd,
parametersFromDefinition
);
}
}

Expand All @@ -210,10 +248,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
17 changes: 16 additions & 1 deletion apps/vs-code-designer/test-setup.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import '@testing-library/jest-dom/vitest';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
import { afterEach, vi } from 'vitest';

// https://testing-library.com/docs/react-testing-library/api#cleanup
afterEach(() => cleanup());

vi.mock('@microsoft/vscode-azext-azureutils', () => ({
// mock implementation or empty object
}));

vi.mock('@microsoft/vscode-azext-utils', () => {
return {
AzureWizardExecuteStep: vi.fn().mockImplementation(() => {
return {};
}),
AzureWizardPromptStep: vi.fn().mockImplementation(() => {
return {};
}),
};
});
16 changes: 5 additions & 11 deletions apps/vs-code-designer/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,19 @@
import { defineProject } from 'vitest/config';
import packageJson from './package.json';
import path from 'path';

export default defineProject({
plugins: [],
resolve: {
alias: [
{
find: 'vscode',
replacement: `${__dirname}/node_modules/@types/vscode/index.d`,
},
{
find: '@microsoft/vscode-azext-utils',
replacement: `${__dirname}/node_modules/@types/vscode/index.d`,
},
],
alias: {
vscode: path.resolve(path.join(__dirname, 'node_modules', '@types', 'vscode', 'index.d.ts')),
},
},
test: {
name: packageJson.name,
dir: './src',
watch: false,
environment: 'jsdom',
environment: 'node',
setupFiles: ['test-setup.ts'],
coverage: { enabled: true, provider: 'istanbul', include: ['src/**/*'], reporter: ['html', 'cobertura'] },
restoreMocks: true,
Expand Down
3 changes: 1 addition & 2 deletions apps/vs-code-react/src/app/designer/services/oAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { JwtTokenConstants, JwtTokenHelper } from './JwtHelper';
import type { IOAuthPopup, IOAuthService, OAuthPopupOptions } from '@microsoft/logic-apps-shared';
import { ExtensionCommand } from '@microsoft/vscode-extension-logic-apps';
import { ExtensionCommand, JwtTokenConstants, JwtTokenHelper } from '@microsoft/vscode-extension-logic-apps';

export interface LoginResult {
[x: string]: any;
Expand Down
Loading
Loading