Beispiel #1
0
    protected async Task LoadSecretsIfNecessaryAsync()
    {
        if (SecretEncrypterFunction != null)
        {
            return;
        }

        var encrypterSecret = new SecretStringEncrypterFunction();
        var errorsAndInfos  = new ErrorsAndInfos();
        var csLambda        = await SecretRepository.GetAsync(encrypterSecret, errorsAndInfos);

        SecretEncrypterFunction = await SecretRepository.CompileCsLambdaAsync <string, string>(csLambda);

        var decrypterSecret = new SecretStringDecrypterFunction();

        csLambda = await SecretRepository.GetAsync(decrypterSecret, errorsAndInfos);

        SecretDecrypterFunction = await SecretRepository.CompileCsLambdaAsync <string, string>(csLambda);

        if (!errorsAndInfos.AnyErrors())
        {
            return;
        }

        throw new Exception(errorsAndInfos.ErrorsToString());
    }
Beispiel #2
0
    private async Task FindReplacementsIfNecessaryAsync()
    {
        if (Replacements.Any())
        {
            return;
        }

        var errorsAndInfos      = new ErrorsAndInfos();
        var machineDrivesSecret = new MachineDrivesSecret();
        var machineDrives       = await SecretRepository.GetAsync(machineDrivesSecret, errorsAndInfos);

        if (errorsAndInfos.AnyErrors())
        {
            throw new Exception(errorsAndInfos.ErrorsToString());
        }
        machineDrives.DrivesOnThisMachine().ToList().ForEach(AddReplacement);

        var logicalFoldersSecret = new LogicalFoldersSecret();
        var logicalFolders       = await SecretRepository.GetAsync(logicalFoldersSecret, errorsAndInfos);

        if (errorsAndInfos.AnyErrors())
        {
            throw new Exception(errorsAndInfos.ErrorsToString());
        }
        logicalFolders.ForEach(AddReplacement);

        var keys = Replacements.Keys.ToList();

        foreach (var key in keys)
        {
            Replacements[key] = ResolveIterative(Replacements[key]).FullName;
        }
    }
Beispiel #3
0
        private async Task <PersonalAccessTokens> GetPersonalAccessTokensAsync(IErrorsAndInfos errorsAndInfos)
        {
            var personalAccessTokensSecret = new PersonalAccessTokensSecret();
            var personalAccessTokens       = await vSecretRepository.GetAsync(personalAccessTokensSecret, errorsAndInfos);

            return(personalAccessTokens);
        }
Beispiel #4
0
        public async Task <IActionResult> GetSecretAsync([FromRoute] string id, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (!Guid.TryParse(id, out var guid) || guid.Equals(Guid.Empty))
            {
                var error = ErrorResponsesService.NotFoundError(Target, $"Secret with id '{id}' not found.");
                return(NotFound(error));
            }

            Model.Secret modelSecret;

            try
            {
                modelSecret = await repository.GetAsync(guid, cancellationToken).ConfigureAwait(false);
            }
            catch (SecretNotFoundException ex)
            {
                var error = ErrorResponsesService.NotFoundError(Target, ex.Message);
                return(NotFound(error));
            }

            var clientSecret = Converter.SecretConverter.Convert(modelSecret);

            return(Ok(clientSecret));
        }
