示例#1
0
        public void simple_crypt_test()
        {
            var c    = KeyVault.EncryptValuesToString(ReferenceDictionary, "A passphrase");
            var read = KeyVault.DecryptValues(c, "A passphrase");

            read.Should().BeEquivalentTo(ReferenceDictionary);
        }
示例#2
0
        public void read_previous_version(int version)
        {
            var fName = PreviousVersionsFolder.AppendPart($"Version{version}.txt");
            var read  = KeyVault.DecryptValues(File.ReadAllText(fName), "A passphrase");

            read.Should().BeEquivalentTo(ReferenceDictionary);
        }
        public void ApplySettings(IActivityMonitor m)
        {
            if (!_f.EnsureDirectory(m))
            {
                return;
            }
            var s = _driver.GetSolution(m, allowInvalidSolution: true);

            if (s == null)
            {
                return;
            }

            if (_driver.BuildRequiredSecrets.Count == 0)
            {
                m.Warn("No build secrets collected for this solution. Skipping KeyVault configuration.");
                return;
            }

            var passPhrase = _secretStore.GetSecretKey(m, SolutionDriver.CODECAKEBUILDER_SECRET_KEY, true);

            // Opens the actual current vault: if more secrets are defined we keep them.
            Dictionary <string, string> current = KeyVault.DecryptValues(TextContent, passPhrase);

            current.Clear();

            // The central CICDKeyVault is protected with the same CODECAKEBUILDER_SECRET_KEY secret.
            Dictionary <string, string> centralized = KeyVault.DecryptValues(_sharedState.CICDKeyVault, passPhrase);

            bool complete = true;

            foreach (var name in _driver.BuildRequiredSecrets.Select(x => x.SecretKeyName))
            {
                if (!centralized.TryGetValue(name, out var secret))
                {
                    m.Error($"Missing required build secret '{name}' in central CICDKeyVault. It must be added.");
                    complete = false;
                }
                else
                {
                    current[name] = secret;
                }
            }
            if (complete)
            {
                Updating?.Invoke(this, new CodeCakeBuilderKeyVaultUpdatingArgs(m, _solutionSpec, s, current));
                string result = KeyVault.EncryptValuesToString(current, passPhrase);
                CreateOrUpdate(m, result);
            }
        }
示例#4
0
 /// <summary>
 /// Opens the key vault.
 /// </summary>
 /// <param name="m">The monitor to use.</param>
 /// <param name="passPhrase">The key vault pass phrase.</param>
 /// <returns>True on success.</returns>
 public bool OpenKeyVault(IActivityMonitor m, string passPhrase)
 {
     if (!CheckPassPhraseConstraints(m, passPhrase))
     {
         return(false);
     }
     if (_passPhrase != null)
     {
         m.Info($"Key Vault is already opened.");
         return(true);
     }
     if (KeyVaultFileExists)
     {
         try
         {
             var keys = KeyVault.DecryptValues(File.ReadAllText(KeyVaultPath), passPhrase);
             m.OpenInfo($"Opening existing Key Vault with keys: {keys.Keys.Concatenate()}.");
             _store.ImportSecretKeys(m, keys);
             _passPhrase = passPhrase;
             _vaultContent.Clear();
             _vaultContent.AddRange(keys);
         }
         catch (Exception ex)
         {
             m.Error("Unable to open the key vault.", ex);
             return(false);
         }
     }
     else
     {
         _passPhrase = passPhrase;
         m.OpenInfo($"New Key Vault opened.");
     }
     if (_store.Infos.Any(s => !s.IsSecretAvailable))
     {
         using (m.OpenWarn($"Missing secrets:"))
         {
             foreach (var s in _store.Infos.Where(s => !s.IsSecretAvailable))
             {
                 m.Warn(s.ToString());
             }
         }
     }
     m.CloseGroup();
     return(true);
 }
