Skip to content

Added Get-AzureRMTenant [#102955260] #918

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
Sep 16, 2015
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.Azure.Common.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Azure.Commands.ResourceManager.Common
{
public static class AccessTokenExtensions
{
public static string GetDomain(this IAccessToken token)
{
if( token != null && token.UserId !=null && token.UserId.Contains('@'))
{
return token.UserId.Split(
new[] { '@' },
StringSplitOptions.RemoveEmptyEntries).Last();
}

return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@
<Compile Include="..\Commands.Common\TestMockSupport.cs">
<Link>Common\TestMockSupport.cs</Link>
</Compile>
<Compile Include="AccessTokenExtensions.cs" />
<Compile Include="AzureRMCmdlet.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
Expand Down
44 changes: 28 additions & 16 deletions src/Common/Commands.ResourceManager.Common/RMProfileClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,27 +45,23 @@ public RMProfileClient(AzureRMProfile profile)
public AzureRMProfile Login(AzureAccount account, AzureEnvironment environment, string tenantId, string subscriptionId, SecureString password)
{
AzureSubscription newSubscription = null;
AzureTenant newTenant = new AzureTenant();
AzureTenant newTenant = null;
ShowDialog promptBehavior = password == null ? ShowDialog.Always : ShowDialog.Never;

// (tenant and subscription are present) OR
// (tenant is present and subscription is not provided)
if (!string.IsNullOrEmpty(tenantId))
{
if (TryGetTenantSubscription(account, environment, tenantId, subscriptionId, password, promptBehavior, out newSubscription))
{
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
}
TryGetTenantSubscription(account, environment, tenantId, subscriptionId, password, promptBehavior, out newSubscription, out newTenant);
}
// (tenant is not provided and subscription is present) OR
// (tenant is not provided and subscription is not provided)
else
{
foreach(var tenant in ListAccountTenants(account, environment, password, promptBehavior))
{
if (TryGetTenantSubscription(account, environment, tenant, subscriptionId, password, ShowDialog.Auto, out newSubscription))
if (TryGetTenantSubscription(account, environment, tenant.Id.ToString(), subscriptionId, password, ShowDialog.Auto, out newSubscription, out newTenant))
{
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
break;
}
}
Expand All @@ -85,17 +81,16 @@ public AzureRMProfile Login(AzureAccount account, AzureEnvironment environment,
public AzureContext UpdateCurrentContext(string subscriptionId, string tenantId)
{
AzureSubscription newSubscription = null;
AzureTenant newTenant = new AzureTenant();
AzureTenant newTenant = null;
AzureAccount account = _profile.Context.Account;
AzureEnvironment envrionment = _profile.Context.Environment;
ShowDialog promptBehavior = ShowDialog.Auto;

if (!string.IsNullOrWhiteSpace(tenantId) &&
!string.IsNullOrWhiteSpace(subscriptionId))
{
if(TryGetTenantSubscription(account, envrionment, tenantId, subscriptionId, null, promptBehavior, out newSubscription))
if(TryGetTenantSubscription(account, envrionment, tenantId, subscriptionId, null, promptBehavior, out newSubscription, out newTenant))
{
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
_profile.Context = new AzureContext(newSubscription, account, envrionment, newTenant);
}
}
Expand All @@ -110,16 +105,17 @@ public AzureContext UpdateCurrentContext(string subscriptionId, string tenantId)
TokenCache.DefaultShared);

account.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;
newTenant = new AzureTenant();
newTenant.Id = new Guid(accessToken.TenantId);
newTenant.Domain = accessToken.GetDomain();
_profile.Context = new AzureContext(account, envrionment, newTenant);
}
else if(!string.IsNullOrWhiteSpace(subscriptionId))
{
foreach (var tenant in ListAccountTenants(account, envrionment, null, promptBehavior))
{
if (TryGetTenantSubscription(account, envrionment, tenant, subscriptionId, null, promptBehavior, out newSubscription))
if (TryGetTenantSubscription(account, envrionment, tenant.Id.ToString(), subscriptionId, null, promptBehavior, out newSubscription, out newTenant))
{
newTenant.Id = new Guid(account.Properties[AzureAccount.Property.Tenants]);
_profile.Context = new AzureContext(newSubscription, account, envrionment, newTenant);
break;
}
Expand All @@ -135,14 +131,24 @@ public AzureContext UpdateCurrentContext(string subscriptionId, string tenantId)
return _profile.Context;
}

public List<AzureTenant> ListTenants(string tenant)
{
return ListAccountTenants(_profile.Context.Account, _profile.Context.Environment, null, ShowDialog.Auto)
.Where(t => tenant == null ||
tenant.Equals(t.Id.ToString(), StringComparison.OrdinalIgnoreCase) ||
tenant.Equals(t.Domain, StringComparison.OrdinalIgnoreCase))
.ToList();
}

private bool TryGetTenantSubscription(
AzureAccount account,
AzureEnvironment environment,
string tenantId,
string subscriptionId,
SecureString password,
ShowDialog promptBehavior,
out AzureSubscription subscription)
out AzureSubscription subscription,
out AzureTenant tenant)
{
var accessToken = AzureSession.AuthenticationFactory.Authenticate(
account,
Expand All @@ -166,7 +172,7 @@ private bool TryGetTenantSubscription(
else
{
var subscriptions = subscriptionClient.Subscriptions.List().Subscriptions;
if (subscriptions != null)
if (subscriptions != null && subscriptions.Any())
{
if (subscriptions.Count > 1)
{
Expand Down Expand Up @@ -195,15 +201,19 @@ private bool TryGetTenantSubscription(
};

account.Properties[AzureAccount.Property.Tenants] = accessToken.TenantId;
tenant = new AzureTenant();
tenant.Id = new Guid(accessToken.TenantId);
tenant.Domain = accessToken.GetDomain();
return true;
}

subscription = null;
tenant = null;
return false;
}
}

private string[] ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
private List<AzureTenant> ListAccountTenants(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
{
var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(
account,
Expand All @@ -217,7 +227,9 @@ private string[] ListAccountTenants(AzureAccount account, AzureEnvironment envir
new TokenCloudCredentials(commonTenantToken.AccessToken),
environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
{
return subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray();
return subscriptionClient.Tenants.List().TenantIds
.Select(ti => new AzureTenant() { Id = new Guid(ti.TenantId), Domain = commonTenantToken.GetDomain() } )
.ToList();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@
</ItemGroup>
<ItemGroup>
<Compile Include="ContextCmdletTests.Live.cs" />
<Compile Include="TenantCmdletTests.cs" />
<Compile Include="LoginCmdletTests.cs" />
<Compile Include="ContextCmdletTests.Mocked.cs" />
<Compile Include="ProfileCmdletTests.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ public void LoginWithSubscriptionAndTenant()
cmdlt.InvokeEndProcessing();

Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
}

[Fact]
Expand Down Expand Up @@ -90,6 +91,7 @@ public void LoginWithSubscriptionAndNoTenant()
cmdlt.InvokeEndProcessing();

Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
}

[Fact]
Expand All @@ -106,6 +108,7 @@ public void LoginWithNoSubscriptionAndNoTenant()
cmdlt.InvokeEndProcessing();

Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
}

[Fact]
Expand All @@ -123,6 +126,7 @@ public void LoginWithNoSubscriptionAndTenant()
cmdlt.InvokeEndProcessing();

Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
Assert.Equal("microsoft.com", AzureRMCmdlet.DefaultProfile.Context.Tenant.Domain);
}
}
}
119 changes: 119 additions & 0 deletions src/Common/Commands.ResourceManager.Profile.Test/TenantCmdletTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
// ----------------------------------------------------------------------------------
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need to add some mocked tests for this - we can do it using the existing infrastructure, or using Moq infrastructure (I'm checking some in with the subscription cmdlet). Please file a PBI for this and we can take it up afterward.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done #103553984

//
// 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.WindowsAzure.Commands.Utilities.Common;
using Microsoft.Azure.Commands.Profile;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Common.Authentication;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using System.Linq;
using Xunit;
using System;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Hyak.Common;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Profile.Test
{
public class TenantCmdletTests
{
private MemoryDataStore dataStore;
private MockCommandRuntime commandRuntimeMock;

public TenantCmdletTests()
{
dataStore = new MemoryDataStore();
AzureSession.DataStore = dataStore;
commandRuntimeMock = new MockCommandRuntime();
AzureRMCmdlet.DefaultProfile = new AzureRMProfile();
}

[Fact]
[Trait(Category.AcceptanceType, Category.LiveOnly)]
public void GetTenantWithTenantParameter()
{
var cmdlt = new GetAzureRMTenantCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";

// Act
Login("2c224e7e-3ef5-431d-a57b-e71f4662e3a6", null);
cmdlt.InvokeBeginProcessing();
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();

Assert.True(commandRuntimeMock.OutputPipeline.Count == 2);
Assert.Equal("72f988bf-86f1-41af-91ab-2d7cd011db47", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Id.ToString());
Assert.Equal("microsoft.com", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Domain);
}

[Fact]
[Trait(Category.AcceptanceType, Category.LiveOnly)]
public void GetTenantWithDomainParameter()
{
var cmdlt = new GetAzureRMTenantCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Tenant = "microsoft.com";

// Act
Login("2c224e7e-3ef5-431d-a57b-e71f4662e3a6", null);
cmdlt.InvokeBeginProcessing();
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();

Assert.True(commandRuntimeMock.OutputPipeline.Count == 2);
Assert.Equal("72f988bf-86f1-41af-91ab-2d7cd011db47", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Id.ToString());
Assert.Equal("microsoft.com", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Domain);
}

[Fact]
[Trait(Category.AcceptanceType, Category.LiveOnly)]
public void GetTenantWithoutParameters()
{
var cmdlt = new GetAzureRMTenantCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;

// Act
Login("2c224e7e-3ef5-431d-a57b-e71f4662e3a6", null);
cmdlt.InvokeBeginProcessing();
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();

Assert.True(commandRuntimeMock.OutputPipeline.Count == 2);
Assert.Equal("72f988bf-86f1-41af-91ab-2d7cd011db47", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Id.ToString());
Assert.Equal("microsoft.com", ((AzureTenant)commandRuntimeMock.OutputPipeline[1]).Domain);
}

private void Login(string subscriptionId, string tenantId)
{
var cmdlt = new LoginAzureRMAccountCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.SubscriptionId = subscriptionId;
cmdlt.Tenant = tenantId;

// Act
cmdlt.InvokeBeginProcessing();
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();

Assert.NotNull(AzureRMCmdlet.DefaultProfile.Context);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Tenant\GetAzureRMTenant.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Microsoft.Azure.Commands.Profile.format.ps1xml">
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// ----------------------------------------------------------------------------------
//
// 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.ResourceManager.Common;
using Microsoft.Azure.Common.Authentication.Models;
using System.Collections.Generic;
using System.Management.Automation;

namespace Microsoft.Azure.Commands.Profile
{
/// <summary>
/// Cmdlet to get user tenant information.
/// </summary>
[Cmdlet(VerbsCommon.Get, "AzureRMTenant")]
[Alias("Get-AzureRMDomain")]
[OutputType(typeof(List<AzureTenant>))]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this should just be AzureTenant

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the task details - "If no tenant is specified, list all tenants.". So it can be a list.

public class GetAzureRMTenantCommand : AzureRMCmdlet
{
[Parameter(Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)]
[Alias("Domain")]
[ValidateNotNullOrEmpty]
public string Tenant { get; set; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs a parameter attribute - it should be Mandatory=False, ValueFromPipelineByPropertyName = true

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addressed.


protected override void ProcessRecord()
{
var profileClient = new RMProfileClient(AzureRMCmdlet.DefaultProfile);

WriteObject(profileClient.ListTenants(Tenant), enumerateCollection: true);
}
}
}