Пример #1
0
        static CredentialsHandler CreateCredentialsHandler(IRepository repo, string remoteName)
        {
            var remote    = repo.Network.Remotes[remoteName];
            var remoteUri = new Uri(remote.Url);

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);

            var targetUrl = remoteUri.GetLeftPart(UriPartial.Authority);
            var creds     = auth.GetCredentials(new TargetUri(targetUrl));

            if (creds == null)
            {
                return(null);
            }

            CredentialsHandler credentialsHandler =
                (url, user, cred) => new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password
            };

            return(credentialsHandler);
        }
Пример #2
0
        protected virtual WebApplicationFactory <Startup> CreateFactory()
        {
            var f = new WebApplicationFactory <Startup>()
                    .WithWebHostBuilder(builder => builder.UseContentRoot("."));
            //{
            //    Environment = TestEnvironment
            //};

            var secretRepository = new SecretStore();

            secretRepository.Assign("1234", "ABCD");

            var mrb        = new HmacMessageRepresentationBuilder();
            var calculator = new HmacSignatureCalculator();

            HmacClient = new HmacClient
            {
                ClientId = "1234"
            };
            var hmacHandler = new HmacClientHandler(HmacClient);
            var requestContentMd5Handler = new RequestContentMd5Handler();
            var hmacSigningHandler       = new HmacSigningHandler(secretRepository, mrb, calculator);

            // Inject all the handlers in the correct order
            Client = f.CreateDefaultClient(hmacHandler, requestContentMd5Handler, hmacSigningHandler);

            //Startup = Program.Startup;

            return(f);
        }
        private void RegisterLocalServices()
        {
            this.localServices.Add(typeof(ISolutionRuleSetsInformationProvider), new Lazy <ILocalService>(() => new SolutionRuleSetsInformationProvider(this, Logger)));
            this.localServices.Add(typeof(IRuleSetSerializer), new Lazy <ILocalService>(() => new RuleSetSerializer(this)));
            this.localServices.Add(typeof(IConfigurationProvider), new Lazy <ILocalService>(() =>
            {
                var solution            = this.GetService <SVsSolution, IVsSolution>();
                var store               = new SecretStore(SolutionBindingSerializer.StoreNamespace);
                var legacySerializer    = new SolutionBindingSerializer(this);
                var sccFileSystem       = this.GetService <ISourceControlledFileSystem>();
                var newConfigSerializer = new ConfigurationSerializer(solution, sccFileSystem, store, Logger);
                return(new ConfigurationProvider(legacySerializer, newConfigSerializer));
            }));
            this.localServices.Add(typeof(IProjectSystemHelper), new Lazy <ILocalService>(() => new ProjectSystemHelper(this)));
            this.localServices.Add(typeof(IRuleSetInspector), new Lazy <ILocalService>(() => new RuleSetInspector(this, Logger)));
            this.localServices.Add(typeof(IRuleSetConflictsController), new Lazy <ILocalService>(() => new RuleSetConflictsController(this, new ConflictsManager(this, Logger))));
            this.localServices.Add(typeof(IProjectSystemFilter), new Lazy <ILocalService>(() => new ProjectSystemFilter(this)));
            this.localServices.Add(typeof(IErrorListInfoBarController), new Lazy <ILocalService>(() => new ErrorListInfoBarController(this, new SolutionBindingInformationProvider(this))));

            // Use Lazy<object> to avoid creating instances needlessly, since the interfaces are serviced by the same instance
            var sccFs = new Lazy <ILocalService>(() => new SourceControlledFileSystem(this));

            this.localServices.Add(typeof(ISourceControlledFileSystem), sccFs);
            this.localServices.Add(typeof(IFileSystem), sccFs);

            Debug.Assert(SupportedLocalServices.Length == this.localServices.Count, "Unexpected number of local services");
            Debug.Assert(SupportedLocalServices.All(t => this.localServices.ContainsKey(t)), "Not all the LocalServices are registered");
        }
 public CredentialStore(SecretStore store)
 {
     if (store == null)
     {
         throw new ArgumentNullException(nameof(store));
     }
     this.store = store;
 }
        public string FindGitHubToken()
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            return(creds?.Password);
        }
        public void ClientNotPresent()
        {
            var store = new SecretStore();

            var secret = store.ClientSecret("client");

            Assert.That(secret, Is.Null);
        }
        public static object Resolve(SecretStore secrets, Service service, Resource resource)
        {
            Func <ResourceResolutionContext, object> resolver;

            if (!Resolvers.TryGetValue(resource.Type, out resolver))
            {
                return(String.Empty);
            }
            return(resolver(new ResourceResolutionContext(secrets, service, resource)) ?? String.Empty);
        }
