public void MultipleConcurrentReadsAllowed()
        {
            bool oldMockSupport = TestMockSupport.RunningMocked;

            TestMockSupport.RunningMocked = true;
            try
            {
                MemoryDataStore store         = new MemoryDataStore();
                string          protectedFile = "myFile.txt";
                using (var tempStream = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream)
                    using (var stream1 = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream)
                        using (var stream2 = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream)
                            using (var stream3 = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream)
                                using (var stream4 = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream)
                                {
                                    Assert.NotNull(tempStream);
                                    Assert.NotNull(stream1);
                                    Assert.NotNull(stream2);
                                    Assert.NotNull(stream3);
                                    Assert.NotNull(stream4);
                                    Assert.Throws <UnauthorizedAccessException>(() => ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.ExclusiveWrite, store).Stream);
                                    var stream5 = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream;
                                    stream5.Close();
                                }

                Assert.NotNull(ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.ExclusiveWrite, store).Stream);
            }
            finally
            {
                TestMockSupport.RunningMocked = oldMockSupport;
            }
        }
 public ProtectedProfileProvider()
 {
     using (var fileProvider = ProtectedFileProvider.CreateFileProvider(Path.Combine(AzureSession.Instance.ARMProfileDirectory, AzureSession.Instance.ARMProfileFile)))
     {
         _profile = new AzureRmProfile(fileProvider);
     }
 }
        public void ShouldSerializeAndDeserializeSettings()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));

            GraphEnvironment userDefinedEnv = new GraphEnvironment
            {
                Name            = "TestCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://tester.com",
                GraphEndpoint   = "https://tester.com"
            };

            settings.EnvironmentTable[userDefinedEnv.Name] = userDefinedEnv;

            // Act
            string serializedSettings = settings.ToString();

            settings.TryDeserializeObject(serializedSettings, out GraphSettings deserializedSettings, new GraphSettingsConverter());
            deserializedSettings.TryGetEnvironment(userDefinedEnv.Name, out IGraphEnvironment deserializedEnv);

            // Assert
            Assert.NotNull(deserializedSettings);
            Assert.NotNull(deserializedEnv);
            Assert.Equal(serializedSettings, deserializedSettings.ToString());
            Assert.Equal(userDefinedEnv.GraphEndpoint, deserializedEnv.GraphEndpoint);

            GraphSession.Reset();
        }
 /// <summary>
 /// Saves a stream to a file on disk.
 /// </summary>
 /// <param name="cmdlet">The calling <see cref="PSCmdlet"/>.</param>
 /// <param name="response">The HTTP response from the service.</param>
 /// <param name="inputStream">The stream to write to file.</param>
 /// <param name="filePath">The path to write the file to. This should include the file name and extension.</param>
 /// <param name="cancellationToken">A cancellation token that will be used to cancel the operation by the user.</param>
 internal static void WriteToFile(this PSCmdlet cmdlet, HttpResponseMessage response, Stream inputStream, string filePath, CancellationToken cancellationToken)
 {
     using (var fileProvider = ProtectedFileProvider.CreateFileProvider(filePath, FileProtection.ExclusiveWrite, new DiskDataStore()))
     {
         string downloadUrl = response?.RequestMessage?.RequestUri.ToString();
         cmdlet.WriteToStream(inputStream, fileProvider.Stream, downloadUrl, cancellationToken);
     }
 }
Example #5
0
        /// <summary>
        /// Writes profile to a specified path.
        /// </summary>
        /// <param name="path">File path on disk to save profile to</param>
        public void Save(string path, bool serializeCache = true)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            using (var provider = ProtectedFileProvider.CreateFileProvider(path, FileProtection.ExclusiveWrite))
            {
                Save(provider, serializeCache);
            }
        }
