Skip to content

Commit

Permalink
create a type for PS Script output and add some test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
YanaXu committed Oct 17, 2023
1 parent 4d29ec0 commit 3caf02d
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 20 deletions.
29 changes: 26 additions & 3 deletions __tests__/PowerShell/AzPSLogin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,39 @@ describe('Testing runPSScript', () => {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
$output['${AzPSConstants.Success}'] = "true"
$output['${AzPSConstants.Result}'] = $PSVersionTable.PSVersion.ToString()
$output['Success'] = $true
$output['Result'] = $PSVersionTable.PSVersion.ToString()
}
catch {
$output['${AzPSConstants.Error}'] = $_.exception.Message
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;

let psVersion: string = await AzPSLogin.runPSScript(script);
expect(psVersion === null).toBeFalsy();
});

test('Get PowerShell Version with Wrong Name', async () => {
let script = `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
$output['Success'] = $true
$output['Result'] = $PSVersionTableWrongName.PSVersion.ToString()
}
catch {
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;

try{
await AzPSLogin.runPSScript(script);
throw new Error("The last step should fail.");
}catch(error){
expect(error.message.includes("Azure PowerShell login failed with error: You cannot call a method on a null-valued expression.")).toBeTruthy();
}
});

});
23 changes: 22 additions & 1 deletion __tests__/PowerShell/AzPSScriptBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ describe("Getting AzLogin PS script", () => {
setEnv('auth-type', 'SERVICE_PRINCIPAL');
let creds = {
'clientId': 'client-id',
'clientSecret': 'client-secret',
'clientSecret': "client-secret",
'tenantId': 'tenant-id',
'subscriptionId': 'subscription-id'
}
Expand All @@ -45,6 +45,27 @@ describe("Getting AzLogin PS script", () => {
});
});

test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=true, secret with single-quote', () => {
setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'true');
setEnv('auth-type', 'SERVICE_PRINCIPAL');
let creds = {
'clientId': 'client-id',
'clientSecret': "client-se'cret",
'tenantId': 'tenant-id',
'subscriptionId': 'subscription-id'
}
setEnv('creds', JSON.stringify(creds));

let loginConfig = new LoginConfig();
loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; $psLoginSecrets = ConvertTo-SecureString 'client-se''cret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy();
expect(loginMethod).toBe('service principal with secret');
});
});

test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=false', () => {
setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true');
Expand Down
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Login to Azure subscription
name: 'Azure Login'
description: 'Authenticate to Azure using OIDC and run your Azure CLI or Azure PowerShell based actions or scripts. github.com/Azure/Actions'
description: 'Authenticate to Azure and run your Azure CLI or Azure PowerShell based actions or scripts.'
inputs:
creds:
description: 'Paste output of `az ad sp create-for-rbac` as value of secret variable: AZURE_CREDENTIALS'
Expand Down
5 changes: 0 additions & 5 deletions src/PowerShell/AzPSConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ export default class AzPSConstants {
static readonly DEFAULT_AZ_PATH_ON_LINUX: string = '/usr/share';
static readonly DEFAULT_AZ_PATH_ON_WINDOWS: string = 'C:\\Modules';
static readonly AzAccounts: string = "Az.Accounts";

static readonly PowerShell_CmdName = "pwsh";

static readonly Success: string = "Success";
static readonly Error: string = "Error";
static readonly Result: string = "Result";
}

15 changes: 11 additions & 4 deletions src/PowerShell/AzPSLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ import AzPSScriptBuilder from './AzPSScriptBuilder';
import AzPSConstants from './AzPSConstants';
import { LoginConfig } from '../common/LoginConfig';

interface PSResultType {
Result: string;
Success: boolean;
Error: string;
}

export class AzPSLogin {
loginConfig: LoginConfig;

Expand Down Expand Up @@ -83,11 +89,12 @@ export class AzPSLogin {
if (commandStdErr) {
throw new Error('Azure PowerShell login failed with errors.');
}
const result: any = JSON.parse(outputString.trim());
if (!(AzPSConstants.Success in result)) {
throw new Error(`Azure PowerShell login failed with error: ${result[AzPSConstants.Error]}`);
const result: PSResultType = JSON.parse(outputString.trim());
console.log(result);
if (!(result.Success)) {
throw new Error(`Azure PowerShell login failed with error: ${result.Error}`);
}
return result[AzPSConstants.Result];
return result.Result;
}
}

14 changes: 8 additions & 6 deletions src/PowerShell/AzPSScriptBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ export default class AzPSScriptBuilder {
$output = @{}
$latestModulePath = (Get-Module -Name '${moduleName}' -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Path
Import-Module -Name $latestModulePath
$output['${AzPSConstants.Result}'] = $latestModulePath
$output['${AzPSConstants.Success}'] = "true"
$output['Success'] = $true
$output['Result'] = $latestModulePath
}
catch {
$output['${AzPSConstants.Error}'] = $_.exception.Message
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;

Expand Down Expand Up @@ -52,11 +53,12 @@ export default class AzPSScriptBuilder {
$WarningPreference = "SilentlyContinue"
$output = @{}
${commands}
$output['${AzPSConstants.Success}'] = "true"
$output['${AzPSConstants.Result}'] = ""
$output['Success'] = $true
$output['Result'] = ""
}
catch {
$output['${AzPSConstants.Error}'] = $_.exception.Message
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;

Expand Down

0 comments on commit 3caf02d

Please sign in to comment.