Пример #8
0
 internal LinkerResourceData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, TargetServiceBase targetService, AuthInfoBase authInfo, ClientType?clientType, string provisioningState, VNetSolution vNetSolution, SecretStore secretStore, string scope) : base(id, name, resourceType, systemData)
 {
     TargetService     = targetService;
     AuthInfo          = authInfo;
     ClientType        = clientType;
     ProvisioningState = provisioningState;
     VNetSolution      = vNetSolution;
     SecretStore       = secretStore;
     Scope             = scope;
 }
        public void ClientPresent()
        {
            var store = new SecretStore();

            store.Assign("client", "A");

            var secret = store.ClientSecret("client");

            Assert.That(secret, Is.EqualTo("A"));
        }
Пример #10
0
 public void ProtectCalled()
 {
     try
     {
         SecretStore.Protect("Test", null);
     }
     catch (Exception ex)
     {
         _thrownEx = ex;
     }
 }
Пример #11
0
 public static SecretStoreConnection Open(SecretStore store)
 {
     if (String.Equals(store.Type, SharepointSecretStoreConnection.TypeName, StringComparison.OrdinalIgnoreCase))
     {
         return new SharepointSecretStoreConnection(store);
     }
     throw new InvalidOperationException(String.Format(
         CultureInfo.CurrentCulture,
         Strings.SecretStoreConnection_UnknownSecretStoreType,
         store.Type));
 }
 public void UnprotectCalled()
 {
     try
     {
         SecretStore.Unprotect(null);
     }
     catch (Exception ex)
     {
         _thrownEx = ex;
     }
 }
        public SharepointSecretStoreConnection(SecretStore store)
        {
            SiteRoot = store.Value;
            Version = store.Version;

            if (Version > MaxVersion)
            {
                throw new NotSupportedException(String.Format(
                    CultureInfo.CurrentCulture,
                    Strings.SharepointSecretStoreConnection_UnsupportedVersion,
                    Version.ToString()));
            }
        }
Пример #14
0
        public Credential GetGitCredentials(string gitUrl)
        {
            var secrets = new SecretStore("git");

            var auth  = new BasicAuthentication(secrets);
            var uri   = new Uri(gitUrl);
            var url   = uri.Scheme + "://" + uri.Authority;
            var creds = auth.GetCredentials(new TargetUri(url));

            //if (creds == null)
            // TODO: Prompt for

            return(creds);
        }
        public Credentials GetCredentials(string url, string usernameFromUrl, SupportedCredentialTypes types)
        {
            var uri     = new Uri(url);
            var host    = uri.Scheme + Uri.SchemeDelimiter + uri.Host;
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri(host));

            return(new UsernamePasswordCredentials()
            {
                Username = creds.Username,
                Password = creds.Password
            });
        }
Пример #16
0
        static Credentials OnHandleCredentials(string url, string usernameFromUrl, SupportedCredentialTypes types)
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            // See https://github.com/microsoft/Git-Credential-Manager-for-Windows/issues/859
            var uri   = new Uri(url);
            var creds = auth.GetCredentials(new TargetUri(uri.GetComponents(UriComponents.Scheme | UriComponents.Host, UriFormat.Unescaped)));

            return(new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password,
            });
        }