Beispiel #5
0
    private static async Task <ShouldDefaultSecretsBeStored> ShouldDefaultSecretsBeStoredAsync(ISecretRepository sut, IErrorsAndInfos errorsAndInfos)
    {
        var secret = new SecretShouldDefaultSecretsBeStored();
        var shouldDefaultSecretsBeStored = await sut.GetAsync(secret, errorsAndInfos);

        Assert.IsNotNull(shouldDefaultSecretsBeStored);
        return(shouldDefaultSecretsBeStored);
    }
        public async Task <IEnumerable <BackbendFolderToBeArchived> > AnalyzeAsync(IErrorsAndInfos errorsAndInfos)
        {
            var result          = new List <BackbendFolderToBeArchived>();
            var backbendFolders = await SecretRepository.GetAsync(new BackbendFoldersSecret(), errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                return(result);
            }
            await backbendFolders.ResolveAsync(FolderResolver, errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                return(result);
            }
            var archiveFolderFinderSecret = await SecretRepository.GetAsync(new ArchiveFolderFinderSecret(), errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                return(result);
            }

            var archiveFolderFinder = await SecretRepository.CompileCsLambdaAsync <string, string>(archiveFolderFinderSecret);

            if (archiveFolderFinder == null)
            {
                errorsAndInfos.Errors.Add(Properties.Resources.CouldNotCompileFolderFinder);
                return(result);
            }

            foreach (var backbendFolder in backbendFolders)
            {
                AnalyzeFolderAsync(backbendFolder, archiveFolderFinder, result);
                foreach (var subFolder in Directory.GetDirectories(backbendFolder.GetFolder().FullName).Select(f => new BackbendFolder {
                    Name = f
                }))
                {
                    subFolder.SetFolder(new Folder(subFolder.Name));
                    AnalyzeFolderAsync(subFolder, archiveFolderFinder, result);
                }
            }

            return(result);
        }
        private async Task <bool> UpdateNugetPackagesForProjectAsync(string projectFileFullName, bool yesNo, IErrorsAndInfos errorsAndInfos)
        {
            using (SimpleLogger.BeginScope(SimpleLoggingScopeId.Create(nameof(UpdateNugetPackagesForProjectAsync), Guid.NewGuid().ToString()))) {
                SimpleLogger.LogInformation("Retrieving dependency ids and versions");
                var dependencyErrorsAndInfos = new ErrorsAndInfos();
                var dependencyIdsAndVersions =
                    await PackageConfigsScanner.DependencyIdsAndVersionsAsync(projectFileFullName.Substring(0, projectFileFullName.LastIndexOf('\\')), true, true, dependencyErrorsAndInfos);

                SimpleLogger.LogInformation("Retrieving manually updated packages");
                var secret = new SecretManuallyUpdatedPackages();
                var manuallyUpdatedPackages = await SecretRepository.GetAsync(secret, errorsAndInfos);

                if (errorsAndInfos.AnyErrors())
                {
                    SimpleLogger.LogInformation("Returning false");
                    return(false);
                }

                foreach (var id in dependencyIdsAndVersions.Select(dependencyIdsAndVersion => dependencyIdsAndVersion.Key).Where(id => manuallyUpdatedPackages.All(p => p.Id != id)))
                {
                    SimpleLogger.LogInformation($"Updating dependency {id}");
                    var projectFileFolder = new Folder(projectFileFullName.Substring(0, projectFileFullName.LastIndexOf('\\')));
                    ProcessRunner.RunProcess("dotnet", "remove " + projectFileFullName + " package " + id, projectFileFolder, errorsAndInfos);
                    ProcessRunner.RunProcess("dotnet", "add " + projectFileFullName + " package " + id, projectFileFolder, errorsAndInfos);
                }

                SimpleLogger.LogInformation("Retrieving dependency ids and versions once more");
                var dependencyIdsAndVersionsAfterUpdate =
                    await PackageConfigsScanner.DependencyIdsAndVersionsAsync(projectFileFullName.Substring(0, projectFileFullName.LastIndexOf('\\')), true, true, dependencyErrorsAndInfos);

                SimpleLogger.LogInformation("Determining differences");
                foreach (var dependencyIdsAndVersion in dependencyIdsAndVersionsAfterUpdate)
                {
                    var id      = dependencyIdsAndVersion.Key;
                    var version = dependencyIdsAndVersion.Value;
                    yesNo = yesNo || !dependencyIdsAndVersions.ContainsKey(id) || version != dependencyIdsAndVersions[id];
                }

                SimpleLogger.LogInformation($"Returning {yesNo}");
                return(yesNo);
            }
        }
Beispiel #8
0
        private async Task <IList <DvinApp> > LoadAsync(bool resolve, IErrorsAndInfos errorsAndInfos)
        {
            var dvinAppsSecret = new SecretDvinApps();
            var secretDvinApps = await SecretRepository.GetAsync(dvinAppsSecret, errorsAndInfos);

            if (!resolve || errorsAndInfos.AnyErrors())
            {
                return(secretDvinApps);
            }

            await secretDvinApps.ResolveFoldersAsync(FolderResolver, errorsAndInfos);

            return(secretDvinApps);
        }
