Esempio n. 1
0
        public void Initialize()
        {
            string asmDir = PathEx.GetDirectoryName(typeof(GitTests).Assembly.Location);

            this.rootDir = PathEx.Combine(asmDir, "test-root");
            DirectoryEx.Create(this.rootDir);
            DirectoryEx.Clear(this.rootDir);

            if (FileEx.Exists(credentialsFilePath))
            {
                var lines = File.ReadAllLines(credentialsFilePath);
                this.userName = lines[0];
                this.password = AH.CreateSecureString(lines[1]);
            }

            var fileOps = new TestFileOperationsExecuter(Path.Combine(this.rootDir, "agent"));

            //var fileOps = new SimulatedFileOperationsExecuter(fileOps);
            //fileOps.MessageLogged += (s, e) => TestLogger.Instance.Log(e.Level, e.Message);

            this.fileOps = fileOps;

            this.processExecuter = new TestRemoteProcessExecuter();
            this.jobExecuter     = new TestRemoteJobExecuter();
        }
Esempio n. 2
0
            private static object ConvertValue(object value, Type targetType)
            {
                if (value == null)
                {
                    return(null);
                }

                var sourceType = value.GetType();

                if (targetType.IsAssignableFrom(sourceType))
                {
                    return(value);
                }

                if (targetType == typeof(string))
                {
                    if (value is SecureString secure)
                    {
                        return(AH.Unprotect(secure));
                    }
                    else
                    {
                        return(value.ToString());
                    }
                }
                else if (targetType == typeof(SecureString))
                {
                    return(AH.CreateSecureString(value.ToString()));
                }
                else
                {
                    throw new NotSupportedException($"Type {sourceType.Name} cannot be converted to {targetType.Name} in resource credential target.");
                }
            }
Esempio n. 3
0
 private JenkinsClient CreateClient()
 {
     return(new JenkinsClient(
                username: "******",
                password: AH.CreateSecureString("test"),
                serverUrl: "http://localhost:8080",
                csrfProtectionEnabled: true
                ));
 }
Esempio n. 4
0
        public async override Task <object> ExecuteAsync(CancellationToken cancellationToken)
        {
            GitRepositoryInfo repo;

            if (!string.IsNullOrEmpty(this.Context.LocalRepositoryPath))
            {
                repo = new GitRepositoryInfo(
                    new WorkspacePath(this.Context.LocalRepositoryPath),
                    this.Context.RemoteRepositoryUrl,
                    this.Context.UserName,
                    AH.CreateSecureString(this.Context.Password)
                    );
            }
            else
            {
                repo = new GitRepositoryInfo(
                    this.Context.RemoteRepositoryUrl,
                    this.Context.UserName,
                    AH.CreateSecureString(this.Context.Password)
                    );
            }

            var client = new LibGitSharpClient(repo, this);

            switch (this.Command)
            {
            case ClientCommand.Archive:
                await client.ArchiveAsync(this.Context.TargetDirectory, this.Context.KeepInternals).ConfigureAwait(false);

                return(null);

            case ClientCommand.Clone:
                await client.CloneAsync(this.Context.CloneOptions).ConfigureAwait(false);

                return(null);

            case ClientCommand.EnumerateRemoteBranches:
                return((await client.EnumerateRemoteBranchesAsync().ConfigureAwait(false)).ToArray());

            case ClientCommand.IsRepositoryValid:
                return(await client.IsRepositoryValidAsync().ConfigureAwait(false));

            case ClientCommand.Tag:
                await client.TagAsync(this.Context.Tag, this.Context.Commit, this.Context.TagMessage, this.Context.Force).ConfigureAwait(false);

                return(null);

            case ClientCommand.Update:
                return(await client.UpdateAsync(this.Context.UpdateOptions).ConfigureAwait(false));

            default:
                throw new InvalidOperationException("Invalid remote LibGitSharp job type: " + this.Command);
            }
        }
        protected YouTrackClient CreateClient(IComponentConfiguration config)
        {
            var credentials = ResourceCredentials.Create <YouTrackCredentials>(config[nameof(IHasCredentials <YouTrackCredentials> .CredentialName)]);

            return(new YouTrackClient(
                       new YouTrackCredentials
            {
                ServerUrl = AH.CoalesceString(config[nameof(YouTrackOperationBase.ServerUrl)], credentials?.ServerUrl),
                UserName = AH.CoalesceString(config[nameof(YouTrackOperationBase.UserName)], credentials?.UserName),
                Password = AH.CreateSecureString(AH.CoalesceString(config[nameof(YouTrackOperationBase.Password)], AH.Unprotect(credentials?.Password))),
                PermanentToken = AH.CreateSecureString(AH.CoalesceString(config[nameof(YouTrackOperationBase.PermanentToken)], AH.Unprotect(credentials?.PermanentToken))),
            }
                       ));
        }