Пример #17
0
 public ConfigTemplateModel(SecretStore secrets, Service service)
 {
     Resources = new ConfigObject(
         service
         .Datacenter
         .Resources
         .GroupBy(r => r.Type)
         .ToDictionary(g => g.Key, g => (object)g.ToDictionary(r => r.Name, r => ResolveValue(secrets, service, r))));
     Service  = service;
     Services = new ConfigObject(
         service
         .Datacenter
         .Services
         .ToDictionary(s => s.Name, s => (object)new ServiceModel(s, secrets)));
 }
        public void SetDependencies(string tableName)
        {
            var region = RegionEndpoint.EUWest1;
            var km     = new AwsKmsKeyManager(region);
            var config = new AmazonDynamoDBConfig
            {
                RegionEndpoint = region
            };

            var repo = new AwsDynamoProtectedSecretRepository(config, tableName);
            var em   = new EncryptionManager(km);
            var ss   = new SecretStore(repo, em);

            _secretStore = ss;
            _repo        = repo;
        }
        public void ClientRemovedOnNullSecret()
        {
            var store = new SecretStore();

            store.Assign("client", "A");

            var secret = store.ClientSecret("client");

            Assert.That(secret, Is.EqualTo("A"));

            store.Assign("client", null);

            secret = store.ClientSecret("client");

            Assert.That(secret, Is.Null);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // See https://stackoverflow.com/questions/45695382/how-do-i-setup-multiple-auth-schemes-in-asp-net-core-2-0
            // and https://github.com/aspnet/Security/issues/1469
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme          = "smart";
                sharedOptions.DefaultChallengeScheme = "smart";
            })
            .AddPolicyScheme("smart", "JWT or HMAC", options =>
            {
                options.ForwardDefaultSelector = context =>
                {
                    var authHeader = context.Request.Headers["Authorization"].ToString();
                    if (authHeader?.StartsWith("Bearer") == true)
                    {
                        return(JwtBearerDefaults.AuthenticationScheme);
                    }

                    return(HmacAuthentication.AuthenticationScheme);
                };
            })
            .AddJwtBearer(options =>
            {
                options.Authority = "https://foo.com/";
                options.Audience  = "aud";
            })
            .AddHmacAuthentication(options =>
            {
            });

            services.AddHmacAuthenticator();

            services.AddDistributedMemoryCache();
            services.AddSingleton <ISignatureCache, DistributedSignatureCache>();

            var secretRepository = new SecretStore();

            secretRepository.Assign("1234", "ABCD");
            services.AddSingleton <ISecretRepository>(secretRepository);
            services.AddTransient <IRequestClaimsProvider>(x => new ClientIdRequestClaimsProvider("name"));

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Пример #21
0
        public void FetchLatestGITFiles()
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            var options = new CloneOptions
            {
                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                {
                    Username = "******",
                    Password = "******"
                },
            };

            // Clone everything from https://github.com/alexdaniel1967/TestHarness to C:\Test folder
            Repository.Clone("https://github.com/alexdaniel1967/TestHarness", @"C:\Test", options);
        }
Пример #22
0
        //this option helps to clone a git project to a specific folder
        private void pictureBox5_Click(object sender, EventArgs e)
        {
            //opens git repo in browser
            Process.Start("https://github.com/sajagxD/sajagbugfinder.git");

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            var options = new CloneOptions
            {
                CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials
                {
                    Username = creds.Username,
                    Password = creds.Password
                },
            };

            Repository.Clone("https://github.com/sajagxD/sajagbugfinder.git", @"c:\projects", options);
        }