Example #6
0
        /// <summary>
        /// Writes profile to a specified path.
        /// </summary>
        /// <param name="path">File path on disk to save profile to</param>
        public void Save(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            using (var provider = ProtectedFileProvider.CreateFileProvider(path, FileProtection.ExclusiveWrite))
            {
                Save(provider);
            }
        }
        /// <summary>
        /// Get the default profile for the current cmdlet invocation
        /// </summary>
        /// <returns>The default profile, whether it is a process-specific profile, ot a profile for the current user</returns>
        protected virtual IProfileOperations GetDefaultProfile()
        {
            IProfileOperations result = null;
            var currentProfile        = DefaultProfile as AzureRmProfile;

            switch (GetContextModificationScope())
            {
            case ContextModificationScope.Process:
                result = currentProfile;
                break;

            case ContextModificationScope.CurrentUser:
                result = new AzureRmAutosaveProfile(currentProfile, ProtectedFileProvider.CreateFileProvider(Path.Combine(AzureSession.Instance.ARMProfileDirectory, AzureSession.Instance.ARMProfileFile), FileProtection.ExclusiveWrite));
                break;
            }

            return(result);
        }
        public void ShouldLoadSettingsFromConfiguredDataStore()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            string settingsContent = @"{
  ""EnvironmentTable"": {
    ""MyNewCloud"": {
      ""Name"": ""MyNewCloud"",
      ""AzureADEndpoint"": ""https://login.MyNewCloud.com"",
      ""GraphEndpoint"": ""https://graph.MyNewCloud.com"",
      ""Type"": ""User-defined""
    },
    ""TrialCloud"": {
      ""Name"": ""MyNewCloud"",
      ""AzureADEndpoint"": ""https://login.TrialCloud.com"",
      ""GraphEndpoint"": ""https://graph.TrialCloud.com"",
      ""Type"": ""User-defined""
    }
  }
}";

            GraphSession.Instance.DataStore.WriteFile(Constants.SettingFilePath, settingsContent);

            // Act
            // Loads settings from disk store.
            GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));

            settings.TryGetEnvironment("MyNewCloud", out IGraphEnvironment loadedEnvironment);

            // Assert
            Assert.NotNull(loadedEnvironment);
            // 5 built-in + 2 user-defined
            Assert.Equal(7, settings.Environments.Count());
            Assert.Equal("https://login.MyNewCloud.com", loadedEnvironment.AzureADEndpoint);
            Assert.Equal("https://graph.MyNewCloud.com", loadedEnvironment.GraphEndpoint);
            Assert.Equal(GraphEnvironmentConstants.EnvironmentType.UserDefined, loadedEnvironment.Type);

            GraphSession.Reset();
        }
        protected override void BeginProcessing()
        {
            _profile = new AzureRmAutosaveProfile(
                (DefaultProfile as AzureRmProfile),
                ProtectedFileProvider.CreateFileProvider(
                    Path.Combine(AzureSession.Instance.ARMProfileDirectory, AzureSession.Instance.ARMProfileFile),
                    FileProtection.ExclusiveWrite));
            var context = _profile.DefaultContext;

            _cache = AzureSession.Instance.TokenCache;
            if (_profile != null && context != null && context.TokenCache != null)
            {
                _cache = context.TokenCache;
            }

            _environment = AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
                _credential = new PSCredential(UserName, ConvertToSecureString(Password));
            }
            base.BeginProcessing();
        }
        public void WriteAccessIsExclusive()
        {
            bool oldMockSupport = TestMockSupport.RunningMocked;

            TestMockSupport.RunningMocked = true;
            try
            {
                MemoryDataStore store         = new MemoryDataStore();
                string          protectedFile = "myFile.txt";
                using (var tempStream = ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.ExclusiveWrite, store).Stream)
                {
                    Assert.Throws <UnauthorizedAccessException>(() => ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.ExclusiveWrite, store).Stream);
                    Assert.Throws <UnauthorizedAccessException>(() => ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream);
                }

                Assert.NotNull(ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store).Stream);
            }
            finally
            {
                TestMockSupport.RunningMocked = oldMockSupport;
            }
        }
        public void ShouldSaveSettingsToConfiguredDataStore()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));

            GraphEnvironment userDefinedEnv = new GraphEnvironment
            {
                Name            = "TestCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://tester.com",
                GraphEndpoint   = "https://tester.com"
            };
            string expectedSettingsContent = @"{
  ""EnvironmentTable"": {
    ""TestCloud"": {
      ""Name"": ""TestCloud"",
      ""AzureADEndpoint"": ""https://tester.com"",
      ""GraphEndpoint"": ""https://tester.com"",
      ""Type"": ""User-defined""
    }
  }
}";

            // Act
            // Saves settings to disk store.
            settings.TrySetEnvironment(userDefinedEnv, out IGraphEnvironment savedEnvironment);
            string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath).Substring(1).TrimEnd(new[] { '\0' });

            // Assert
            Assert.NotEmpty(settingsContent);
            Assert.Equal(expectedSettingsContent, settingsContent);

            GraphSession.Reset();
        }
        public void ShouldRemoveSettingsFromConfiguredDataStore()
        {
            GraphSession.Initialize(() => new GraphSession());

            // Arrange
            GraphSession.Instance.DataStore = new MockDataStore();
            GraphSettings    settings      = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead));
            GraphEnvironment myNewCloudEnv = new GraphEnvironment
            {
                Name            = "MyNewCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://login.MyNewCloud.com",
                GraphEndpoint   = "https://graph.MyNewCloud.com"
            };
            GraphEnvironment trialCloudEnv = new GraphEnvironment
            {
                Name            = "TrialCloud",
                Type            = GraphEnvironmentConstants.EnvironmentType.UserDefined,
                AzureADEndpoint = "https://login.TrialCloud.com",
                GraphEndpoint   = "https://graph.TrialCloud.com"
            };

            settings.TrySetEnvironment(myNewCloudEnv, out IGraphEnvironment mergedMyNewCloudEnv);
            settings.TrySetEnvironment(trialCloudEnv, out IGraphEnvironment mergedTrialCloudEnv);

            // Act
            settings.RemoveEnvironment(trialCloudEnv.Name);
            string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath);

            // Assert
            Assert.NotEmpty(settingsContent);
            // 5 built-in + 1 user-defined
            Assert.Equal(6, settings.Environments.Count());

            GraphSession.Reset();
        }