Beispiel #9
0
        public async Task SetBenchmarkDefinitionsAsync()
        {
            var secret         = new SecretBenchmarkDefinitions();
            var errorsAndInfos = new ErrorsAndInfos();

            BenchmarkDefinitions = await SecretRepository.GetAsync(secret, errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                throw new Exception(string.Join("\r\n", errorsAndInfos.Errors));
            }

            SelectedBenchmarkDefinition       = BenchmarkDefinitions[0];
            BenchmarkExecutions               = new ObservableCollection <IBenchmarkExecution>();
            BenchmarkExecutionStates          = new ObservableCollection <IBenchmarkExecutionState>();
            DisplayedBenchmarkExecutionStates = new ObservableCollection <IDisplayedBenchmarkExecutionState>();

            BenchmarkDefinitions.CollectionChanged     += BenchmarkDefinitionsOnCollectionChanged;
            BenchmarkExecutionStates.CollectionChanged += BenchmarkExecutionStatesOnCollectionChanged;
        }
Beispiel #10
0
    public async Task <string> Disguise(ISecretRepository secretRepository, string s, IErrorsAndInfos errorsAndInfos)
    {
        var bytes = Encoding.UTF8.GetBytes(s);

        EnsurePrimeNumbers(bytes);
        long pos              = bytes.Length;
        var  primePos         = bytes.Length;
        var  disguised        = "";
        var  secretLongString = await secretRepository.GetAsync(new LongSecretString(), errorsAndInfos);

        var longString = secretLongString.TheLongString;

        foreach (var aByte in bytes)
        {
            pos       += aByte * PrimeNumbers[primePos];
            primePos  += aByte;
            disguised += longString.Substring((int)(pos % (longString.Length - 3)), 3);
        }

        return(disguised);
    }