Пример #23
0
        public ConfigStore(
            bool isDevelopmentEnvironment,
            Func <string, string> confReader,
            ILoggerFactory logFactory)
        {
            Ensure.ArgumentNotNull(logFactory, nameof(logFactory));
            this.logger = logFactory.CreateLogger <ConfigStore>();

            EnvironmentSupport.Dump(this.logger);

            if (isDevelopmentEnvironment)
            {
                Ensure.ArgumentNotNull(confReader, nameof(confReader));
                var message = "API is booting as dev environment.";
                // For now, just warning, in future we will fail in this scenario
                // Environment.FailFast(message);
                logger.LogCritical(message);

                _keyValues = new Dictionary <string, string>
                {
                    { "storage-table-account-name", confReader("StorageConfig:AccountName") },
                    { "storage-table-account-key", confReader("StorageConfig:AccountKey") },
                    { "storage-document-account-endpoint", confReader("StorageConfig:DocumentEndpoint") },
                    { "storage-document-account-key", confReader("StorageConfig:DocumentKey") }
                };
            }
            else
            {
                Console.WriteLine("Creating secret store...");
                _secretStore = new SecretStore(
                    EnvironmentSupport.ClientID,
                    EnvironmentSupport.ClientSecret,
                    EnvironmentSupport.VaultBaseUri,
                    logFactory);
            }
        }
Пример #24
0
        static CredentialsHandler CreateCredentialsHandler(IRepository repo, string remoteName)
        {
            CredentialsHandler retval = null;

            var remote    = repo.Network.Remotes[remoteName];
            var remoteUri = new Uri(remote.Url);

            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);

            var targetUrl = remoteUri.GetLeftPart(UriPartial.Authority);

            //HACK ALERT!! to make this thing play nice with Windows Credentials and how it stores my PATs. YMMV
            if (targetUrl.Contains("dev.azure.com", StringComparison.OrdinalIgnoreCase))
            {
                var url = new Uri(targetUrl);
                if (!string.IsNullOrWhiteSpace(url.UserInfo))
                {
                    targetUrl = url + url.UserInfo;
                }
            }
            //End HACK ALERT!!

            var creds = auth.GetCredentials(new TargetUri(targetUrl));

            if (creds != null)
            {
                retval = (url, user, cred) => new UsernamePasswordCredentials
                {
                    Username = creds.Username,
                    Password = creds.Password
                };
            }

            return(retval);
        }
        static IDictionary <string, string> GetReferences(IRepository repo, string remoteName)
        {
            var secrets = new SecretStore("git");
            var auth    = new BasicAuthentication(secrets);
            var creds   = auth.GetCredentials(new TargetUri("https://github.com"));

            CredentialsHandler credentialsHandler =
                (url, user, cred) => new UsernamePasswordCredentials
            {
                Username = creds.Username,
                Password = creds.Password
            };

            var dictionary = new Dictionary <string, string>();
            var remote     = repo.Network.Remotes[remoteName];
            var refs       = repo.Network.ListReferences(remote, credentialsHandler);

            foreach (var reference in refs)
            {
                dictionary[reference.CanonicalName] = reference.TargetIdentifier;
            }

            return(dictionary);
        }