Esempio n. 6
0
 public override void Deserialize(Stream stream)
 {
     using (var reader = new BinaryReader(stream, InedoLib.UTF8Encoding, true))
     {
         this.JobName = reader.ReadString();
         this.AdditionalParameters  = reader.ReadString();
         this.WaitForStart          = reader.ReadBoolean();
         this.WaitForCompletion     = reader.ReadBoolean();
         this.ProxyRequest          = reader.ReadBoolean();
         this.JenkinsBuildNumber    = reader.ReadString();
         this.ServerUrl             = reader.ReadString();
         this.UserName              = reader.ReadString();
         this.Password              = AH.CreateSecureString(reader.ReadString());
         this.CsrfProtectionEnabled = reader.ReadBoolean();
     }
 }
Esempio n. 7
0
            public PackageSourceData(SQLiteDataReader reader)
            {
                this.Name    = reader.GetString(0);
                this.FeedUrl = reader.GetString(1);
                if (!reader.IsDBNull(2))
                {
                    this.UserName = reader.GetString(2);
                }

                var blob = !reader.IsDBNull(3) ? reader.GetFieldValue <byte[]>(3) : null;

                if (blob != null)
                {
                    this.Password = AH.CreateSecureString(InedoLib.UTF8Encoding.GetString(ProtectedData.Unprotect(blob, null, RompConfig.UserMode ? DataProtectionScope.CurrentUser : DataProtectionScope.LocalMachine)));
                }
            }
        public async Task <IEnumerable <string> > GetSuggestionsAsync(IComponentConfiguration config)
        {
            string ownerName = AH.CoalesceString(config[nameof(GitHubCredentials.OrganizationName)], config[nameof(GitHubCredentials.UserName)]);

            if (string.IsNullOrEmpty(ownerName))
            {
                return(Enumerable.Empty <string>());
            }

            GitHubClient client;

            try
            {
                client = new GitHubClient(config[nameof(GitHubCredentials.ApiUrl)], config[nameof(GitHubCredentials.UserName)], AH.CreateSecureString(config[nameof(GitHubCredentials.Password)].ToString()), config[nameof(GitHubCredentials.OrganizationName)]);
            }
            catch (InvalidOperationException)
            {
                return(Enumerable.Empty <string>());
            }

            var orgs = await client.GetOrganizationsAsync(CancellationToken.None).ConfigureAwait(false);

            var names = from m in orgs
                        let name = m["login"]?.ToString()
                                   where !string.IsNullOrEmpty(name)
                                   select name;

            return(names);
        }
Esempio n. 9
0
 private static SecureString CoalescePassword(string a, SecureString b)
 {
     return(AH.CreateSecureString(AH.CoalesceString(a, AH.Unprotect(b))));
 }
Esempio n. 10
0
        private AwsSecureCredentials GetCredentials(ICredentialResolutionContext context)
        {
            AwsSecureCredentials credentials;

            if (string.IsNullOrEmpty(this.CredentialName))
            {
                credentials = this.AccessKey == null ? null : new AwsSecureCredentials();
            }
            else
            {
                credentials = SecureCredentials.TryCreate(this.CredentialName, context) as AwsSecureCredentials;
                if (credentials == null)
                {
                    var rc = SecureCredentials.TryCreate(this.CredentialName, context) as AwsLegacyCredentials;
                    credentials = rc?.ToSecureCredentials() as AwsSecureCredentials;
                }
            }

            if (credentials != null)
            {
                credentials.AccessKeyId     = AH.CoalesceString(this.AccessKey, credentials.AccessKeyId);
                credentials.SecretAccessKey = !string.IsNullOrWhiteSpace(this.SecretAccessKey) ? AH.CreateSecureString(this.SecretAccessKey) : credentials.SecretAccessKey;
            }

            return(credentials);
        }
 public static SecureString ToSecureString(this string s) => AH.CreateSecureString(s);