Beispiel #11
0
        private async Task AutoCommitAndPushAsync(string nugetFeedId, IFolder repositoryFolder, List <string> files, bool onlyIfNecessary, string commitMessage, bool noRebuildRequired, IErrorsAndInfos errorsAndInfos)
        {
            var branchName = GitUtilities.CheckedOutBranch(repositoryFolder);

            if (branchName != "master")
            {
                errorsAndInfos.Errors.Add(Properties.Resources.CheckedOutBranchIsNotMaster);
                return;
            }

            var headTipShaBeforePush = GitUtilities.HeadTipIdSha(repositoryFolder);

            GitUtilities.IdentifyOwnerAndName(repositoryFolder, out var owner, out _, errorsAndInfos);
            if (errorsAndInfos.AnyErrors())
            {
                errorsAndInfos.Errors.Add(Properties.Resources.OwnerAndNameNotFound);
                return;
            }

            var personalAccessTokensSecret = new PersonalAccessTokensSecret();
            var personalAccessTokens       = await SecretRepository.GetAsync(personalAccessTokensSecret, errorsAndInfos);

            var personalAccessToken = personalAccessTokens.FirstOrDefault(t => t.Owner == owner && t.Purpose == "AutoCommitPush");

            if (personalAccessToken == null)
            {
                errorsAndInfos.Errors.Add(Properties.Resources.AutoCommitPushAccessTokenNotFound);
                return;
            }

            using var repo = new Repository(repositoryFolder.FullName);

            var remotes = repo.Network.Remotes.ToList();

            if (remotes.Count != 1)
            {
                errorsAndInfos.Errors.Add(Properties.Resources.RemoteNotFoundOrNotUnique);
                return;
            }

            var remote = remotes[0];

            files.ForEach(f => {
                // ReSharper disable once AccessToDisposedClosure
                Commands.Stage(repo, f);
            });

            var checkFiles = GitUtilities.FilesWithUncommittedChanges(repositoryFolder);

            if (onlyIfNecessary && !checkFiles.Any())
            {
                return;
            }

            if (checkFiles.Count != files.Count)
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.NumberOfFilesWithUncommittedChangesHasChanged,
                                                        string.Join(", ", files), string.Join(", ", checkFiles)));
                return;
            }

            var author    = new Signature(personalAccessToken.TokenName, personalAccessToken.Email, DateTime.Now);
            var committer = author;

            repo.Commit(commitMessage, author, committer);

            var options = new PushOptions {
                CredentialsProvider = (_, _, _) => new UsernamePasswordCredentials {
                    Username = owner,
                    Password = personalAccessToken.Token
                }
            };

            repo.Network.Push(remote, @"refs/heads/" + branchName, options);

            if (!noRebuildRequired)
            {
                return;
            }

            var pushedHeadTipShaRepository = PushedHeadTipShaRepository;

            if (!(await pushedHeadTipShaRepository.GetAsync(nugetFeedId, errorsAndInfos)).Contains(headTipShaBeforePush))
            {
                return;
            }

            var headTipSha = GitUtilities.HeadTipIdSha(repositoryFolder);
            await pushedHeadTipShaRepository.AddAsync(nugetFeedId, headTipSha, errorsAndInfos);
        }
        public async Task <IPackageToPush> FindPackageToPushAsync(string nugetFeedId, IFolder packageFolderWithBinaries, IFolder repositoryFolder, string solutionFileFullName, IErrorsAndInfos errorsAndInfos)
        {
            IPackageToPush packageToPush = new PackageToPush();

            errorsAndInfos.Infos.Add(Properties.Resources.CheckingProjectVsSolution);
            var projectFileFullName = solutionFileFullName.Replace(".sln", ".csproj");

            if (!File.Exists(projectFileFullName))
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.ProjectFileNotFound, projectFileFullName));
                return(packageToPush);
            }

            errorsAndInfos.Infos.Add(Properties.Resources.LoadingProject);
            var project = ProjectFactory.Load(solutionFileFullName, projectFileFullName, errorsAndInfos);

            if (errorsAndInfos.Errors.Any())
            {
                return(packageToPush);
            }

            errorsAndInfos.Infos.Add(Properties.Resources.LoadingNugetFeeds);
            var developerSettingsSecret = new DeveloperSettingsSecret();
            var developerSettings       = await SecretRepository.GetAsync(developerSettingsSecret, errorsAndInfos);

            if (errorsAndInfos.Errors.Any())
            {
                return(packageToPush);
            }

            if (developerSettings == null)
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.MissingDeveloperSettings, developerSettingsSecret.Guid + ".xml"));
                return(packageToPush);
            }

            var nugetFeedsSecret = new SecretNugetFeeds();
            var nugetFeeds       = await SecretRepository.GetAsync(nugetFeedsSecret, errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                return(packageToPush);
            }

            errorsAndInfos.Infos.Add(Properties.Resources.IdentifyingNugetFeed);
            var nugetFeed = nugetFeeds.FirstOrDefault(f => f.Id == nugetFeedId);

            if (nugetFeed == null)
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.UnknownNugetFeed, nugetFeedId, nugetFeedsSecret.Guid + ".xml"));
                return(packageToPush);
            }

            if (!nugetFeed.IsAFolderToResolve())
            {
                var nugetConfigFileFullName = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\NuGet\" + "nuget.config";
                packageToPush.ApiKey = NugetConfigReader.GetApiKey(nugetConfigFileFullName, nugetFeed.Id, errorsAndInfos);
                if (errorsAndInfos.Errors.Any())
                {
                    return(packageToPush);
                }
            }

            errorsAndInfos.Infos.Add(Properties.Resources.IdentifyingFeedUrl);
            var source = await nugetFeed.UrlOrResolvedFolderAsync(FolderResolver, errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                return(packageToPush);
            }

            packageToPush.FeedUrl = source;
            if (string.IsNullOrEmpty(packageToPush.FeedUrl))
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.IncompleteDeveloperSettings, developerSettingsSecret.Guid + ".xml"));
                return(packageToPush);
            }

            errorsAndInfos.Infos.Add(Properties.Resources.SearchingLocalPackage);
            var localPackageRepository = new FindLocalPackagesResourceV2(packageFolderWithBinaries.FullName);
            var localPackages          = localPackageRepository.GetPackages(new NullLogger(), CancellationToken.None).Where(p => !p.Identity.Version.IsPrerelease).ToList();

            if (!localPackages.Any())
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.NoPackageFilesFound, packageFolderWithBinaries.FullName));
                return(packageToPush);
            }

            var latestLocalPackageVersion = localPackages.Max(p => p.Identity.Version.Version);

            errorsAndInfos.Infos.Add(string.Format(Properties.Resources.FoundLocalPackage, latestLocalPackageVersion));

            errorsAndInfos.Infos.Add(Properties.Resources.SearchingRemotePackage);
            var packageId      = string.IsNullOrWhiteSpace(project.PackageId) ? project.RootNamespace : project.PackageId;
            var remotePackages = await NugetFeedLister.ListReleasedPackagesAsync(nugetFeedId, packageId, errorsAndInfos);

            if (errorsAndInfos.Errors.Any())
            {
                return(packageToPush);
            }
            if (!remotePackages.Any())
            {
                errorsAndInfos.Errors.Add(string.Format(Properties.Resources.NoRemotePackageFilesFound, packageToPush.FeedUrl, packageId));
                return(packageToPush);
            }

            errorsAndInfos.Infos.Add(Properties.Resources.LoadingPushedHeadTipShas);
            var pushedHeadTipShas = await PushedHeadTipShaRepository.GetAsync(nugetFeedId, errorsAndInfos);

            if (errorsAndInfos.AnyErrors())
            {
                return(packageToPush);
            }

            var headTipIdSha = repositoryFolder == null ? "" : GitUtilities.HeadTipIdSha(repositoryFolder);

            if (!string.IsNullOrWhiteSpace(headTipIdSha) && pushedHeadTipShas.Contains(headTipIdSha))
            {
                errorsAndInfos.Infos.Add(string.Format(Properties.Resources.HeadTipShaHasAlreadyBeenPushed, headTipIdSha, nugetFeedId));
                return(packageToPush);
            }

            var latestRemotePackageVersion = remotePackages.Max(p => p.Identity.Version.Version);

            errorsAndInfos.Infos.Add(string.Format(Properties.Resources.FoundRemotePackage, latestRemotePackageVersion));
            if (latestRemotePackageVersion >= latestLocalPackageVersion)
            {
                errorsAndInfos.Infos.Add(string.Format(Properties.Resources.RemotePackageHasHigherOrEqualVersion, headTipIdSha));
                return(packageToPush);
            }

            errorsAndInfos.Infos.Add(Properties.Resources.CheckingRemotePackageTag);
            var remotePackage = remotePackages.First(p => p.Identity.Version.Version == latestRemotePackageVersion);

            if (!string.IsNullOrEmpty(remotePackage.Tags) && !string.IsNullOrWhiteSpace(headTipIdSha))
            {
                errorsAndInfos.Infos.Add(string.Format(Properties.Resources.TagsAre, remotePackage.Tags));
                var tags = remotePackage.Tags.Split(' ').ToList();
                if (tags.Contains(headTipIdSha))
                {
                    errorsAndInfos.Infos.Add(string.Format(Properties.Resources.PackageAlreadyTaggedWithHeadTipSha, headTipIdSha));
                    return(packageToPush);
                }

                if (tags.Count != 1)
                {
                    errorsAndInfos.Errors.Add(string.Format(Properties.Resources.RemotePackageContainsSeveralTags, tags));
                    return(packageToPush);
                }

                var tag = tags[0];
                errorsAndInfos.Infos.Add(string.Format(Properties.Resources.CheckingIfThereAreChangedBinaries, headTipIdSha, tag));
                var listerErrorsAndInfos = new ErrorsAndInfos();
                var changedBinaries      = ChangedBinariesLister.ListChangedBinaries(packageId, headTipIdSha, tag, listerErrorsAndInfos);
                if (listerErrorsAndInfos.AnyErrors())
                {
                    errorsAndInfos.Infos.AddRange(listerErrorsAndInfos.Infos);
                    errorsAndInfos.Errors.AddRange(listerErrorsAndInfos.Errors);
                    return(packageToPush);
                }
                if (!changedBinaries.Any())
                {
                    errorsAndInfos.Infos.Add(string.Format(Properties.Resources.NoBinariesHaveChanged));
                    return(packageToPush);
                }
            }

            errorsAndInfos.Infos.Add(Properties.Resources.PackageNeedsToBePushed);
            packageToPush.PackageFileFullName = packageFolderWithBinaries.FullName + @"\" + packageId + "." + latestLocalPackageVersion + ".nupkg";
            packageToPush.Id      = packageId;
            packageToPush.Version = latestLocalPackageVersion?.ToString();
            if (File.Exists(packageToPush.PackageFileFullName))
            {
                return(packageToPush);
            }

            errorsAndInfos.Errors.Add(string.Format(Properties.Resources.FileNotFound, packageToPush.PackageFileFullName));
            return(packageToPush);
        }