Пример #26
0
 public AccessController(OneContext context, AuthStore store, SecretStore secretStore)
 {
     Context          = context;
     Store            = store;
     this.secretStore = secretStore;
 }
        internal static LinkerResourceData DeserializeLinkerResourceData(JsonElement element)
        {
            ResourceIdentifier           id                = default;
            string                       name              = default;
            ResourceType                 type              = default;
            SystemData                   systemData        = default;
            Optional <TargetServiceBase> targetService     = default;
            Optional <AuthInfoBase>      authInfo          = default;
            Optional <ClientType>        clientType        = default;
            Optional <string>            provisioningState = default;
            Optional <VnetSolution>      vNetSolution      = default;
            Optional <SecretStore>       secretStore       = default;
            Optional <string>            scope             = default;

            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("id"))
                {
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("systemData"))
                {
                    systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("targetService"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            targetService = TargetServiceBase.DeserializeTargetServiceBase(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("authInfo"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            authInfo = AuthInfoBase.DeserializeAuthInfoBase(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("clientType"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            clientType = new ClientType(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            provisioningState = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("vNetSolution"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                vNetSolution = null;
                                continue;
                            }
                            vNetSolution = VnetSolution.DeserializeVnetSolution(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("secretStore"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                secretStore = null;
                                continue;
                            }
                            secretStore = SecretStore.DeserializeSecretStore(property0.Value);
                            continue;
                        }
                        if (property0.NameEquals("scope"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                scope = null;
                                continue;
                            }
                            scope = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return(new LinkerResourceData(id, name, type, systemData, targetService.Value, authInfo.Value, Optional.ToNullable(clientType), provisioningState.Value, vNetSolution.Value, secretStore.Value, scope.Value));
        }
Пример #28
0
        private static BaseAuthentication CreateAuthentication(OperationArguments operationArguments)
        {
            Debug.Assert(operationArguments != null, "The operationArguments is null");

            Trace.WriteLine("Program::CreateAuthentication");

            var secrets = new SecretStore(SecretsNamespace);
            BaseAuthentication authority = null;

            switch (operationArguments.Authority)
            {
            case AuthorityType.Auto:
                Trace.WriteLine("   detecting authority type");

                // detect the authority
                if (BaseVsoAuthentication.GetAuthentication(operationArguments.TargetUri,
                                                            VsoCredentialScope,
                                                            secrets,
                                                            null,
                                                            out authority) ||
                    GithubAuthentication.GetAuthentication(operationArguments.TargetUri,
                                                           GithubCredentialScope,
                                                           secrets,
                                                           out authority))
                {
                    // set the authority type based on the returned value
                    if (authority is VsoMsaAuthentication)
                    {
                        operationArguments.Authority = AuthorityType.MicrosoftAccount;
                        goto case AuthorityType.MicrosoftAccount;
                    }
                    else if (authority is VsoAadAuthentication)
                    {
                        operationArguments.Authority = AuthorityType.AzureDirectory;
                        goto case AuthorityType.AzureDirectory;
                    }
                    else if (authority is GithubAuthentication)
                    {
                        operationArguments.Authority = AuthorityType.GitHub;
                        goto case AuthorityType.GitHub;
                    }
                }

                operationArguments.Authority = AuthorityType.Basic;
                goto case AuthorityType.Basic;

            case AuthorityType.AzureDirectory:
                Trace.WriteLine("   authority is Azure Directory");

                Guid tenantId = Guid.Empty;
                // return the allocated authority or a generic AAD backed VSO authentication object
                return(authority ?? new VsoAadAuthentication(Guid.Empty, VsoCredentialScope, secrets));

            case AuthorityType.Basic:
            default:
                Trace.WriteLine("   authority is basic");

                // return a generic username + password authentication object
                return(authority ?? new BasicAuthentication(secrets));

            case AuthorityType.GitHub:
                Trace.WriteLine("    authority it GitHub");

                // return a GitHub authenitcation object
                return(authority ?? new GithubAuthentication(GithubCredentialScope, secrets));

            case AuthorityType.MicrosoftAccount:
                Trace.WriteLine("   authority is Microsoft Live");

                // return the allocated authority or a generic MSA backed VSO authentication object
                return(authority ?? new VsoMsaAuthentication(VsoCredentialScope, secrets));
            }
        }
Пример #29
0
        public static async Task <BaseAuthentication> CreateAuthentication(Program program, OperationArguments operationArguments)
        {
            if (operationArguments is null)
            {
                throw new ArgumentNullException(nameof(operationArguments));
            }
            if (operationArguments.TargetUri is null)
            {
                var innerException = new NullReferenceException($"`{operationArguments.TargetUri}` cannot be null.");
                throw new ArgumentException(innerException.Message, nameof(operationArguments), innerException);
            }

            var secretsNamespace         = operationArguments.CustomNamespace ?? Program.SecretsNamespace;
            var secrets                  = new SecretStore(secretsNamespace, null, null, Secret.UriToName);
            BaseAuthentication authority = null;

            var basicCredentialCallback = (operationArguments.UseModalUi)
                    ? new AcquireCredentialsDelegate(program.ModalPromptForCredentials)
                    : new AcquireCredentialsDelegate(program.BasicCredentialPrompt);

            var bitbucketCredentialCallback = (operationArguments.UseModalUi)
                    ? Bitbucket.AuthenticationPrompts.CredentialModalPrompt
                    : new Bitbucket.Authentication.AcquireCredentialsDelegate(program.BitbucketCredentialPrompt);

            var bitbucketOauthCallback = (operationArguments.UseModalUi)
                    ? Bitbucket.AuthenticationPrompts.AuthenticationOAuthModalPrompt
                    : new Bitbucket.Authentication.AcquireAuthenticationOAuthDelegate(program.BitbucketOAuthPrompt);

            var githubCredentialCallback = (operationArguments.UseModalUi)
                    ? new Github.Authentication.AcquireCredentialsDelegate(Github.AuthenticationPrompts.CredentialModalPrompt)
                    : new Github.Authentication.AcquireCredentialsDelegate(program.GitHubCredentialPrompt);

            var githubAuthcodeCallback = (operationArguments.UseModalUi)
                    ? new Github.Authentication.AcquireAuthenticationCodeDelegate(Github.AuthenticationPrompts.AuthenticationCodeModalPrompt)
                    : new Github.Authentication.AcquireAuthenticationCodeDelegate(program.GitHubAuthCodePrompt);

            NtlmSupport basicNtlmSupport = NtlmSupport.Auto;

            ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;

            switch (operationArguments.Authority)
            {
            case AuthorityType.Auto:
                Git.Trace.WriteLine($"detecting authority type for '{operationArguments.TargetUri}'.");

                // Detect the authority.
                authority = await BaseVstsAuthentication.GetAuthentication(operationArguments.TargetUri,
                                                                           Program.VstsCredentialScope,
                                                                           secrets)
                            ?? Github.Authentication.GetAuthentication(operationArguments.TargetUri,
                                                                       Program.GitHubCredentialScope,
                                                                       secrets,
                                                                       githubCredentialCallback,
                                                                       githubAuthcodeCallback,
                                                                       null)
                            ?? Bitbucket.Authentication.GetAuthentication(operationArguments.TargetUri,
                                                                          new SecretStore(secretsNamespace, Secret.UriToActualUrl),
                                                                          bitbucketCredentialCallback,
                                                                          bitbucketOauthCallback);

                if (authority != null)
                {
                    // Set the authority type based on the returned value.
                    if (authority is VstsMsaAuthentication)
                    {
                        operationArguments.Authority = AuthorityType.MicrosoftAccount;
                        goto case AuthorityType.MicrosoftAccount;
                    }
                    else if (authority is VstsAadAuthentication)
                    {
                        operationArguments.Authority = AuthorityType.AzureDirectory;
                        goto case AuthorityType.AzureDirectory;
                    }
                    else if (authority is Github.Authentication)
                    {
                        operationArguments.Authority = AuthorityType.GitHub;
                        goto case AuthorityType.GitHub;
                    }
                    else if (authority is Bitbucket.Authentication)
                    {
                        operationArguments.Authority = AuthorityType.Bitbucket;
                        goto case AuthorityType.Bitbucket;
                    }
                }
                goto default;

            case AuthorityType.AzureDirectory:
                Git.Trace.WriteLine($"authority for '{operationArguments.TargetUri}' is Azure Directory.");

                Guid tenantId = Guid.Empty;

                // Get the identity of the tenant.
                var result = await BaseVstsAuthentication.DetectAuthority(operationArguments.TargetUri);

                if (result.Key)
                {
                    tenantId = result.Value;
                }

                // Return the allocated authority or a generic AAD backed VSTS authentication object.
                return(authority ?? new VstsAadAuthentication(tenantId, Program.VstsCredentialScope, secrets));

            case AuthorityType.Basic:
                // Enforce basic authentication only.
                basicNtlmSupport = NtlmSupport.Never;
                goto default;

            case AuthorityType.GitHub:
                Git.Trace.WriteLine($"authority for '{operationArguments.TargetUri}' is GitHub.");

                // Return a GitHub authentication object.
                return(authority ?? new Github.Authentication(operationArguments.TargetUri,
                                                              Program.GitHubCredentialScope,
                                                              secrets,
                                                              githubCredentialCallback,
                                                              githubAuthcodeCallback,
                                                              null));

            case AuthorityType.Bitbucket:
                Git.Trace.WriteLine($"authority for '{operationArguments.TargetUri}'  is Bitbucket");

                // Return a Bitbucket authentication object.
                return(authority ?? new Bitbucket.Authentication(secrets,
                                                                 bitbucketCredentialCallback,
                                                                 bitbucketOauthCallback));

            case AuthorityType.MicrosoftAccount:
                Git.Trace.WriteLine($"authority for '{operationArguments.TargetUri}' is Microsoft Live.");

                // Return the allocated authority or a generic MSA backed VSTS authentication object.
                return(authority ?? new VstsMsaAuthentication(Program.VstsCredentialScope, secrets));

            case AuthorityType.Ntlm:
                // Enforce NTLM authentication only.
                basicNtlmSupport = NtlmSupport.Always;
                goto default;

            default:
                Git.Trace.WriteLine($"authority for '{operationArguments.TargetUri}' is basic with NTLM={basicNtlmSupport}.");

                // Return a generic username + password authentication object.
                return(authority ?? new BasicAuthentication(secrets, basicNtlmSupport, basicCredentialCallback, null));
            }
        }
Пример #30
0
        private void LogInButton_Click(object sender, EventArgs e)
        {
            gitHubCredentials = new UsernamePasswordCredentials()
            {
                Username = gitHubUsernameTextBox.Text,
                Password = gitHubPasswordTextBox.Text
            };


            // Setup GitHub authentication
            SecretStore         gitSecretStore   = new SecretStore("git");
            BasicAuthentication authType         = new BasicAuthentication(gitSecretStore);
            Credential          userCredentials  = authType.GetCredentials(new TargetUri("https://github.com"));
            CloneOptions        credCloneOptions = new CloneOptions
            {
                OnTransferProgress = cloneProgress =>
                {
                    var clonePercentage = (100 * cloneProgress.ReceivedObjects) / cloneProgress.TotalObjects;
                    cloneProgressBar.Invoke(new Action(() => cloneProgressBar.Value = clonePercentage));
                    return(true);
                },
                CredentialsProvider = (_url, _user, _cred) => gitHubCredentials,
            };

            // Try to authenticate, notify the user if there's an error
            try
            {
                // Clone the repo and close the form
                // We also want to nullify all credential objects to respect the user's privacy
                // This should make the memory "out of scope" in the eyes of the garbage collector

                // Extract the repo name from the URL, then combine it with the path to make the full path
                string[] repoSplit    = projectURL.Trim().Split('/');
                string   repoName     = repoSplit[repoSplit.Length - 1].Split('.')[0];
                string   combinedPath = Path.Combine(pathToClone, repoName);


                Repository.Clone(projectURL, combinedPath, credCloneOptions);

                userCredentials  = null;
                credCloneOptions = null;

                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Repository cloned successfully! Closing login form.", "Cloned Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);
                })).Start();

                this.Close();
            }
            catch (LibGit2Sharp.NameConflictException)
            {
                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Failed to clone the repo. Directory already exists with that name.", "Cloning Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                })).Start();
            }
            catch (LibGit2Sharp.LibGit2SharpException)
            {
                new Thread(new ThreadStart(delegate
                {
                    MessageBox.Show("Failed to clone the repo. Please check your internet connection or credentials.", "Cloning Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                })).Start();
            }
        }
 public void GetCalled()
 {
     _returnedSecret = SecretStore.Get(clearSecret.ApplicationName, clearSecret.Name);
 }
 public ResourceResolutionContext(SecretStore secrets, Service service, Resource resource)
 {
     Secrets  = secrets;
     Service  = service;
     Resource = resource;
 }