public async Task TestSimpleDecryptAndLaunch()
        {
            FakeLauncher launcher = new FakeLauncher();
            bool         called   = false;

            TypeMap.Register.New <ILauncher>(() => { called = true; return(launcher); });

            FileOperationsController controller = new FileOperationsController();

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("a");
                return(Task.FromResult <object>(null));
            };
            FileOperationContext status = await controller.DecryptAndLaunchAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");

            Assert.That(called, Is.True, "There should be a call to launch.");
            Assert.That(Path.GetFileName(launcher.Path), Is.EqualTo("HelloWorld-Key-a.txt"), "The file should be decrypted and the name should be the original from the encrypted headers.");

            IDataStore destinationInfo = New <IDataStore>(launcher.Path);

            Assert.That(destinationInfo.IsAvailable, "After decryption the destination file should be created.");

            string fileContent;

            using (Stream stream = destinationInfo.OpenRead())
            {
                fileContent = new StreamReader(stream).ReadToEnd();
            }

            Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted.");
        }
        public static void TestSimple()
        {
            int workThreadId = -1;
            FileOperationContext returnedStatus = new FileOperationContext(String.Empty, ErrorStatus.UnspecifiedError);

            bool done = false;

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestSimple), new ProgressContext(), false))
            {
                worker.WorkAsync = (ThreadWorkerEventArgs e) =>
                {
                    workThreadId = Thread.CurrentThread.ManagedThreadId;
                    e.Result     = new FileOperationContext(String.Empty, ErrorStatus.Success);
                    return(Task.FromResult <object>(null));
                };
                worker.Completing += (object sender, ThreadWorkerEventArgs e) =>
                {
                    returnedStatus = e.Result;
                    done           = true;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(returnedStatus.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should be returned as successful.");
            Assert.That(workThreadId, Is.Not.EqualTo(Thread.CurrentThread.ManagedThreadId), "The work should not be performed on the caller thread.");
            Assert.That(done, Is.True, "The background work must have executed the completed handler now.");
        }
        public async Task TestEncryptFileThatIsAlreadyEncrypted()
        {
            FileOperationsController controller = new FileOperationsController();
            FileOperationContext     status     = await controller.EncryptFileAsync(New <IDataStore>("test" + OS.Current.AxCryptExtension));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.FileAlreadyEncrypted), "The status should indicate that it was already encrypted.");
        }
        public void TestDecryptFileWithExceptionBeforeStartingDecryption()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("a");
                return(Task.FromResult <object>(null));
            };
            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>((FileOperationEventArgs e) =>
            {
                throw new FileNotFoundException("Just kidding, but we're faking...", e.OpenFileFullName);
            });
            string destinationPath = String.Empty;
            AsyncDelegateAction <FileOperationEventArgs> previous = controller.KnownKeyAdded;

            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>(async(FileOperationEventArgs e) =>
            {
                await previous.ExecuteAsync(e);
                destinationPath = e.SaveFileFullName;
            });
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            Assert.DoesNotThrowAsync(async() => { status = await controller.DecryptFileAsync(New <IDataStore>(_helloWorldAxxPath)); });

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.FileDoesNotExist), "The status should indicate an exception occurred.");
            Assert.That(String.IsNullOrEmpty(destinationPath), "Since an exception occurred, the destination file should not be created.");
        }
Exemple #5
0
        public async Task TestFileContainedByActiveFilesButNotDecrypted()
        {
            IDataStore dataStore = New <IDataStore>(_helloWorldAxxPath);

            TypeMap.Register.New <ILauncher>(() => new FakeLauncher());

            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should succeed.");

            IDataStore fileInfo = New <IDataStore>(_helloWorldAxxPath);
            ActiveFile destinationActiveFile = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(fileInfo.FullName);

            destinationActiveFile.DecryptedFileInfo.Delete();
            destinationActiveFile = new ActiveFile(destinationActiveFile, ActiveFileStatus.NotDecrypted);
            Resolve.FileSystemState.Add(destinationActiveFile);
            await Resolve.FileSystemState.Save();

            status = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should once again succeed.");
        }
        public void TestSimpleWipeOnThreadWorker()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.WipeQueryConfirmation += (object sender, FileOperationEventArgs e) =>
            {
                e.Cancel     = false;
                e.Skip       = false;
                e.ConfirmAll = false;
            };

            string destinationPath      = String.Empty;
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
                status          = e.Status;
            };

            controller.WipeFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));
            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");

            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(!destinationInfo.IsAvailable, "After wiping the destination file should not exist.");
        }
