public IAccessToken Authenticate(ref AzureAccount account, AzureEnvironment environment, string tenant, SecureString password,
     ShowDialog promptBehavior)
 {
     var token = TokenProvider.GetAccessToken(GetAdalConfiguration(environment, tenant), promptBehavior, account.Id, password, account.Type);
     account.Id = token.UserId;
     return token;
 }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     if (credentialType == AzureAccount.AccountType.User)
     {
         throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
     }
     return new ServicePrincipalAccessToken(config, AcquireToken(config, userId, password), this, userId);
 }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            return TokenProvider(account, environment, tenant);
        }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     switch (credentialType)
     {
         case AzureAccount.AccountType.User:
             return userTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType);
         case AzureAccount.AccountType.ServicePrincipal:
             return servicePrincipalTokenProvider.GetAccessToken(config, promptBehavior, userId, password, credentialType);
         default:
             throw new ArgumentException(Resources.UnknownCredentialType, "credentialType");
     }
 }
        public static void SetCurrentContext(AzureSubscription subscription, AzureEnvironment environment, AzureAccount account)
        {
            if (environment == null)
            {
                if (subscription != null && CurrentContext != null &&
                    subscription.Environment == CurrentContext.Environment.Name)
                {
                    environment = CurrentContext.Environment;
                }
                else
                {
                    environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
                }

                if (subscription != null)
                {
                    subscription.Environment = environment.Name;
                }
            }

            if (account == null)
            {
                if (subscription != null && CurrentContext != null && subscription.Account != null)
                {
                    if (CurrentContext.Account != null && subscription.Account == CurrentContext.Account.Id)
                    {
                        account = CurrentContext.Account;
                    }
                    else
                    {
                        throw new ArgumentException(Resources.AccountIdDoesntMatchSubscription, "account");
                    }

                    subscription.Account = account.Id;

                }
            }

            if (subscription != null && subscription.Environment != environment.Name)
            {
                throw new ArgumentException(Resources.EnvironmentNameDoesntMatchSubscription, "environment");
            }

            CurrentContext = new AzureContext
            {
                Subscription = subscription,
                Account = account,
                Environment = environment
            };
        }
        public IAccessToken Authenticate(AzureAccount account, AzureEnvironment environment, string tenant, SecureString password, ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            var token = new MockAccessToken
            {
                UserId = account.Id,
                LoginType = LoginType.OrgId,
                AccessToken = "123"
            };

            return token;
        }
        public override void ExecuteCmdlet()
        {
            AzureAccount azureAccount = new AzureAccount();

            azureAccount.Type = ServicePrincipal.IsPresent
                ? AzureAccount.AccountType.ServicePrincipal
                : AzureAccount.AccountType.User;
            
            SecureString password = null;
            if (Credential != null)
            {
                azureAccount.Id = Credential.UserName;
                password = Credential.Password;
            }

            if (!string.IsNullOrEmpty(Tenant))
            {
                azureAccount.SetProperty(AzureAccount.Property.Tenants, new[] {Tenant});
            }

            var account = ProfileClient.AddAccountAndLoadSubscriptions(azureAccount, ProfileClient.GetEnvironmentOrDefault(Environment), password);

            if (account != null)
            {
                WriteVerbose(string.Format(Resources.AddAccountAdded, azureAccount.Id));
                if (ProfileClient.Profile.DefaultSubscription != null)
                {
                    WriteVerbose(string.Format(Resources.AddAccountShowDefaultSubscription,
                        ProfileClient.Profile.DefaultSubscription.Name));
                }
                WriteVerbose(Resources.AddAccountViewSubscriptions);
                WriteVerbose(Resources.AddAccountChangeSubscription);

                string subscriptionsList = account.GetProperty(AzureAccount.Property.Subscriptions);
                string tenantsList = account.GetProperty(AzureAccount.Property.Tenants);

                if (subscriptionsList == null)
                {
                    WriteWarning(string.Format(Resources.NoSubscriptionAddedMessage, azureAccount.Id));
                }

                WriteObject(account.ToPSAzureAccount());
            } 
        }
        private void LoadAccountTenants(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            var commonTenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment,
                AuthenticationFactory.CommonAdTenant, password, promptBehavior);

            if (environment.IsEndpointSet(AzureEnvironment.Endpoint.ResourceManager))
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<Azure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                        subscriptionClient.Tenants.List().TenantIds.Select(ti => ti.TenantId).ToArray());
                }
            }
            else
            {
                using (var subscriptionClient = AzureSession.ClientFactory
                        .CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(commonTenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                {
                    var subscriptionListResult = subscriptionClient.Subscriptions.List();
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants,
                        subscriptionListResult.Subscriptions.Select(s => s.ActiveDirectoryTenantId).Distinct().ToArray());
                }
            }
        }
        private IEnumerable<AzureSubscription> ListSubscriptionsFromServer(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            try
            {
                if (!account.IsPropertySet(AzureAccount.Property.Tenants))
                {
                    LoadAccountTenants(ref account, environment, password, promptBehavior);
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }

            try
            {
                List<AzureSubscription> mergedSubscriptions = MergeSubscriptions(
                    ListServiceManagementSubscriptions(ref account, environment, password, ShowDialog.Never).ToList(),
                    ListResourceManagerSubscriptions(ref account, environment, password, ShowDialog.Never).ToList());

                // Set user ID
                foreach (var subscription in mergedSubscriptions)
                {
                    subscription.Environment = environment.Name;
                    subscription.Account = account.Id;
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                }

                if (mergedSubscriptions.Any())
                {
                    return mergedSubscriptions;
                }
                else
                {
                    return new AzureSubscription[0];
                }
            }
            catch (AadAuthenticationException aadEx)
            {
                WriteOrThrowAadExceptionMessage(aadEx);
                return new AzureSubscription[0];
            }
        }
        public List<AzureSubscription> ImportPublishSettings(string filePath, string environmentName)
        {
            var subscriptions = ListSubscriptionsFromPublishSettingsFile(filePath, environmentName);
            if (subscriptions.Any())
            {
                foreach (var subscription in subscriptions)
                {
                    AzureAccount account = new AzureAccount
                    {
                        Id = subscription.Account,
                        Type = AzureAccount.AccountType.Certificate
                    };
                    account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                    AddOrSetAccount(account);
                    subscription.SetOrAppendProperty(AzureSubscription.Property.SupportedModes,
                        AzureModule.AzureServiceManagement.ToString());

                    if (!Profile.Subscriptions.ContainsKey(subscription.Id))
                    {
                        AddOrSetSubscription(subscription);
                    }

                    if (Profile.DefaultSubscription == null)
                    {
                        Profile.DefaultSubscription = subscription;
                    }
                }
            }
            return subscriptions;
        }
        public AzureAccount AddOrSetAccount(AzureAccount account)
        {
            if (account == null)
            {
                throw new ArgumentNullException("Account needs to be specified.", "account");
            }

            if (Profile.Accounts.ContainsKey(account.Id))
            {
                Profile.Accounts[account.Id] =
                    MergeAccountProperties(account, Profile.Accounts[account.Id]);
            }
            else
            {
                Profile.Accounts[account.Id] = account;
            }

            // Update in-memory environment
            if (AzureSession.CurrentContext != null && AzureSession.CurrentContext.Account != null &&
                AzureSession.CurrentContext.Account.Id == account.Id)
            {
                AzureSession.SetCurrentContext(AzureSession.CurrentContext.Subscription,
                    AzureSession.CurrentContext.Environment,
                    Profile.Accounts[account.Id]);
            }

            return Profile.Accounts[account.Id];
        }
        public AzureAccount AddAccountAndLoadSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("environment");
            }

            if (account == null)
            {
                throw new ArgumentNullException("account");
            }

            var subscriptionsFromServer = ListSubscriptionsFromServer(ref account, environment, password, ShowDialog.Always).ToList();

            Debug.Assert(account != null);

            // If account id is null the login failed
            if (account.Id != null)
            {
                // Add the account to the profile
                AddOrSetAccount(account);

                // Update back Profile.Subscriptions
                foreach (var subscription in subscriptionsFromServer)
                {
                    AddOrSetSubscription(subscription);
                }

                if (Profile.DefaultSubscription == null)
                {
                    var firstSubscription = Profile.Subscriptions.Values.FirstOrDefault();
                    if (firstSubscription != null)
                    {
                        SetSubscriptionAsDefault(firstSubscription.Name, firstSubscription.Account);
                    }
                }

                return Profile.Accounts[account.Id];
            }
            else
            {
                return null;
            }
        }
        private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior, string[] tenants)
        {
            List<AzureSubscription> result = new List<AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return result;
            }

            foreach (var tenant in tenants)
            {
                try
                {
                    var tenantAccount = new AzureAccount();
                    CopyAccount(account, tenantAccount);
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(tenantAccount, environment, tenant, password, ShowDialog.Never);
                    if (tenantAccount.Id == account.Id)
                    {
                        tenantAccount = account;
                    }

                    tenantAccount.SetOrAppendProperty(AzureAccount.Property.Tenants, new string[] { tenant });
                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(tenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            // only add the subscription if it's actually in this tenant
                            if (subscription.ActiveDirectoryTenantId == tenant)
                            {
                                AzureSubscription psSubscription = new AzureSubscription
                                {
                                    Id = new Guid(subscription.SubscriptionId),
                                    Name = subscription.SubscriptionName,
                                    Environment = environment.Name
                                };
                                psSubscription.Properties[AzureSubscription.Property.SupportedModes] =
                                    AzureModule.AzureServiceManagement.ToString();
                                psSubscription.SetProperty(AzureSubscription.Property.Tenants,
                                    subscription.ActiveDirectoryTenantId);
                                psSubscription.Account = tenantAccount.Id;
                                tenantAccount.SetOrAppendProperty(AzureAccount.Property.Subscriptions,
                                    new string[] { psSubscription.Id.ToString() });
                                result.Add(psSubscription);
                            }
                        }
                    }

                    AddOrSetAccount(tenantAccount);
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return result;
        }
 private void SetMockData()
 {
     rdfeSubscription1 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub1",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     rdfeSubscription2 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub2",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     csmSubscription1 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub1",
         State = "Active",
         SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription1withDuplicateId = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "RdfeSub1",
         State = "Active",
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription2 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub2",
         State = "Active",
         SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     azureSubscription1 = new AzureSubscription
     {
         Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub1",
         Environment = "Test",
         Account = "test",
         Properties = new Dictionary<AzureSubscription.Property, string>
         {
             { AzureSubscription.Property.Default, "True" } 
         }
     };
     azureSubscription2 = new AzureSubscription
     {
         Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub2",
         Environment = "Test",
         Account = "test"
     };
     azureSubscription3withoutUser = new AzureSubscription
     {
         Id = new Guid("76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub3",
         Environment = "Test",
     };
     azureEnvironment = new AzureEnvironment
     {
         Name = "Test",
         Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
         {
             { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" },
             { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" },
             { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" },
             { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" },
         }
     };
     azureAccount = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties = new Dictionary<AzureAccount.Property, string>
         {
             { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
         }
     };
 }
 private void SetMockData()
 {
     rdfeSubscription1 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub1",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     rdfeSubscription2 = new Subscriptions.Models.SubscriptionListOperationResponse.Subscription
     {
         SubscriptionId = "26E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         SubscriptionName = "RdfeSub2",
         SubscriptionStatus = Subscriptions.Models.SubscriptionStatus.Active,
         ActiveDirectoryTenantId = "Common"
     };
     csmSubscription1 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub1",
         State = "Active",
         SubscriptionId = "36E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription1withDuplicateId = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "RdfeSub1",
         State = "Active",
         SubscriptionId = "16E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     csmSubscription2 = new Azure.Subscriptions.Models.Subscription
     {
         Id = "Subscriptions/46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E",
         DisplayName = "CsmSub2",
         State = "Active",
         SubscriptionId = "46E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"
     };
     azureSubscription1 = new AzureSubscription
     {
         Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub1",
         Environment = "Test",
         Account = "test",
         Properties = new Dictionary<AzureSubscription.Property, string>
         {
             { AzureSubscription.Property.Default, "True" } 
         }
     };
     azureSubscription2 = new AzureSubscription
     {
         Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub2",
         Environment = "Test",
         Account = "test"
     };
     azureSubscription3withoutUser = new AzureSubscription
     {
         Id = new Guid("76E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub3",
         Environment = "Test",
     };
     azureEnvironment = new AzureEnvironment
     {
         Name = "Test",
         Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
         {
             { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" },
             { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" },
             { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" },
             { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" },
         }
     };
     azureAccount = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties = new Dictionary<AzureAccount.Property, string>
         {
             { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
         }
     };
     newProfileDataPath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory, AzurePowerShell.ProfileFile);
     oldProfileDataPath = System.IO.Path.Combine(AzurePowerShell.ProfileDirectory, AzurePowerShell.OldProfileFile);
     oldProfileData = @"<?xml version=""1.0"" encoding=""utf-8""?>
         <ProfileData xmlns:i=""http://www.w3.org/2001/XMLSchema-instance"" xmlns=""http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.Commands.Utilities.Common"">
           <DefaultEnvironmentName>AzureCloud</DefaultEnvironmentName>
           <Environments>
             <AzureEnvironmentData>
               <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
               <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
               <CommonTenantId>Common</CommonTenantId>
               <GalleryEndpoint>https://current.gallery.azure-test.net</GalleryEndpoint>
               <ManagementPortalUrl>http://go.microsoft.com/fwlink/?LinkId=254433</ManagementPortalUrl>
               <Name>Current</Name>
               <PublishSettingsFileUrl>d:\Code\azure.publishsettings</PublishSettingsFileUrl>
               <ResourceManagerEndpoint>https://api-current.resources.windows-int.net/</ResourceManagerEndpoint>
               <ServiceEndpoint>https://umapi.rdfetest.dnsdemo4.com:8443/</ServiceEndpoint>
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <StorageEndpointSuffix i:nil=""true"" />
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureEnvironmentData>
             <AzureEnvironmentData>
               <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
               <AdTenantUrl>https://login.windows-ppe.net/</AdTenantUrl>
               <CommonTenantId>Common</CommonTenantId>
               <GalleryEndpoint>https://df.gallery.azure-test.net</GalleryEndpoint>
               <ManagementPortalUrl>https://windows.azure-test.net</ManagementPortalUrl>
               <Name>Dogfood</Name>
               <PublishSettingsFileUrl>https://auxnext.windows.azure-test.net/publishsettings/index</PublishSettingsFileUrl>
               <ResourceManagerEndpoint>https://api-dogfood.resources.windows-int.net</ResourceManagerEndpoint>
               <ServiceEndpoint>https://management-preview.core.windows-int.net/</ServiceEndpoint>
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <StorageEndpointSuffix i:nil=""true"" />
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureEnvironmentData>
           </Environments>
           <Subscriptions>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint i:nil=""true"" />
               <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
               <ActiveDirectoryTenantId i:nil=""true"" />
               <ActiveDirectoryUserId i:nil=""true"" />
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>true</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate i:nil=""true""/>
               <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
               <Name>Test</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint i:nil=""true"" />
               <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
               <ActiveDirectoryTenantId>123</ActiveDirectoryTenantId>
               <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>true</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate i:nil=""true""/>
               <ManagementEndpoint>https://management-preview.core.windows-int.net/</ManagementEndpoint>
               <Name>Test 2</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>06E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1F</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint>https://login.windows.net/</ActiveDirectoryEndpoint>
               <ActiveDirectoryServiceEndpointResourceId>https://management.core.windows.net/</ActiveDirectoryServiceEndpointResourceId>
               <ActiveDirectoryTenantId>72f988bf-86f1-41af-91ab-2d7cd011db47</ActiveDirectoryTenantId>
               <ActiveDirectoryUserId>[email protected]</ActiveDirectoryUserId>
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>false</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate>
               <ManagementEndpoint>https://management.core.windows.net/</ManagementEndpoint>
               <Name>Test 3</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>d1e52cbc-b073-42e2-a0a0-c2f547118a6f</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
             <AzureSubscriptionData>
               <ActiveDirectoryEndpoint i:nil=""true"" />
               <ActiveDirectoryServiceEndpointResourceId i:nil=""true"" />
               <ActiveDirectoryTenantId i:nil=""true"" />
               <ActiveDirectoryUserId i:nil=""true"" />
               <CloudStorageAccount i:nil=""true"" />
               <GalleryEndpoint i:nil=""true"" />
               <IsDefault>false</IsDefault>
               <LoginType i:nil=""true"" />
               <ManagementCertificate>3AF24D48B97730E5C4C9CCB12397B5E046F79E09</ManagementCertificate>
               <ManagementEndpoint>https://management.core.chinacloudapi.cn/</ManagementEndpoint>
               <Name>Mooncake Test</Name>
               <RegisteredResourceProviders xmlns:d4p1=""http://schemas.microsoft.com/2003/10/Serialization/Arrays"" />
               <ResourceManagerEndpoint i:nil=""true"" />
               <SqlDatabaseDnsSuffix>.database.windows.net</SqlDatabaseDnsSuffix>
               <SubscriptionId>c14d7dc5-ed4d-4346-a02f-9f1bcf78fb66</SubscriptionId>
               <TrafficManagerDnsSuffix>trafficmanager.net</TrafficManagerDnsSuffix>
             </AzureSubscriptionData>
           </Subscriptions>
         </ProfileData>";
 }
        private AzureAccount MergeAccountProperties(AzureAccount account1, AzureAccount account2)
        {
            if (account1 == null || account2 == null)
            {
                throw new ArgumentNullException("account1");
            }
            if (account1.Id != account2.Id)
            {
                throw new ArgumentException("Account1 Ids do not match.");
            }
            if (account1.Type != account2.Type)
            {
                throw new ArgumentException("Account1 types do not match.");
            }
            AzureAccount mergeAccount = new AzureAccount
            {
                Id = account1.Id,
                Type = account1.Type
            };

            // Merge all properties
            foreach (AzureAccount.Property property in Enum.GetValues(typeof(AzureAccount.Property)))
            {
                string propertyValue = account1.GetProperty(property) ?? account2.GetProperty(property);
                if (propertyValue != null)
                {
                    mergeAccount.Properties[property] = propertyValue;
                }
            }

            // Merge Tenants
            var tenants = account1.GetPropertyAsArray(AzureAccount.Property.Tenants)
                    .Union(account2.GetPropertyAsArray(AzureAccount.Property.Tenants), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Tenants, tenants.ToArray());

            // Merge Subscriptions
            var subscriptions = account1.GetPropertyAsArray(AzureAccount.Property.Subscriptions)
                    .Union(account2.GetPropertyAsArray(AzureAccount.Property.Subscriptions), StringComparer.CurrentCultureIgnoreCase);

            mergeAccount.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.ToArray());

            return mergeAccount;
        }
 private void SetMockData()
 {
     azureSubscription1 = new AzureSubscription
     {
         Id = new Guid("56E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub1",
         Environment = "Test",
         Account = "test",
         Properties = new Dictionary<AzureSubscription.Property, string>
         {
             { AzureSubscription.Property.Default, "True" } 
         }
     };
     azureSubscription2 = new AzureSubscription
     {
         Id = new Guid("66E3F6FD-A3AA-439A-8FC4-1F5C41D2AD1E"),
         Name = "LocalSub2",
         Environment = "Test",
         Account = "test"
     };
     azureEnvironment = new AzureEnvironment
     {
         Name = "Test",
         Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
         {
             { AzureEnvironment.Endpoint.ServiceManagement, "https://umapi.rdfetest.dnsdemo4.com:8443/" },
             { AzureEnvironment.Endpoint.ManagementPortalUrl, "https://windows.azure-test.net" },
             { AzureEnvironment.Endpoint.AdTenant, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.ActiveDirectory, "https://login.windows-ppe.net/" },
             { AzureEnvironment.Endpoint.Gallery, "https://current.gallery.azure-test.net" },
             { AzureEnvironment.Endpoint.ResourceManager, "https://api-current.resources.windows-int.net/" },
         }
     };
     azureAccount = new AzureAccount
     {
         Id = "test",
         Type = AzureAccount.AccountType.User,
         Properties = new Dictionary<AzureAccount.Property, string>
         {
             { AzureAccount.Property.Subscriptions, azureSubscription1.Id + "," + azureSubscription2.Id } 
         }
     };
 }
 public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
     AzureAccount.AccountType credentialType)
 {
     return this.accessToken;
 }
Example #19
0
        public IEnumerable<AzureAccount> ToAzureAccounts()
        {
            if (!string.IsNullOrEmpty(ActiveDirectoryUserId))
            {
                AzureAccount userAccount = new AzureAccount
                {
                    Id = ActiveDirectoryUserId,
                    Type = AzureAccount.AccountType.User
                };

                userAccount.SetProperty(AzureAccount.Property.Subscriptions, new Guid(this.SubscriptionId).ToString());
                
                if (!string.IsNullOrEmpty(ActiveDirectoryTenantId))
                {
                    userAccount.SetProperty(AzureAccount.Property.Tenants, ActiveDirectoryTenantId);
                }

                yield return userAccount;
            }

            if (!string.IsNullOrEmpty(ManagementCertificate))
            {
                AzureAccount certificateAccount = new AzureAccount
                {
                    Id = ManagementCertificate,
                    Type = AzureAccount.AccountType.Certificate
                };

                certificateAccount.SetProperty(AzureAccount.Property.Subscriptions, new Guid(this.SubscriptionId).ToString());

                yield return certificateAccount;
            }
        }
        private IEnumerable<AzureSubscription> ListServiceManagementSubscriptions(ref AzureAccount account, AzureEnvironment environment, SecureString password, ShowDialog promptBehavior)
        {
            List<AzureSubscription> result = new List<AzureSubscription>();

            if (!environment.IsEndpointSet(AzureEnvironment.Endpoint.ServiceManagement))
            {
                return result;
            }

            foreach (var tenant in account.GetPropertyAsArray(AzureAccount.Property.Tenants))
            {
                try
                {
                    var tenantToken = AzureSession.AuthenticationFactory.Authenticate(ref account, environment, tenant, password, ShowDialog.Never);

                    using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<WindowsAzure.Subscriptions.SubscriptionClient>(
                            new TokenCloudCredentials(tenantToken.AccessToken),
                            environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ServiceManagement)))
                    {
                        var subscriptionListResult = subscriptionClient.Subscriptions.List();
                        foreach (var subscription in subscriptionListResult.Subscriptions)
                        {
                            AzureSubscription psSubscription = new AzureSubscription
                            {
                                Id = new Guid(subscription.SubscriptionId),
                                Name = subscription.SubscriptionName,
                                Environment = environment.Name
                            };
                            psSubscription.Properties[AzureSubscription.Property.SupportedModes] = AzureModule.AzureServiceManagement.ToString();
                            psSubscription.SetProperty(AzureSubscription.Property.Tenants, subscription.ActiveDirectoryTenantId);

                            AzureSession.SubscriptionTokenCache[Tuple.Create(psSubscription.Id, account.Id)] = tenantToken;

                            result.Add(psSubscription);
                        }
                    }
                }
                catch (CloudException cEx)
                {
                    WriteOrThrowAadExceptionMessage(cEx);
                }
                catch (AadAuthenticationException aadEx)
                {
                    WriteOrThrowAadExceptionMessage(aadEx);
                }
            }

            return result;
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            string jwtToken;

            if (mode == AzureModule.AzureResourceManager)
            {
                jwtToken = csmEnvironment.Credentials != null ?
                ((TokenCloudCredentials)csmEnvironment.Credentials).Token : null;
            }
            else if (mode == AzureModule.AzureServiceManagement)
            {
                jwtToken = rdfeEnvironment.Credentials != null ?
                ((TokenCloudCredentials)rdfeEnvironment.Credentials).Token : null;
            }
            else
            {
                throw new ArgumentException("Invalid module mode.");
            }

            SetEndpointsToDefaults(rdfeEnvironment, csmEnvironment);

            /*
                WindowsAzureProfile.Instance.TokenProvider = new FakeAccessTokenProvider(
                jwtToken,
                csmEnvironment.UserName,
                csmEnvironment.AuthorizationContext == null ? null : csmEnvironment.AuthorizationContext.TenatId);
            */
            if (HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback)
            {
                AzureSession.AuthenticationFactory = new MockAuthenticationFactory();
            }
            else
            {
                AzureSession.AuthenticationFactory = new MockAuthenticationFactory(currentEnvironment.UserName, jwtToken);
            }

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;                
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;                
            }

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            testSubscription = new AzureSubscription()
            {
                Id = new Guid(currentEnvironment.SubscriptionId),
                Name = testSubscriptionName,
                Environment = testEnvironmentName,
                Account = currentEnvironment.UserName,
                Properties = new Dictionary<AzureSubscription.Property,string> 
                {
                     { AzureSubscription.Property.Default, "True"},
                     { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")},
                }
            };

            testAccount = new AzureAccount()
            {
                Id = currentEnvironment.UserName,
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string> 
                {
                     { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                }
            };

            client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
            client.Profile.Accounts[testAccount.Id] = testAccount;
            client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
        }
        /// <summary>
        /// Executes the set subscription cmdlet operation.
        /// </summary>
        public override void ExecuteCmdlet()
        {
            AzureSubscription subscription = null;

            if (!string.IsNullOrEmpty(SubscriptionId) && string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(new Guid(SubscriptionId));
                Environment = subscription.Environment;
            }
            else if (string.IsNullOrEmpty(SubscriptionId) && !string.IsNullOrEmpty(SubscriptionName))
            {
                subscription = ProfileClient.GetSubscription(SubscriptionName);
                Environment = subscription.Environment;
            }
            else
            {
                subscription = new AzureSubscription();
                subscription.Id = new Guid(SubscriptionId);
                subscription.Name = SubscriptionName;
            }

            AzureEnvironment environment = ProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            if (environment == null)
            {
                environment = DefaultProfileClient.GetEnvironment(Environment, ServiceEndpoint, ResourceManagerEndpoint);
            }

            if (environment == null)
            {
                throw new ArgumentException("ServiceEndpoint and ResourceManagerEndpoint values do not "+
                    "match existing environment. Please use Environment parameter.");
            }
            else
            {
                subscription.Environment = environment.Name;
            }

            if (ServiceEndpoint != null || ResourceManagerEndpoint != null)
            {
                WriteWarning("Please use Environment parameter to specify subscription environment. This "+
                    "warning will be converted into an error in the upcoming release.");
            }

            if (Certificate != null)
            {
                ProfileClient.ImportCertificate(Certificate);
                subscription.Account = Certificate.Thumbprint;
                AzureAccount account = new AzureAccount
                {
                    Id = Certificate.Thumbprint,
                    Type = AzureAccount.AccountType.Certificate
                };
                account.SetOrAppendProperty(AzureAccount.Property.Subscriptions, subscription.Id.ToString());
                ProfileClient.AddOrSetAccount(account);

                if (subscription.Account == null)
                {
                    subscription.Account = account.Id;
                }
            }

            if (subscription.Account == null)
            {
                throw new ArgumentException("Certificate is required for creating a new subscription.");
            }

            if (!string.IsNullOrEmpty(CurrentStorageAccountName))
            {
                subscription.Properties[AzureSubscription.Property.StorageAccount] = CurrentStorageAccountName;
            }

            subscription = ProfileClient.AddOrSetSubscription(subscription);

            if (PassThru)
            {
                WriteObject(subscription);
            }
        }
        private void SetupAzureEnvironmentFromEnvironmentVariables(AzureModule mode)
        {
            TestEnvironment rdfeEnvironment = new RDFETestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment csmEnvironment = new CSMTestEnvironmentFactory().GetTestEnvironment();
            TestEnvironment currentEnvironment = (mode == AzureModule.AzureResourceManager ? csmEnvironment : rdfeEnvironment);

            if (currentEnvironment.UserName == null)
            {
                currentEnvironment.UserName = "******";
            }

            SetEndpointsToDefaults(rdfeEnvironment, csmEnvironment);

            SetAuthenticationFactory(mode, rdfeEnvironment, csmEnvironment);

            AzureEnvironment environment = new AzureEnvironment { Name = testEnvironmentName };

            Debug.Assert(currentEnvironment != null);
            environment.Endpoints[AzureEnvironment.Endpoint.ActiveDirectory] = currentEnvironment.ActiveDirectoryEndpoint.AbsoluteUri;
            environment.Endpoints[AzureEnvironment.Endpoint.Gallery] = currentEnvironment.GalleryUri.AbsoluteUri;

            if (csmEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ResourceManager] = csmEnvironment.BaseUri.AbsoluteUri;                
            }

            if (rdfeEnvironment != null)
            {
                environment.Endpoints[AzureEnvironment.Endpoint.ServiceManagement] = rdfeEnvironment.BaseUri.AbsoluteUri;                
            }

            if (!client.Profile.Environments.ContainsKey(testEnvironmentName))
            {
                client.AddOrSetEnvironment(environment);
            }

            testSubscription = new AzureSubscription()
            {
                Id = new Guid(currentEnvironment.SubscriptionId),
                Name = testSubscriptionName,
                Environment = testEnvironmentName,
                Account = currentEnvironment.UserName,
                Properties = new Dictionary<AzureSubscription.Property,string> 
                {
                     { AzureSubscription.Property.Default, "True"},
                     { AzureSubscription.Property.StorageAccount, Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT")},
                }
            };

            testAccount = new AzureAccount()
            {
                Id = currentEnvironment.UserName,
                Type = AzureAccount.AccountType.User,
                Properties = new Dictionary<AzureAccount.Property, string> 
                {
                     { AzureAccount.Property.Subscriptions, currentEnvironment.SubscriptionId},
                }
            };

            client.Profile.Subscriptions[testSubscription.Id] = testSubscription;
            client.Profile.Accounts[testAccount.Id] = testAccount;
            client.SetSubscriptionAsCurrent(testSubscription.Name, testSubscription.Account);
        }
        /// <summary>
        /// Common helper method for other tests to create a unit test subscription
        /// that connects to the mock server.
        /// </summary>
        /// <param name="powershell">The powershell instance used for the test.</param>
        public static AzureSubscription SetupUnitTestSubscription(System.Management.Automation.PowerShell powershell)
        {
            UnitTestHelper.ImportAzureModule(powershell);

            // Set the client certificate used in the subscription
            powershell.Runspace.SessionStateProxy.SetVariable(
                "clientCertificate",
                UnitTestHelper.GetUnitTestClientCertificate());

            ProfileClient client = new ProfileClient();
            client.Profile.Environments[UnitTestEnvironmentName] = new AzureEnvironment
                {
                    Name = UnitTestEnvironmentName,
                    Endpoints = new Dictionary<AzureEnvironment.Endpoint, string>
                    {
                        {AzureEnvironment.Endpoint.ServiceManagement, MockHttpServer.DefaultHttpsServerPrefixUri.AbsoluteUri},
                        {AzureEnvironment.Endpoint.SqlDatabaseDnsSuffix, ".database.windows.net"}
                    }
                };
            
            var account = new AzureAccount
            {
                Id = UnitTestHelper.GetUnitTestClientCertificate().Thumbprint,
                Type = AzureAccount.AccountType.Certificate
            };

            var subscription = new AzureSubscription
            {
                Id = new Guid(UnitTestSubscriptionId),
                Name = UnitTestSubscriptionName,
                Environment = UnitTestEnvironmentName,
                Account = account.Id
            };

            client.AddOrSetAccount(account);
            client.AddOrSetSubscription(subscription);
            client.SetSubscriptionAsCurrent(UnitTestSubscriptionName, account.Id);
            client.Profile.Save();
            
            return subscription;
        }
 private void CopyAccount(AzureAccount sourceAccount, AzureAccount targetAccount)
 {
     targetAccount.Id = sourceAccount.Id;
     targetAccount.Type = sourceAccount.Type;
 }