Skip to content

Added policy management cmdlets for Azure Attestation Service #11072

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

Merged
merged 3 commits into from
Feb 10, 2020
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
1 change: 1 addition & 0 deletions src/Attestation/Attestation.Test/Attestation.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Azure.Attestation" Version="0.9.0-preview" />
<PackageReference Include="Microsoft.Azure.Management.Attestation" Version="0.10.0-preview" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Attestation;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Management.Attestation;
using Microsoft.Azure.ServiceManagement.Common.Models;
Expand All @@ -23,6 +23,7 @@
using System.IO;
using System.Linq;
using Microsoft.Azure.Management.Internal.Resources;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;

namespace Microsoft.Azure.Commands.Attestation.Test
Expand All @@ -31,19 +32,13 @@ class AttestationController
{
private readonly EnvironmentSetupHelper _helper;


public ResourceManagementClient ResourceClient { get; private set; }

public AttestationManagementClient AttestationManagementClient { get; private set; }

public static AttestationController NewInstance => new AttestationController();

public AttestationController()
{
_helper = new EnvironmentSetupHelper();
}


public void RunPowerShellTest(XunitTracingInterceptor logger, params string[] scripts)
{
var sf = new StackTrace().GetFrame(1);
Expand All @@ -58,14 +53,37 @@ public void RunPowerShellTest(XunitTracingInterceptor logger, params string[] sc
// no custom cleanup
null,
callingClassType,
mockName);
mockName,
true,
false);
}

public void RunDataPowerShellTest(XunitTracingInterceptor logger, params string[] scripts)
{
var sf = new StackTrace().GetFrame(1);
var callingClassType = sf.GetMethod().ReflectedType?.ToString();
var mockName = sf.GetMethod().Name;

logger.Information(string.Format("Test method entered: {0}.{1}", callingClassType, mockName));
_helper.TracingInterceptor = logger;

RunPowerShellTestWorkflow(
() => scripts,
// no custom cleanup
null,
callingClassType,
mockName,
false,
true);
}