Exemple #7
0
        public async Task TestExitEvent()
        {
            IDataStore dataStore             = New <IDataStore>(_helloWorldAxxPath);
            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            FakeLauncher launcher = new FakeLauncher();
            bool         called   = false;

            TypeMap.Register.New <ILauncher>(() => { called = true; launcher.WasStarted = true; return(launcher); });

            SessionNotify notificationMonitor = new SessionNotify();

            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, notificationMonitor);
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should succeed.");
            Assert.That(called, Is.True, "There should be a call to launch to try launching.");
            Assert.That(Path.GetFileName(launcher.Path), Is.EqualTo("HelloWorld-Key-a.txt"), "The file should be decrypted and the name should be the original from the encrypted headers.");

            bool changedWasRaised = false;

            notificationMonitor.AddCommand((SessionNotification notification) => { changedWasRaised = true; return(Constant.CompletedTask); });
            Assert.That(changedWasRaised, Is.False, "The global changed event should not have been raised yet.");

            launcher.RaiseExited();
            Assert.That(changedWasRaised, Is.True, "The global changed event should be raised when the process exits.");
        }
        public async Task TestWipeWithConfirmAll()
        {
            ProgressContext          progress   = new ProgressContext();
            FileOperationsController controller = new FileOperationsController(progress);
            int confirmationCount = 0;

            controller.WipeQueryConfirmation += (object sender, FileOperationEventArgs e) =>
            {
                if (confirmationCount++ > 0)
                {
                    throw new InvalidOperationException("The event should not be raised a second time.");
                }
                e.ConfirmAll = true;
            };
            progress.NotifyLevelStart();
            FileOperationContext status = await controller.WipeFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The wipe should indicate success.");

            IDataStore fileInfo = New <IDataStore>(_helloWorldAxxPath);

            Assert.That(!fileInfo.IsAvailable, "The file should not exist after wiping.");

            Assert.DoesNotThrowAsync(async() => { status = await controller.WipeFileAsync(New <IDataStore>(_davidCopperfieldTxtPath)); });
            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The wipe should indicate success.");
            progress.NotifyLevelFinished();

            fileInfo = New <IDataStore>(_davidCopperfieldTxtPath);
            Assert.That(!fileInfo.IsAvailable, "The file should not exist after wiping.");
        }