示例#5
0
        public void simple_crypt_test()
        {
            var vals = new Dictionary <string, string> {
                { "A", "a1" },
                { "Hello", "world" },
                { "Hi", null },
                { "Hi2", "" },
                { "It", @"Works!
                          well.." }
            };
            var c     = KeyVault.EncryptValuesToString(vals, "A passphrase");
            var vals2 = KeyVault.DecryptValues(c, "A passphrase");

            vals2.Should().BeEquivalentTo(vals);

            Assert.Throws <System.Security.Cryptography.CryptographicException>(
                () => KeyVault.DecryptValues(c, "bad password"));
        }
示例#6
0
        public void keys_can_be_removed()
        {
            var vals = new Dictionary <string, string> {
                { "ThisKeyWillBeRemoved", "qsmlk" },
                { "Hello", "world" },
                { "Hi", null },
                { "ThisWillAlsoBeRemoved", "this value will not be here." },
                { "It", @"Works!
                          well.." }
            };
            var c = KeyVault.EncryptValuesToString(vals, "A passphrase");

            c = c.Replace("ThisKeyWillBeRemoved", "")
                .Replace("ThisWillAlsoBeRemoved", "");

            var vals2 = KeyVault.DecryptValues(c, "A passphrase");

            vals.Remove("ThisKeyWillBeRemoved");
            vals.Remove("ThisWillAlsoBeRemoved");
            vals2.Should().BeEquivalentTo(vals);
        }
示例#7
0
        public void keys_can_be_removed()
        {
            var vals = new Dictionary <string, string> {
                { "ThisKeyWillBeRemoved", "qsmlk" },
                { "Hello", "world" },
                { "Hi", null },
                { "ThisWillAlsoBeRemoved", "this value will not be here." },
                { "It", @"Works! well.." }
            };
            // We remove the keys from the text crypted file (by emptying the declaration lines).
            var c = KeyVault.EncryptValuesToString(vals, "A passphrase");

            c = c.Replace("ThisKeyWillBeRemoved", "")
                .Replace("ThisWillAlsoBeRemoved", "");

            // Removing the keys from the initial dictionary:
            vals.Remove("ThisKeyWillBeRemoved");
            vals.Remove("ThisWillAlsoBeRemoved");

            // Decryption doesn't return these removed lines!
            var vals2 = KeyVault.DecryptValues(c, "A passphrase");

            vals2.Should().BeEquivalentTo(vals);
        }
示例#8
0
        public void bad_password_throws_an_InvalidDataException()
        {
            var c = KeyVault.EncryptValuesToString(ReferenceDictionary, "A passphrase");

            Assert.Throws <InvalidDataException>(() => KeyVault.DecryptValues(c, "bad password"));
        }
示例#9
0
        public void ApplySettings(IActivityMonitor m)
        {
            if (!this.CheckCurrentBranch(m))
            {
                return;
            }
            YamlMapping firstMapping = GetFirstMapping(m, true);

            if (firstMapping == null)
            {
                return;
            }
            var solution = _driver.GetSolution(m, allowInvalidSolution: true);

            if (solution == null)
            {
                return;
            }

            // We don't use AppVeyor for private repositories.
            if (!GitFolder.IsPublic)
            {
                if (TextContent != null)
                {
                    m.Log(LogLevel.Info, "The project is private, so we don't use Appveyor and the Appveyor.yml is not needed.");
                    Delete(m);
                }
                return;
            }
            // We currently always use AppVeyor when the repository is public.
            YamlMapping env = FindOrCreateYamlElement(m, firstMapping, "environment");

            if (env == null)
            {
                return;
            }

            var passphrase = _keyStore.GetSecretKey(m, SolutionDriver.CODECAKEBUILDER_SECRET_KEY, false);

            if (passphrase != null)
            {
                var central = KeyVault.DecryptValues(_sharedState.CICDKeyVault, passphrase);
                if (central.TryGetValue(APPVEYOR_ENCRYPTED_CODECAKEBUILDER_SECRET_KEY, out var appveyorSecure))
                {
                    env[SolutionDriver.CODECAKEBUILDER_SECRET_KEY] = CreateKeyValue("secure", appveyorSecure);
                }
                else
                {
                    m.Warn($"Update of {SolutionDriver.CODECAKEBUILDER_SECRET_KEY} encrypted secure key has been skipped: {APPVEYOR_ENCRYPTED_CODECAKEBUILDER_SECRET_KEY} key should be defined in CICDKeyVault.");
                }
            }
            else
            {
                m.Info($"Update of {SolutionDriver.CODECAKEBUILDER_SECRET_KEY} encrypted secure skipped.");
            }
            // Remove obsolete environment variables definitions.
            env.Remove("NUGET_API_KEY");
            env.Remove("MYGET_RELEASE_API_KEY");
            env.Remove("MYGET_PREVIEW_API_KEY");
            env.Remove("MYGET_CI_API_KEY");
            env.Remove("CK_DB_TEST_MASTER_CONNECTION_STRING");
            env.Remove("AZURE_FEED_SIGNATURE_OPENSOURCE_PAT");
            env.Remove("AZURE_FEED_PAT");
            env.Remove("VSS_NUGET_EXTERNAL_FEED_ENDPOINTS");
            if (_solutionSpec.SqlServer != null)
            {
                env["SqlServer/MasterConnectionString"] = new YamlValue($"Server=(local)\\SQL{_solutionSpec.SqlServer.ToUpperInvariant()};Database=master;User ID=sa;Password=Password12!");
            }
            //
            firstMapping.Remove(new YamlValue("init"));
            if (_solutionSpec.SqlServer != null)
            {
                firstMapping["services"] = new YamlValue("mssql" + _solutionSpec.SqlServer.ToLowerInvariant());
            }
            var install = new YamlSequence();

            // Temporary: installs the 6.9.0 of npm.
            if (solution.GeneratedArtifacts.Any(g => g.Artifact.Type.Name == "NPM"))
            {
                install.Add(CreateKeyValue("cmd", "npm install -g [email protected]"));
                install.Add(CreateKeyValue("ps", "Install-Product node 12"));
            }
            firstMapping["install"] = install;

            firstMapping["version"]      = new YamlValue("build{build}");
            firstMapping["image"]        = new YamlValue("Visual Studio 2019");
            firstMapping["clone_folder"] = new YamlValue("C:\\CKli-World\\" + GitFolder.SubPath.Path.Replace('/', '\\'));
            EnsureDefaultBranches(firstMapping);
            SetSequence(firstMapping, "build_script", new YamlValue("dotnet run --project CodeCakeBuilder -nointeraction"));
            firstMapping["test"]      = new YamlValue("off");
            firstMapping["artifacts"] = new YamlSequence()
            {
                new YamlMapping()
                {
                    ["path"] = new YamlValue(@"'**\*.log'"),
                    ["name"] = new YamlValue("Log file")
                },
                new YamlMapping()
                {
                    ["path"] = new YamlValue(@"'**\*.trx'"),
                    ["name"] = new YamlValue("Visual studio test results file")
                },
                new YamlMapping()
                {
                    ["path"] = new YamlValue(@"'**\Tests\**\TestResult*.xml'"),
                    ["name"] = new YamlValue("NUnit tests result files")
                },
                new YamlMapping()
                {
                    ["path"] = new YamlValue(@"'**Tests\**\Logs\**\*'"),
                    ["name"] = new YamlValue("Log files")
                }
            };
            CreateOrUpdate(m, YamlMappingToString(m));
        }