public void RunPowerShellTestWorkflow(
Func<string[]> scriptBuilder,
Action cleanup,
string callingClassType,
string mockName)
string mockName,
bool setupManagementClients,
bool setupDataClient)
{
var providers = new Dictionary<string, string>
{
Expand All @@ -82,8 +100,17 @@ public void RunPowerShellTestWorkflow(
HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");
using (var context = MockContext.Start(callingClassType, mockName))
{
SetupManagementClients(context);
_helper.SetupEnvironment(AzureModule.AzureResourceManager);
if (setupManagementClients)
{
SetupManagementClients(context);
_helper.SetupEnvironment(AzureModule.AzureResourceManager);
}

if (setupDataClient)
{
SetupDataClient(context);
}

var callingClassName =
callingClassType.Split(new[] {"."}, StringSplitOptions.RemoveEmptyEntries).Last();
_helper.SetupModules(AzureModule.AzureResourceManager,
Expand All @@ -109,9 +136,19 @@ public void RunPowerShellTestWorkflow(
}
private void SetupManagementClients(MockContext context)
{
ResourceClient = GetResourceManagementClient(context);
AttestationManagementClient = GetAttestationManagementClient(context);
_helper.SetupManagementClients(ResourceClient, AttestationManagementClient);
_helper.SetupManagementClients(
GetResourceManagementClient(context),
GetAttestationManagementClient(context)
);
}

private void SetupDataClient(MockContext context)
{
_helper.SetupManagementClients(
GetResourceManagementClient(context),
GetAttestationManagementClient(context),
GetAttestationClient(context)
);
}

private static ResourceManagementClient GetResourceManagementClient(MockContext context)
Expand All @@ -123,5 +160,28 @@ private static AttestationManagementClient GetAttestationManagementClient(MockCo
{
return context.GetServiceClient<AttestationManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
}

private static AttestationClient GetAttestationClient(MockContext context)
{
string environmentConnectionString = Environment.GetEnvironmentVariable("TEST_CSM_ORGID_AUTHENTICATION");
string accessToken = "fakefakefake";

// When recording, we should have a connection string passed into the code from the environment
if (!string.IsNullOrEmpty(environmentConnectionString))
{
// Gather test client credential information from the environment
var connectionInfo = new ConnectionString(Environment.GetEnvironmentVariable("TEST_CSM_ORGID_AUTHENTICATION"));
string servicePrincipal = connectionInfo.GetValue<string>(ConnectionStringKeys.ServicePrincipalKey);
string servicePrincipalSecret = connectionInfo.GetValue<string>(ConnectionStringKeys.ServicePrincipalSecretKey);
string aadTenant = connectionInfo.GetValue<string>(ConnectionStringKeys.AADTenantKey);

// Create credentials
var clientCredentials = new ClientCredential(servicePrincipal, servicePrincipalSecret);
var authContext = new AuthenticationContext($"https://login.windows.net/{aadTenant}", TokenCache.DefaultShared);
accessToken = authContext.AcquireTokenAsync("https://attest.azure.net", clientCredentials).Result.AccessToken;
}

return new AttestationClient(new AttestationCredentials(accessToken), HttpMockServer.CreateInstance());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Xunit;

namespace Microsoft.Azure.Commands.Attestation.Test.ScenarioTests
{
public class AttstationPolicyTests : RMTestBase
{
public XunitTracingInterceptor _logger;

public AttstationPolicyTests(Xunit.Abstractions.ITestOutputHelper output)
{
_logger = new XunitTracingInterceptor(output);
XunitTracingInterceptor.AddToContext(_logger);
TestExecutionHelpers.SetUpSessionAndProfile();
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestGetAttestationPolicy()
{
AttestationController.NewInstance.RunDataPowerShellTest(_logger, "Test-GetAttestationPolicy");
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestResetAttestationPolicy()
{
AttestationController.NewInstance.RunDataPowerShellTest(_logger, "Test-ResetAttestationPolicy");
}

/// <summary>
/// This test is categorized as LiveOnly since the Set-AzAttestationPolicy cmdlet retrieves and validates
/// a signed JWT token from the service. A playback of a recording will result in failure, since the
/// recorded JWT will have expired since the recording was generated.
///
/// On a related note, if one does try to create a recording of this test case, currently there's a
/// conflict for the following two libraries used by the authentication code in this DLL
/// (Microsoft.Azure.PowerShell.Cmdlets.Attestation.Test.dll) and the DLL used to implement the
/// PowerShell cmdlets (Microsoft.Azure.PowerShell.Cmdlets.Attestation.dll). This DLL requires
/// version 5.1.2 (indirectly through Microsoft.Rest.ClientRuntime.Azure.TestFramework) and the cmdlet
/// DLL requires version 5.6.0 (indirectly through Microsoft.IdentityModel.JsonWebTokens.
/// * Microsoft.IdentityModel.Tokens.dll
/// * Microsoft.IdentityModel.Logging.dll
///
/// A work-around to record tests is to copy the 5.6.0 versions of the DLL's into the bin directory
/// holding the Microsoft.Azure.PowerShell.Cmdlets.Attestation.Test.dll.
/// </summary>
[Fact]
[Trait(Category.AcceptanceType, Category.LiveOnly)]
public void TestSetAttestationPolicy()
{
AttestationController.NewInstance.RunDataPowerShellTest(_logger, "Test-SetAttestationPolicy");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Test Get-AzAttestationPolicy
#>
#------------------------------Get-AzAttestationPolicy-----------------------------------
function Test-GetAttestationPolicy
{
$unknownRGName = getAssetName
$attestationProviderName = getAssetName
$policyTemplateName = "SgxDisableDebugMode"
$teeType = "SgxEnclave"

try
{
$rgName = Create-ResourceGroup
$attestationCreated = New-AzAttestation -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -AttestationPolicy $policyTemplateName

Assert-NotNull attestationCreated
Assert-AreEqual $attestationProviderName $attestationCreated.Name
Assert-NotNull attestationCreated.AttesUri
Assert-NotNull attestationCreated.Id
Assert-NotNull attestationCreated.Status

$getPolicy = Get-AzAttestationPolicy -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -Tee $teeType
Assert-NotNull $getPolicy
}

finally
{
Clean-ResourceGroup $rgName.ResourceGroupName
}
}

<#
.SYNOPSIS
Test Reset-AzAttestationPolicy
#>
#------------------------------Reset-AzAttestationPolicy-----------------------------------
function Test-ResetAttestationPolicy
{
$unknownRGName = getAssetName
$attestationProviderName = getAssetName
$policyTemplateName = "SgxDisableDebugMode"
$teeType = "SgxEnclave"
try
{
$rgName = Create-ResourceGroup
$attestationCreated = New-AzAttestation -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -AttestationPolicy $policyTemplateName

Assert-NotNull attestationCreated
Assert-AreEqual $attestationProviderName $attestationCreated.Name
Assert-NotNull attestationCreated.AttesUri
Assert-NotNull attestationCreated.Id
Assert-NotNull attestationCreated.Status

$getPolicy = Get-AzAttestationPolicy -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -Tee $teeType
Assert-NotNull $getPolicy
$resetPolicyResponse = Reset-AzAttestationPolicy -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -Tee $teeType -PassThru
Assert-AreEqual $resetPolicyResponse $true
}
finally
{
Clean-ResourceGroup $rgName.ResourceGroupName
}
}

<#
.SYNOPSIS
Test Set-AzAttestationPolicy
#>
#------------------------------Set-AzAttestationPolicy-----------------------------------
# DO NOT RECORD/PLAYBACK THIS TEST, IT WILL FAIL DUE TO AN EXPIRING JWT TOKEN!
#------------------------------Set-AzAttestationPolicy-----------------------------------
function Test-SetAttestationPolicy
{
$unknownRGName = getAssetName
$attestationProviderName = getAssetName
$policyTemplateName = "SgxDisableDebugMode"
$teeType = "SgxEnclave"
$policyDocument = "eyJhbGciOiJub25lIn0.eyJBdHRlc3RhdGlvblBvbGljeSI6ICJ7XHJcbiAgICBcIiR2ZXJzaW9uXCI6IDEsXHJcbiAgICBcIiRhbGxvdy1kZWJ1Z2dhYmxlXCIgOiB0cnVlLFxyXG4gICAgXCIkY2xhaW1zXCI6W1xyXG4gICAgICAgIFwiaXMtZGVidWdnYWJsZVwiICxcclxuICAgICAgICBcInNneC1tcnNpZ25lclwiLFxyXG4gICAgICAgIFwic2d4LW1yZW5jbGF2ZVwiLFxyXG4gICAgICAgIFwicHJvZHVjdC1pZFwiLFxyXG4gICAgICAgIFwic3ZuXCIsXHJcbiAgICAgICAgXCJ0ZWVcIixcclxuICAgICAgICBcIk5vdERlYnVnZ2FibGVcIlxyXG4gICAgXSxcclxuICAgIFwiTm90RGVidWdnYWJsZVwiOiB7XCJ5ZXNcIjp7XCIkaXMtZGVidWdnYWJsZVwiOnRydWUsIFwiJG1hbmRhdG9yeVwiOnRydWUsIFwiJHZpc2libGVcIjpmYWxzZX19LFxyXG4gICAgXCJpcy1kZWJ1Z2dhYmxlXCIgOiBcIiRpcy1kZWJ1Z2dhYmxlXCIsXHJcbiAgICBcInNneC1tcnNpZ25lclwiIDogXCIkc2d4LW1yc2lnbmVyXCIsXHJcbiAgICBcInNneC1tcmVuY2xhdmVcIiA6IFwiJHNneC1tcmVuY2xhdmVcIixcclxuICAgIFwicHJvZHVjdC1pZFwiIDogXCIkcHJvZHVjdC1pZFwiLFxyXG4gICAgXCJzdm5cIiA6IFwiJHN2blwiLFxyXG4gICAgXCJ0ZWVcIiA6IFwiJHRlZVwiXHJcbn0ifQ."

# Prevent this script from inadvertantly running in Record or Playback modes
if (((Get-ChildItem Env:\HttpRecorderMode).Value -eq "Playback") -or ((Get-ChildItem Env:\HttpRecorderMode).Value -eq "Record"))
{
return
}

try
{
$rgName = Create-ResourceGroup
$attestationCreated = New-AzAttestation -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -AttestationPolicy $policyTemplateName

Assert-NotNull attestationCreated
Assert-AreEqual $attestationProviderName $attestationCreated.Name
Assert-NotNull attestationCreated.AttesUri
Assert-NotNull attestationCreated.Id
Assert-NotNull attestationCreated.Status

# NOTE: Set-AzAttestionPolicy does not work in recording/playback mode because the recorded JWT token expires and then fails validation
$setPolicyResponse = Set-AzAttestationPolicy -Name $attestationProviderName -ResourceGroupName $rgName.ResourceGroupName -Tee $teeType -Policy $policyDocument -PassThru
Assert-AreEqual $setPolicyResponse $true
}

finally
{
Clean-ResourceGroup $rgName.ResourceGroupName
}
}
Loading