Exemple #9
0
        public async Task TestFileAlreadyDecryptedButWithUnknownKey()
        {
            IDataStore dataStore = New <IDataStore>(_helloWorldAxxPath);

            TypeMap.Register.New <ILauncher>(() => new FakeLauncher());
            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            DateTime utcNow = DateTime.UtcNow;

            ((FakeNow)New <INow>()).TimeFunction = () => { return(utcNow); };
            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should succeed.");

            ActiveFile destinationActiveFile = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(dataStore.FullName);

            Assert.That(destinationActiveFile.DecryptedFileInfo.LastWriteTimeUtc, Is.Not.EqualTo(utcNow), "The decryption should restore the time stamp of the original file, and this is not now.");
            destinationActiveFile.DecryptedFileInfo.SetFileTimes(utcNow, utcNow, utcNow);

            IEnumerable <LogOnIdentity> badKeys = new LogOnIdentity[] { new LogOnIdentity("b") };

            status = await fileOperation.OpenAndLaunchApplication(badKeys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.InvalidKey), "The launch should fail this time, since the key is not known.");
            destinationActiveFile = Resolve.FileSystemState.FindActiveFileFromEncryptedPath(dataStore.FullName);
            Assert.That(destinationActiveFile.DecryptedFileInfo.LastWriteTimeUtc, Is.EqualTo(utcNow), "There should be no decryption, and thus the time stamp should be as just set.");
        }
        public async Task TestSimpleEncryptFile()
        {
            FileOperationsController controller = new FileOperationsController();
            string destinationPath = String.Empty;

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("allan");
            };
            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
            };

            FileOperationContext status = await controller.EncryptFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");

            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After encryption the destination file should be created.");
            using (V2AxCryptDocument document = new V2AxCryptDocument())
            {
                using (Stream stream = destinationInfo.OpenRead())
                {
                    document.Load(new Passphrase("allan"), new V2Aes256CryptoFactory().CryptoId, stream);
                    Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
                }
            }
        }
        public async Task TestDecryptFileWithRepeatedPassphraseQueries()
        {
            FileOperationsController controller = new FileOperationsController();
            int passphraseTry = 0;

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                switch (++passphraseTry)
                {
                case 1:
                    e.LogOnIdentity = new LogOnIdentity("b");
                    break;

                case 2:
                    e.LogOnIdentity = new LogOnIdentity("d");
                    break;

                case 3:
                    e.LogOnIdentity = new LogOnIdentity("a");
                    break;

                case 4:
                    e.LogOnIdentity = new LogOnIdentity("e");
                    break;
                }
                ;
                return(Task.FromResult <object>(null));
            };
            string destinationPath = String.Empty;

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
            };
            bool knownKeyWasAdded = false;

            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>((FileOperationEventArgs e) =>
            {
                knownKeyWasAdded = e.LogOnIdentity.Equals(new LogOnIdentity("a"));
                return(Constant.CompletedTask);
            });
            FileOperationContext status = await controller.DecryptFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");
            Assert.That(knownKeyWasAdded, "A new known key was used, so the KnownKeyAdded event should have been raised.");
            Assert.That(passphraseTry, Is.EqualTo(3), "The third key was the correct one.");
            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After decryption the destination file should be created.");

            string fileContent;

            using (Stream stream = destinationInfo.OpenRead())
            {
                fileContent = new StreamReader(stream).ReadToEnd();
            }
            Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted.");
        }
        private static Task <bool> CheckEncryptionStatus(FileOperationContext foc)
        {
            if (foc.ErrorStatus == ErrorStatus.FileAlreadyEncrypted)
            {
                foc = new FileOperationContext(foc.FullName, ErrorStatus.Success);
            }

            return(Task.FromResult(CheckStatusAndShowMessage(foc, string.Empty)));
        }
Exemple #13
0
        public async Task TestFileDoesNotExist()
        {
            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };
            FileOperation fileOperation      = new FileOperation(Resolve.FileSystemState, new SessionNotify());

            IDataStore           dataStore = New <IDataStore>(_rootPath.PathCombine("Documents", "HelloWorld-NotThere.axx"));
            FileOperationContext status    = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.FileDoesNotExist), "The launch should fail with status FileDoesNotExist.");
        }