Example #13
0
 /// <summary>
 /// Creates a <see cref="GraphSettings"/> with shared read access to the data store.
 /// </summary>
 /// <param name="cmdlet">The calling cmdlet.</param>
 /// <returns>A new instance of <see cref="GraphSettings"/>.</returns>
 internal static GraphSettings GetContextSettings(this PSCmdlet cmdlet)
 {
     return(new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)));
 }
        public void LockFailureThrowsGoodException()
        {
            string            protectedFile = "myFile.txt";
            Mock <IDataStore> store         = new Mock <IDataStore>();

            store.Setup(d => d.FileExists(It.IsAny <string>())).Returns(true);
            store.Setup(d => d.OpenForExclusiveWrite(It.IsAny <string>())).Throws(new IOException("File is in use"));
            store.Setup(d => d.OpenForSharedRead(It.IsAny <string>())).Throws(new IOException("File is in use"));
            bool oldMockSupport = TestMockSupport.RunningMocked;

            TestMockSupport.RunningMocked = true;
            try
            {
                Assert.Contains(protectedFile, Assert.Throws <UnauthorizedAccessException>(() => ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.SharedRead, store.Object).Stream).Message);
                store.Verify(d => d.OpenForSharedRead(It.IsAny <string>()), Times.Exactly(ProtectedFileProvider.MaxTries + 1));
                Assert.Contains(protectedFile, Assert.Throws <UnauthorizedAccessException>(() => ProtectedFileProvider.CreateFileProvider(protectedFile, FileProtection.ExclusiveWrite, store.Object).Stream).Message);
                store.Verify(d => d.OpenForExclusiveWrite(It.IsAny <string>()), Times.Exactly(ProtectedFileProvider.MaxTries + 1));
            }
            finally
            {
                TestMockSupport.RunningMocked = oldMockSupport;
            }
        }
 public void FileProviderThrowsOnInvalidInputs()
 {
     Assert.Throws <ArgumentNullException>(() => ProtectedFileProvider.CreateFileProvider(string.Empty, FileProtection.SharedRead, null));
     Assert.Throws <ArgumentOutOfRangeException>(() => ProtectedFileProvider.CreateFileProvider(string.Empty, FileProtection.SharedRead, new MemoryDataStore()));
 }