Esempio n. 12
0
        private static void Credentials(ArgList args)
        {
            var command = args.PopCommand()?.ToLowerInvariant();

            switch (command)
            {
            case "list":
                list();
                break;

            case "display":
                display();
                break;

            case "store":
                store();
                break;

            case "delete":
                delete();
                break;

            default:
                Console.WriteLine("Usage:");
                Console.WriteLine("romp credentials list");
                Console.WriteLine("romp credentials display <name> [--show-hidden]");
                Console.WriteLine("romp credentials store <name>");
                Console.WriteLine("romp credentials delete <name>");
                break;
            }

            void list()
            {
                foreach (var c in RompDb.GetCredentials())
                {
                    Console.WriteLine(c.CredentialType_Name + "::" + c.Credential_Name);
                }
            }

            void display()
            {
                var(type, name) = parseQualifiedName();
                var creds = RompDb.GetCredentialsByName(type, name);

                if (creds == null)
                {
                    throw new RompException($"Credentials {type}::{name} not found.");
                }

                bool showHidden = false;

                args.ProcessOptions(
                    o =>
                {
                    if (string.Equals(o.Key, "show-hidden", StringComparison.OrdinalIgnoreCase))
                    {
                        showHidden = true;
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                    );

                args.ThrowIfAnyRemaining();

                var instance = (ResourceCredentials)Persistence.DeserializeFromPersistedObjectXml(creds.Configuration_Xml);

                Console.WriteLine($"Name: {creds.CredentialType_Name}::{creds.Credential_Name}");

                foreach (var prop in Persistence.GetPersistentProperties(instance.GetType(), false))
                {
                    var alias = prop.GetCustomAttribute <ScriptAliasAttribute>()?.Alias;
                    if (alias != null) // only show items with ScriptAlias
                    {
                        var  propName = prop.GetCustomAttribute <DisplayNameAttribute>()?.DisplayName ?? alias;
                        bool hidden   = prop.GetCustomAttribute <PersistentAttribute>().Encrypted;

                        var value = prop.GetValue(instance);
                        if (value is SecureString secure)
                        {
                            value = AH.Unprotect(secure);
                        }

                        if (hidden && !showHidden)
                        {
                            value = "(hidden)";
                        }
                        if (value == null)
                        {
                            value = "(not specified)";
                        }

                        Console.WriteLine(propName + ": " + value);
                    }
                }
            }

            void store()
            {
                var n    = parseQualifiedName();
                var type = (from c in ExtensionsManager.GetComponentsByBaseClass <ResourceCredentials>()
                            let a = c.ComponentType.GetCustomAttribute <ScriptAliasAttribute>()
                                    where string.Equals(a?.Alias, n.type, StringComparison.OrdinalIgnoreCase) || string.Equals(c.ComponentType.Name, n.type, StringComparison.OrdinalIgnoreCase)
                                    orderby string.Equals(a?.Alias, n.type, StringComparison.OrdinalIgnoreCase) descending
                                    select c.ComponentType).FirstOrDefault();

                if (type == null)
                {
                    throw new RompException($"Unknown credentials type \"{n.type}\". Are you missing an extension?");
                }

                var credentials = (ResourceCredentials)Activator.CreateInstance(type);

                if (!Console.IsInputRedirected)
                {
                    foreach (var property in Persistence.GetPersistentProperties(type, true))
                    {
Again:
                        Console.Write((property.GetCustomAttribute <DisplayNameAttribute>()?.DisplayName ?? property.Name) + ": ");
                        string value;
                        if (property.GetCustomAttribute <PersistentAttribute>()?.Encrypted == true || property.PropertyType == typeof(SecureString))
                        {
                            value = ReadSensitive();
                        }
                        else
                        {
                            value = Console.ReadLine();
                        }

                        if (!string.IsNullOrEmpty(value))
                        {
                            if (property.PropertyType == typeof(string))
                            {
                                property.SetValue(credentials, value);
                            }
                            else if (property.PropertyType == typeof(SecureString))
                            {
                                property.SetValue(credentials, AH.CreateSecureString(value));
                            }
                            else
                            {
                                try
                                {
                                    var convertedValue = Convert.ChangeType(value, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
                                    property.SetValue(credentials, convertedValue);
                                }
                                catch (Exception ex)
                                {
                                    Console.Error.WriteLine("Invalid value: " + ex.Message);
                                    goto Again;
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new RompException("Credentials must be stored interactively.");
                }

                RompDb.CreateOrUpdateCredentials(n.name, credentials, true);
                Console.WriteLine("Credentials stored.");
            }

            void delete()
            {
                var(type, name) = parseQualifiedName();
                RompDb.DeleteCredentials(type, name);
                Console.WriteLine("Credentials deleted.");
            }

            (string type, string name) parseQualifiedName()
            {
                var qualifiedName = args.PopCommand();

                if (string.IsNullOrEmpty(qualifiedName))
                {
                    throw new RompException("Expected credentials name.");
                }

                var parts = qualifiedName.Split(new[] { "::" }, StringSplitOptions.None);

                if (parts.Length != 2 || string.IsNullOrWhiteSpace(parts[0]) || string.IsNullOrWhiteSpace(parts[1]))
                {
                    throw new RompException("Invalid credentials name specification.");
                }

                return(parts[0], parts[1]);
            }
        }
Esempio n. 13
0
        private static void Sources(ArgList args)
        {
            var command = args.PopCommand()?.ToLowerInvariant();

            switch (command)
            {
            case "list":
                list();
                break;

            case "display":
                display();
                break;

            case "create":
                create();
                break;

            case "delete":
                delete();
                break;

            case "default":
                defaultCommand();
                break;

            default:
                Console.WriteLine("Usage:");
                Console.WriteLine("romp sources list");
                Console.WriteLine("romp sources display <name> [--show-hidden]");
                Console.WriteLine("romp sources create <name> <url>");
                Console.WriteLine("romp sources delete <name>");
                break;
            }

            void list()
            {
                bool any = false;

                Console.WriteLine("Package sources:");

                foreach (var s in RompDb.GetPackageSources())
                {
                    any = true;
                    var url = s.FeedUrl;
                    if (!string.IsNullOrEmpty(s.UserName))
                    {
                        url = s.UserName + "@" + url;
                    }
                    Console.WriteLine(" " + s.Name + ": " + url);
                }

                if (!any)
                {
                    Console.WriteLine(" (none)");
                }
            }

            void display()
            {
                var name = args.PopCommand();

                if (string.IsNullOrEmpty(name))
                {
                    throw new RompException("Expected source name.");
                }

                var source = RompDb.GetPackageSources()
                             .FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase));

                if (source == null)
                {
                    throw new RompException($"Source {name} not found.");
                }

                bool showHidden = false;

                args.ProcessOptions(
                    o =>
                {
                    if (string.Equals(o.Key, "show-hidden", StringComparison.OrdinalIgnoreCase))
                    {
                        showHidden = true;
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                    );

                args.ThrowIfAnyRemaining();

                Console.WriteLine("Name: " + source.Name);
                Console.WriteLine("Url: " + source.FeedUrl);
                Console.WriteLine("User: "******"(not specified)");
                if (showHidden)
                {
                    Console.WriteLine("Password: "******"(not specified)");
                }
            }

            void create()
            {
                var name = args.PopCommand();
                var url  = args.PopCommand();

                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(url))
                {
                    throw new RompException("Usage: romp sources create <name> <url>");
                }

                Uri uri;

                try
                {
                    uri = new Uri(url);
                }
                catch (Exception ex)
                {
                    throw new RompException("Invalid URL: " + ex.Message, ex);
                }

                string       userName = null;
                SecureString password = null;

                if (!string.IsNullOrEmpty(uri.UserInfo))
                {
                    var parts = uri.UserInfo.Split(new[] { ':' }, 2);
                    userName = parts[0];
                    password = AH.CreateSecureString(parts.Length > 1 ? parts[1] : string.Empty);
                }

                var sanitizedUrl = new UriBuilder(uri)
                {
                    UserName = null,
                    Password = null
                };

                RompDb.CreateOrUpdatePackageSource(name, sanitizedUrl.ToString(), userName, password);
                Console.WriteLine("Package source stored.");
            }

            void delete()
            {
                var name = args.PopCommand();

                if (string.IsNullOrEmpty(name))
                {
                    throw new RompException("Expected source name.");
                }

                RompDb.DeletePackageSource(name);
                Console.WriteLine("Package source deleted.");

                if (string.Equals(RompConfig.DefaultSource, name, StringComparison.OrdinalIgnoreCase))
                {
                    RompConfig.DeleteValue("default-source");
                }
            }

            void defaultCommand()
            {
                var name = args.PopCommand();

                if (string.IsNullOrEmpty(name))
                {
                    throw new RompException("Expected source name.");
                }

                if (!RompDb.GetPackageSources().Any(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)))
                {
                    throw new RompException($"No source named {name} has been configured.");
                }

                RompConfig.SetValue("default-source", name);
                Console.WriteLine($"Default source set to {name}.");
            }
        }