Exemple #14
0
        public async Task TestInvalidKey()
        {
            IDataStore dataStore = New <IDataStore>(_helloWorldAxxPath);

            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("b") };
            FileOperation fileOperation      = new FileOperation(Resolve.FileSystemState, new SessionNotify());

            FileOperationContext status = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.InvalidKey), "The key is invalid, so the launch should fail with that status.");
        }
        public async Task TestEncryptFileWhenCanceledDuringQueryPassphrase()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.Cancel = true;
            };

            FileOperationContext status = await controller.EncryptFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Canceled), "The status should indicate cancellation.");
        }
        public async Task TestCanceledDecryptAndLaunch()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                e.Cancel = true;
                return(Task.FromResult <object>(null));
            };
            FileOperationContext status = await controller.DecryptAndLaunchAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Canceled), "The status should indicate cancellation.");
        }
        public async Task TestEncryptFileWhenDestinationExists()
        {
            IDataStore sourceInfo = New <IDataStore>(_davidCopperfieldTxtPath);
            IDataStore expectedDestinationInfo = New <IDataStore>(AxCryptFile.MakeAxCryptFileName(sourceInfo));

            using (Stream stream = expectedDestinationInfo.OpenWrite())
            {
            }

            FileOperationsController controller = new FileOperationsController();
            string        destinationPath       = String.Empty;
            LogOnIdentity logOnIdentity         = null;

            controller.QueryEncryptionPassphrase += (object sender, FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("allan");
            };
            controller.QuerySaveFileAs += (object sender, FileOperationEventArgs e) =>
            {
                e.SaveFileFullName = Path.Combine(Path.GetDirectoryName(e.SaveFileFullName), "alternative-name.axx");
            };
            Guid cryptoId = Guid.Empty;

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
                logOnIdentity   = e.LogOnIdentity;
                cryptoId        = e.CryptoId;
            };

            FileOperationContext status = await controller.EncryptFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");

            Assert.That(Path.GetFileName(destinationPath), Is.EqualTo("alternative-name.axx"), "The alternative name should be used, since the default existed.");
            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After encryption the destination file should be created.");

            EncryptionParameters encryptionParameters = new EncryptionParameters(cryptoId, logOnIdentity);
            await encryptionParameters.AddAsync(logOnIdentity.PublicKeys);

            Headers           headers = new Headers();
            AxCryptReaderBase reader  = headers.CreateReader(new LookAheadStream(destinationInfo.OpenRead()));

            using (IAxCryptDocument document = AxCryptReaderBase.Document(reader))
            {
                document.Load(logOnIdentity.Passphrase, cryptoId, headers);
                Assert.That(document.PassphraseIsValid, "The encrypted document should be valid and encrypted with the passphrase given.");
            }
        }
Exemple #18
0
        /// <summary
        /// Instantiates a worker group with specified maximum concurrency and external progress reporting. Progress
        /// will be reported on the thread instantiating the ProgressContext used.
        /// </summary>
        /// <param name="maxConcurrent">The maximum number of worker threads active at any one time</param>
        /// <param name="progress">The ProgressContext that receives progress notifications</param>
        public WorkerGroup(int maxConcurrent, IProgressContext progress)
        {
            if (progress == null)
            {
                throw new ArgumentNullException("progress");
            }

            _concurrencyControlSemaphore = Resolve.Portable.Semaphore(maxConcurrent, maxConcurrent);
            _maxConcurrencyCount         = maxConcurrent;
            _singleThread = Resolve.Portable.SingleThread();
            FirstError    = new FileOperationContext(String.Empty, ErrorStatus.Success);
            progress.NotifyLevelStart();
            Progress = new WorkerGroupProgressContext(progress, _singleThread);
        }
Exemple #19
0
        public async Task TestWin32Exception()
        {
            IDataStore dataStore             = New <IDataStore>(_helloWorldAxxPath);
            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            SetupAssembly.FakeRuntimeEnvironment.Launcher = ((string path) =>
            {
                throw new Win32Exception("Fake Win32Exception from Unit Test.");
            });

            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.CannotStartApplication), "The launch should fail since the launch throws a Win32Exception.");
        }
        public async Task TestDecryptWithKnownKey()
        {
            FileOperationsController controller = new FileOperationsController();
            await Resolve.KnownIdentities.AddAsync(new LogOnIdentity("b"));

            await Resolve.KnownIdentities.AddAsync(new LogOnIdentity("c"));

            await Resolve.KnownIdentities.AddAsync(new LogOnIdentity("a"));

            await Resolve.KnownIdentities.AddAsync(new LogOnIdentity("e"));

            bool passphraseWasQueried = false;

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                passphraseWasQueried = true;
                return(Task.FromResult <object>(null));
            };
            string destinationPath = String.Empty;

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
            };
            bool knownKeyWasAdded = false;

            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>((FileOperationEventArgs e) =>
            {
                knownKeyWasAdded = true;
                return(Constant.CompletedTask);
            });
            FileOperationContext status = await controller.DecryptFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");
            Assert.That(!knownKeyWasAdded, "An already known key was used, so the KnownKeyAdded event should not have been raised.");
            Assert.That(!passphraseWasQueried, "An already known key was used, so the there should be no need to query for a passphrase.");
            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After decryption the destination file should be created.");

            string fileContent;

            using (Stream stream = destinationInfo.OpenRead())
            {
                fileContent = new StreamReader(stream).ReadToEnd();
            }
            Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted.");
        }
        public async Task TestWipeWithSkip()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.WipeQueryConfirmation += (object sender, FileOperationEventArgs e) =>
            {
                e.Skip = true;
            };
            FileOperationContext status = await controller.WipeFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The wipe should indicate success even when skipping.");

            IDataStore fileInfo = New <IDataStore>(_helloWorldAxxPath);

            Assert.That(fileInfo.IsAvailable, "The file should still exist after wiping that was skipped during confirmation.");
        }
        public async Task TestVerifyEncrypted()
        {
            FileOperationsController controller = new FileOperationsController();
            bool passphraseWasQueried           = false;

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                passphraseWasQueried = true;
                e.Cancel             = true;
                return(Task.FromResult <object>(null));
            };
            bool knownKeyWasAdded = false;

            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>((FileOperationEventArgs e) =>
            {
                knownKeyWasAdded = true;
                return(Constant.CompletedTask);
            });

            FileOperationContext status = await controller.VerifyEncryptedAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Canceled));
            Assert.That(knownKeyWasAdded, Is.False);
            Assert.That(passphraseWasQueried, Is.True);

            controller = new FileOperationsController();
            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("a");
                return(Task.FromResult <object>(null));
            };
            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>((FileOperationEventArgs e) =>
            {
                knownKeyWasAdded = true;
                return(Constant.CompletedTask);
            });

            await Resolve.KnownIdentities.AddAsync(new LogOnIdentity("b"));

            await Resolve.KnownIdentities.AddAsync(new LogOnIdentity("c"));

            status = await controller.VerifyEncryptedAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success));
            Assert.That(knownKeyWasAdded, Is.True, "A known key should have been added.");
        }
Exemple #23
0
        public async Task TestImmediateExit()
        {
            IDataStore dataStore             = New <IDataStore>(_helloWorldAxxPath);
            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            FakeLauncher launcher = new FakeLauncher();
            bool         called   = false;

            TypeMap.Register.New <ILauncher>(() => { called = true; launcher.WasStarted = true; launcher.HasExited = true; return(launcher); });

            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should succeed even if the process exits immediately.");
            Assert.That(called, Is.True, "There should be a call to launch to try launching.");
            Assert.That(Path.GetFileName(launcher.Path), Is.EqualTo("HelloWorld-Key-a.txt"), "The file should be decrypted and the name should be the original from the encrypted headers.");
        }
        public async Task TestSimpleWipe()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.WipeQueryConfirmation += (object sender, FileOperationEventArgs e) =>
            {
                e.Cancel     = false;
                e.Skip       = false;
                e.ConfirmAll = false;
            };
            FileOperationContext status = await controller.WipeFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The wipe should indicate success.");

            IDataStore fileInfo = New <IDataStore>(_helloWorldAxxPath);

            Assert.That(!fileInfo.IsAvailable, "The file should not exist after wiping.");
        }
        public void TestDecryptWithCancelDuringQueryDecryptionPassphraseOnThreadWorker()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                e.Cancel = true;
                return(Task.FromResult <object>(null));
            };
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                status = e.Status;
            };

            controller.DecryptFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Canceled), "The status should indicate cancellation.");
        }
        public static void TestExceptionDuringWork()
        {
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            using (IThreadWorker worker = Resolve.Portable.ThreadWorker(nameof(TestExceptionDuringWork), new ProgressContext(), false))
            {
                worker.WorkAsync = (e) =>
                {
                    throw new InvalidOperationException("Something went intentionally wrong.");
                };
                worker.Completed += (sender, e) =>
                {
                    status = e.Result;
                };
                worker.Run();
                worker.Join();
            }

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Exception));
        }
        public async Task TestEncryptFileWhenCanceledDuringQuerySaveAs()
        {
            IDataStore sourceInfo = New <IDataStore>(_davidCopperfieldTxtPath);
            IDataStore expectedDestinationInfo = New <IDataStore>(AxCryptFile.MakeAxCryptFileName(sourceInfo));

            using (Stream stream = expectedDestinationInfo.OpenWrite())
            {
            }

            FileOperationsController controller = new FileOperationsController();

            controller.QuerySaveFileAs += (object sender, FileOperationEventArgs e) =>
            {
                e.Cancel = true;
            };

            FileOperationContext status = await controller.EncryptFileAsync(New <IDataStore>(_davidCopperfieldTxtPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Canceled), "The status should indicate cancellation.");
        }
        public void TestSimpleDecryptFileOnThreadWorker()
        {
            FileOperationsController controller = new FileOperationsController();

            controller.QueryDecryptionPassphrase = (FileOperationEventArgs e) =>
            {
                e.LogOnIdentity = new LogOnIdentity("a");
                return(Task.FromResult <object>(null));
            };
            bool knownKeyWasAdded = false;

            controller.KnownKeyAdded = new AsyncDelegateAction <FileOperationEventArgs>((FileOperationEventArgs e) =>
            {
                knownKeyWasAdded = e.LogOnIdentity.Equals(new LogOnIdentity("a"));
                return(Constant.CompletedTask);
            });
            string destinationPath      = String.Empty;
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            controller.Completed += (object sender, FileOperationEventArgs e) =>
            {
                destinationPath = e.SaveFileFullName;
                status          = e.Status;
            };

            controller.DecryptFileAsync(New <IDataStore>(_helloWorldAxxPath));

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The status should indicate success.");
            Assert.That(knownKeyWasAdded, "A new known key was used, so the KnownKeyAdded event should have been raised.");
            IDataStore destinationInfo = New <IDataStore>(destinationPath);

            Assert.That(destinationInfo.IsAvailable, "After decryption the destination file should be created.");

            string fileContent;

            using (Stream stream = destinationInfo.OpenRead())
            {
                fileContent = new StreamReader(stream).ReadToEnd();
            }
            Assert.That(fileContent.Contains("Hello"), "A file named Hello World should contain that text when decrypted.");
        }
Exemple #29
0
        public async Task TestSimpleOpenAndLaunch()
        {
            IDataStore dataStore = New <IDataStore>(_helloWorldAxxPath);

            IEnumerable <LogOnIdentity> keys = new LogOnIdentity[] { new LogOnIdentity("a") };

            var mock = new Mock <ILauncher>()
            {
                CallBase = true
            };
            string launcherPath = null;

            mock.Setup(x => x.Launch(It.IsAny <string>())).Callback((string path) => launcherPath = path);
            TypeMap.Register.New <ILauncher>(() => mock.Object);

            FileOperation        fileOperation = new FileOperation(Resolve.FileSystemState, new SessionNotify());
            FileOperationContext status        = await fileOperation.OpenAndLaunchApplication(keys, dataStore, new ProgressContext());

            Assert.That(status.ErrorStatus, Is.EqualTo(ErrorStatus.Success), "The launch should succeed.");
            Assert.DoesNotThrow(() => mock.Verify(x => x.Launch(launcherPath)));
        }
        public async Task WorkAsync(string name, Func <IProgressContext, Task <FileOperationContext> > workAsync, Func <FileOperationContext, Task> completeAsync, IProgressContext progress)
        {
            _name = name;

            Busy = true;
            OnWorkStatusChanged();
            FileOperationContext status = new FileOperationContext(String.Empty, ErrorStatus.Unknown);

            try
            {
                status = await Task.Run(async() => await workAsync(progress).Free());
            }
            catch (OperationCanceledException)
            {
                status = new FileOperationContext(String.Empty, ErrorStatus.Canceled);
            }
            await completeAsync(status);

            Busy = false;
            OnWorkStatusChanged();
        }