public OAuthViewModel(IEnvironment environment)
        {
            EnsureArgument.NotNull(environment, nameof(environment));

            _environment = environment;

            Title                 = "OAuth authentication required";
            OkCommand             = new RelayCommand(Accept);
            CancelCommand         = new RelayCommand(Cancel);
            LearnMoreCommand      = new RelayCommand(LearnMore);
            ForgotPasswordCommand = new RelayCommand(ForgotPassword);
            SignUpCommand         = new RelayCommand(SignUp);
        }
Example #2
0
        public CredentialsViewModel(IEnvironment environment)
        {
            EnsureArgument.NotNull(environment, nameof(environment));

            _environment = environment;

            Title                 = "Connect to Bitbucket";
            LoginCommand          = new RelayCommand(Accept, CanLogin);
            CancelCommand         = new RelayCommand(Cancel);
            ForgotPasswordCommand = new RelayCommand(ForgotPassword);
            SignUpCommand         = new RelayCommand(SignUp);

            PropertyChanged += OnPropertyChanged;
        }
Example #3
0
        public static IMemoryCache SetUpCacheEntryGet(this IMemoryCache mockedMemoryCache, object cacheEntryKey, object cacheEntryValue)
        {
            EnsureArgument.IsNotNull(mockedMemoryCache, nameof(mockedMemoryCache));
            EnsureArgument.IsNotNull(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug($"Setting up cache entry Get for '{cacheEntryKey}'");

            Mock.Get(mockedMemoryCache)
            .Setup(m => m.TryGetValue(It.Is <object>(k => k.Equals(cacheEntryKey)), out cacheEntryValue))
            .Callback(() => Logger.LogDebug("Cache TryGetValue invoked"))
            .Returns(true);

            return(mockedMemoryCache);
        }
Example #4
0
        public CredentialsViewModel(IEnvironment environment)
        {
            EnsureArgument.NotNull(environment, nameof(environment));

            _environment = environment;

            Title                = "Connect to GitLab";
            SignUpCommand        = new RelayCommand(SignUp);
            SignInBrowserCommand = new RelayCommand(SignInBrowser);
            SignInTokenCommand   = new RelayCommand(SignInToken, CanSignInToken);
            SignInBasicCommand   = new RelayCommand(SignInBasic, CanSignInBasic);

            PropertyChanged += OnPropertyChanged;
        }
Example #5
0
        public LinuxCredentialStore(IFileSystem fileSystem, ISettings settings, ISessionManager sessionManager, IGpg gpg, IEnvironment environment)
        {
            EnsureArgument.NotNull(fileSystem, nameof(fileSystem));
            EnsureArgument.NotNull(settings, nameof(settings));
            EnsureArgument.NotNull(sessionManager, nameof(sessionManager));
            EnsureArgument.NotNull(gpg, nameof(gpg));
            EnsureArgument.NotNull(environment, nameof(environment));

            _fileSystem     = fileSystem;
            _settings       = settings;
            _sessionManager = sessionManager;
            _gpg            = gpg;
            _environment    = environment;
        }
        internal static IAppCache SetUpCacheEntry <T>(this IAppCache mockedCachingService, string cacheEntryKey, T cacheEntryValue)
        {
            EnsureArgument.IsNotNull(mockedCachingService, nameof(mockedCachingService));
            EnsureArgument.IsNotNullOrEmpty(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug("Setting up cache entry for '{cacheEntryKey}' (type: '{type}'; value: '{cacheEntryValue}')", cacheEntryKey, typeof(T), cacheEntryValue);

            mockedCachingService.SetUpCacheEntryAdd <T>(cacheEntryKey);

            mockedCachingService.SetUpCacheEntryGet(cacheEntryKey, cacheEntryValue);

            mockedCachingService.SetUpCacheEntryRemove <T>(cacheEntryKey);

            return(mockedCachingService);
        }
        public string GetAuthority(string orgName)
        {
            EnsureArgument.NotNullOrWhiteSpace(orgName, nameof(orgName));

            _trace.WriteLine($"Looking up cached authority for organization '{orgName}'...");

            IGitConfiguration config = _git.GetConfiguration();

            if (config.TryGet(GitConfigurationLevel.Global, GetAuthorityKey(orgName), out string authority))
            {
                return(authority);
            }

            return(null);
        }
        public async Task <string> CreatePersonalAccessTokenAsync(Uri organizationUri, JsonWebToken accessToken, IEnumerable <string> scopes)
        {
            const string sessionTokenUrl = "_apis/token/sessiontokens?api-version=1.0&tokentype=compact";

            EnsureArgument.AbsoluteUri(organizationUri, nameof(organizationUri));
            if (!UriHelpers.IsAzureDevOpsHost(organizationUri.Host))
            {
                throw new ArgumentException($"Provided URI '{organizationUri}' is not a valid Azure DevOps hostname", nameof(organizationUri));
            }
            EnsureArgument.NotNull(accessToken, nameof(accessToken));

            _context.Trace.WriteLine("Getting Azure DevOps Identity Service endpoint...");
            Uri identityServiceUri = await GetIdentityServiceUriAsync(organizationUri, accessToken);

            _context.Trace.WriteLine($"Identity Service endpoint is '{identityServiceUri}'.");

            Uri requestUri = new Uri(identityServiceUri, sessionTokenUrl);

            _context.Trace.WriteLine($"HTTP: POST {requestUri}");
            using (StringContent content = CreateAccessTokenRequestJson(organizationUri, scopes))
                using (HttpRequestMessage request = CreateRequestMessage(HttpMethod.Post, requestUri, content, accessToken))
                    using (HttpResponseMessage response = await HttpClient.SendAsync(request))
                    {
                        _context.Trace.WriteLine($"HTTP: Response {(int)response.StatusCode} [{response.StatusCode}]");

                        string responseText = await response.Content.ReadAsStringAsync();

                        if (!string.IsNullOrWhiteSpace(responseText))
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                if (TryGetFirstJsonStringField(responseText, "token", out string token))
                                {
                                    return(token);
                                }
                            }
                            else
                            {
                                if (TryGetFirstJsonStringField(responseText, "message", out string errorMessage))
                                {
                                    throw new Exception($"Failed to create PAT: {errorMessage}");
                                }
                            }
                        }
                    }

            throw new Exception("Failed to create PAT");
        }
Example #9
0
        internal static IAppCache SetUpCacheEntryRemove <T>(this IAppCache mockedCachingService, string cacheEntryKey)
        {
            EnsureArgument.IsNotNull(mockedCachingService, nameof(mockedCachingService));
            EnsureArgument.IsNotNullOrEmpty(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug("Setting up cache entry Remove for '{cacheEntryKey}'", cacheEntryKey);

            mockedCachingService.When(x => x.Remove(Arg.Is <string>(s => s.Equals(cacheEntryKey))))
            .Do(x =>
            {
                Logger.LogDebug("Cache Remove invoked");
                ProjectReflectionShortcuts.SetUpCacheEntryGetMethod(typeof(T)).Invoke(null, new object[] { mockedCachingService, cacheEntryKey, default(T) });
            });

            return(mockedCachingService);
        }
        public static IMemoryCache SetUpCacheEntryRemove(this IMemoryCache mockedMemoryCache, object cacheEntryKey, object defaultValue)
        {
            EnsureArgument.IsNotNull(mockedMemoryCache, nameof(mockedMemoryCache));
            EnsureArgument.IsNotNull(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug($"Setting up cache entry Remove for '{cacheEntryKey}' (default value: {defaultValue})");

            mockedMemoryCache.When(x => x.Remove(Arg.Is <object>(k => k.Equals(cacheEntryKey))))
            .Do(x =>
            {
                Logger.LogDebug("Cache Remove invoked");
                mockedMemoryCache.SetUpCacheEntryGet(cacheEntryKey, defaultValue);
            });

            return(mockedMemoryCache);
        }
        public ICredential GetCredentials(string resource, string userName)
        {
            EnsureArgument.NotNullOrWhiteSpace(resource, nameof(resource));

            ThrowIfUserInteractionDisabled();

            // TODO: we only support system GUI prompts on Windows currently
            if (Context.SessionManager.IsDesktopSession && PlatformUtils.IsWindows())
            {
                return(GetCredentialsByUi(resource, userName));
            }

            ThrowIfTerminalPromptsDisabled();

            return(GetCredentialsByTty(resource, userName));
        }
        public AzureReposHostProvider(ICommandContext context, IAzureDevOpsRestApi azDevOps,
                                      IMicrosoftAuthentication msAuth, IAzureDevOpsAuthorityCache authorityCache,
                                      IAzureReposBindingManager bindingManager)
        {
            EnsureArgument.NotNull(context, nameof(context));
            EnsureArgument.NotNull(azDevOps, nameof(azDevOps));
            EnsureArgument.NotNull(msAuth, nameof(msAuth));
            EnsureArgument.NotNull(authorityCache, nameof(authorityCache));
            EnsureArgument.NotNull(bindingManager, nameof(bindingManager));

            _context        = context;
            _azDevOps       = azDevOps;
            _msAuth         = msAuth;
            _authorityCache = authorityCache;
            _bindingManager = bindingManager;
        }
Example #13
0
        internal static IAppCache SetUpCacheEntryGet <T>(this IAppCache mockedCachingService, string cacheEntryKey, T cacheEntryValue)
        {
            EnsureArgument.IsNotNull(mockedCachingService, nameof(mockedCachingService));
            EnsureArgument.IsNotNullOrEmpty(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug("Setting up cache entry Get/GetOrAdd for '{cacheEntryKey}' (type: '{type}'; value: '{cacheEntryValue}')", cacheEntryKey, typeof(T), cacheEntryValue);

            mockedCachingService.Get <T>(Arg.Is <string>(s => s.Equals(cacheEntryKey))).Returns(cacheEntryValue).AndDoes(x => Logger.LogDebug("Cache Get invoked"));

            mockedCachingService.GetOrAdd(Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, T> >())
            .Returns(cacheEntryValue)
            .AndDoes(x => Logger.LogDebug("Cache GetOrAdd invoked"));

            //Backwards compatibility
            if (ProjectReflectionShortcuts.GetOrAddWithMemoryCacheEntryOptionsMethod != null)
            {
                Logger.LogDebug("Setting up GetOrAddWithMemoryCacheEntryOptionsMethod");

                ProjectReflectionShortcuts.GetOrAddWithMemoryCacheEntryOptionsMethod.MakeGenericMethod(typeof(T))
                .Invoke(mockedCachingService.Configure(),
                        new object[] { Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, T> >(), Arg.Any <MemoryCacheEntryOptions>() })
                .Returns(cacheEntryValue)
                .AndDoes(x => Logger.LogDebug("Cache GetOrAdd invoked"));
            }

            mockedCachingService.GetAsync <T>(Arg.Is <string>(s => s.Equals(cacheEntryKey)))
            .Returns(Task.FromResult(cacheEntryValue))
            .AndDoes(x => Logger.LogDebug("Cache GetAsync invoked"));

            mockedCachingService.GetOrAddAsync(Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, Task <T> > >())
            .Returns(Task.FromResult(cacheEntryValue))
            .AndDoes(x => Logger.LogDebug("Cache GetOrAddAsync invoked"));

            //Backwards compatibility
            if (ProjectReflectionShortcuts.GetOrAddAsyncWithMemoryCacheEntryOptionsMethod != null)
            {
                Logger.LogDebug("Setting up GetOrAddAsyncWithMemoryCacheEntryOptionsMethod");

                ProjectReflectionShortcuts.GetOrAddAsyncWithMemoryCacheEntryOptionsMethod.MakeGenericMethod(typeof(T))
                .Invoke(mockedCachingService.Configure(),
                        new object[] { Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <Func <ICacheEntry, Task <T> > >(), Arg.Any <MemoryCacheEntryOptions>() })
                .Returns(Task.FromResult(cacheEntryValue))
                .AndDoes(x => Logger.LogDebug("Cache GetOrAddAsync invoked"));
            }

            return(mockedCachingService);
        }
        private static bool SqlMatchesFromSqlExpression(string sql, FromSqlQueryRootExpression expression)
        {
            EnsureArgument.IsNotNull(expression, nameof(expression));

            var expressionSql = expression.Sql;
            var parts         = new List <string>();

            parts.Add($"Invocation sql: '{expressionSql}'");
            parts.Add($"Set up sql: '{sql}'");
            Logger.LogDebug(string.Join(Environment.NewLine, parts));

            var result = expressionSql.Contains(sql, StringComparison.OrdinalIgnoreCase);

            Logger.LogDebug("Match? {result}", result);

            return(result);
        }
        public static IMemoryCache SetUpCacheEntryGet(this IMemoryCache mockedMemoryCache, object cacheEntryKey, object cacheEntryValue)
        {
            EnsureArgument.IsNotNull(mockedMemoryCache, nameof(mockedMemoryCache));
            EnsureArgument.IsNotNull(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug($"Setting up cache entry Get for '{cacheEntryKey}'");

            mockedMemoryCache.TryGetValue(Arg.Is <object>(k => k.Equals(cacheEntryKey)), out Arg.Any <object>())
            .Returns(x =>
            {
                x[1] = cacheEntryValue;
                return(true);
            })
            .AndDoes(x => Logger.LogDebug("Cache TryGetValue invoked"));

            return(mockedMemoryCache);
        }
        internal static IAppCache SetUpCacheEntryAdd <T>(this IAppCache mockedCachingService, string cacheEntryKey)
        {
            EnsureArgument.IsNotNull(mockedCachingService, nameof(mockedCachingService));
            EnsureArgument.IsNotNullOrEmpty(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug("Setting up cache entry Add for '{cacheEntryKey}'", cacheEntryKey);

            Mock.Get(mockedCachingService)
            .Setup(m => m.Add(It.Is <string>(s => s.Equals(cacheEntryKey)), It.IsAny <T>(), It.IsAny <MemoryCacheEntryOptions>()))
            .Callback((string key, T item, MemoryCacheEntryOptions providedPolicy) =>
            {
                Logger.LogDebug("Cache Add invoked");
                mockedCachingService.SetUpCacheEntryGet(key, item);
            });

            return(mockedCachingService);
        }
Example #17
0
        /// <summary>
        ///     Sets up ExecuteSqlRaw invocations containing a specified sql string and parameters to return a specified result.
        /// </summary>
        /// <typeparam name="TDbContext">The db context type.</typeparam>
        /// <param name="mockedDbContext">The mocked db context.</param>
        /// <param name="sql">The ExecuteSqlRaw sql string. Set up supports case insensitive partial matches.</param>
        /// <param name="parameters">The ExecuteSqlRaw parameters. Set up supports case insensitive partial parameter sequence matching.</param>
        /// <param name="executeSqlRawResult">The integer to return when ExecuteSqlRaw is invoked.</param>
        /// <param name="callback">Operations to perform after ExecuteSqlCommand is invoked.</param>
        /// <returns>The mocked db context.</returns>
        public static TDbContext AddExecuteSqlRawResult <TDbContext>(
            this TDbContext mockedDbContext, string sql, IEnumerable <object> parameters, int executeSqlRawResult, Action <string, IEnumerable <object> > callback = null)
            where TDbContext : DbContext
        {
            EnsureArgument.IsNotNull(mockedDbContext, nameof(mockedDbContext));
            EnsureArgument.IsNotNull(sql, nameof(sql));
            EnsureArgument.IsNotNull(parameters, nameof(parameters));

            var relationalCommandMock = new Mock <IRelationalCommand>();

            relationalCommandMock.Setup(m => m.ExecuteNonQuery(It.IsAny <RelationalCommandParameterObject>()))
            .Returns((RelationalCommandParameterObject providedRelationalCommandParameterObject) => executeSqlRawResult);

            relationalCommandMock.Setup(m => m.ExecuteNonQueryAsync(It.IsAny <RelationalCommandParameterObject>(), It.IsAny <CancellationToken>()))
            .Returns((RelationalCommandParameterObject providedRelationalCommandParameterObject, CancellationToken providedCancellationToken) =>
                     Task.FromResult(executeSqlRawResult));
            var relationalCommand = relationalCommandMock.Object;

            var rawSqlCommandMock = new Mock <RawSqlCommand>(relationalCommand, new Dictionary <string, object>());

            rawSqlCommandMock.Setup(m => m.RelationalCommand).Returns(() => relationalCommand);
            rawSqlCommandMock.Setup(m => m.ParameterValues).Returns(() => new Dictionary <string, object>());
            var rawSqlCommand = rawSqlCommandMock.Object;

            var existingRawSqlCommandBuilder =
                ((IRelationalDatabaseFacadeDependencies)((IInfrastructure <IServiceProvider>)mockedDbContext).Instance.GetService(typeof(IDatabaseFacadeDependencies)))
                .RawSqlCommandBuilder;

            Mock.Get(existingRawSqlCommandBuilder)
            .Setup(m => m.Build(It.Is <string>(s => s.Contains(sql, StringComparison.OrdinalIgnoreCase)),
                                It.Is <IEnumerable <object> >(p => ParameterMatchingHelper.DoInvocationParametersMatchSetUpParameters(parameters, p))))
            .Returns((string providedSql, IEnumerable <object> providedParameters) => rawSqlCommand)
            .Callback((string providedSql, IEnumerable <object> providedParameters) =>
            {
                callback?.Invoke(providedSql, providedParameters);

                var parts = new List <string>();
                parts.Add($"Invocation sql: {providedSql}");
                parts.Add("Invocation Parameters:");
                parts.Add(ParameterMatchingHelper.StringifyParameters(providedParameters));
                Logger.LogDebug(string.Join(Environment.NewLine, parts));
            });

            return(mockedDbContext);
        }
        public async Task <AuthenticationResult> AcquireTokenAsync(Uri targetUri, string username, string password, string authenticationCode, IEnumerable <string> scopes)
        {
            EnsureArgument.AbsoluteUri(targetUri, nameof(targetUri));
            EnsureArgument.NotNull(scopes, nameof(scopes));

            string base64Cred = new GitCredential(username, password).ToBase64String();

            Uri requestUri = GetAuthenticationRequestUri(targetUri);

            _context.Trace.WriteLine($"HTTP: POST {requestUri}");
            using (HttpContent content = GetTokenJsonContent(targetUri, scopes))
                using (var request = new HttpRequestMessage(HttpMethod.Post, requestUri))
                {
                    // Set the request content as well as auth and 2FA headers
                    request.Content = content;
                    request.Headers.Authorization = new AuthenticationHeaderValue(Constants.Http.WwwAuthenticateBasicScheme, base64Cred);
                    if (!string.IsNullOrWhiteSpace(authenticationCode))
                    {
                        request.Headers.Add(GitHubConstants.GitHubOptHeader, authenticationCode);
                    }

                    // Send the request!
                    using (HttpResponseMessage response = await HttpClient.SendAsync(request))
                    {
                        _context.Trace.WriteLine($"HTTP: Response {(int) response.StatusCode} [{response.StatusCode}]");

                        switch (response.StatusCode)
                        {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Created:
                            return(await ParseSuccessResponseAsync(targetUri, response));

                        case HttpStatusCode.Unauthorized:
                            return(ParseUnauthorizedResponse(targetUri, authenticationCode, response));

                        case HttpStatusCode.Forbidden:
                            return(await ParseForbiddenResponseAsync(targetUri, password, response));

                        default:
                            _context.Trace.WriteLine($"Authentication failed for '{targetUri}'.");
                            return(new AuthenticationResult(GitHubAuthenticationResultType.Failure));
                        }
                    }
                }
        }
Example #19
0
        public AzureReposBinding GetBinding(string orgName)
        {
            EnsureArgument.NotNullOrWhiteSpace(orgName, nameof(orgName));

            string orgKey = GetOrgUserKey(orgName);

            IGitConfiguration config = _git.GetConfiguration();

            _trace.WriteLine($"Looking up organization binding for '{orgName}'...");

            // NOT using the short-circuiting OR operator here on purpose - we need both branches to be evaluated
            if (config.TryGet(GitConfigurationLevel.Local, orgKey, out string localUser) |
                config.TryGet(GitConfigurationLevel.Global, orgKey, out string globalUser))
            {
                return(new AzureReposBinding(orgName, globalUser, localUser));
            }

            // No bound user
            return(null);
        }
Example #20
0
        internal static void SetSource <TEntity>(this DbSet <TEntity> mockedReadOnlyDbSet, IEnumerable <TEntity> source) where TEntity : class
        {
            EnsureArgument.IsNotNull(mockedReadOnlyDbSet, nameof(mockedReadOnlyDbSet));
            EnsureArgument.IsNotNull(source, nameof(source));

            var asyncEnumerable     = new AsyncEnumerable <TEntity>(source, new FakeQueryRootExpression(Substitute.For <IAsyncQueryProvider>(), mockedReadOnlyDbSet.EntityType));
            var mockedQueryProvider = ((IQueryable <TEntity>)mockedReadOnlyDbSet).Provider;

            ((IQueryable <TEntity>)mockedReadOnlyDbSet).Expression.Returns(callInfo => asyncEnumerable.Expression);

            ((IAsyncEnumerable <TEntity>)mockedReadOnlyDbSet).GetAsyncEnumerator(Arg.Any <CancellationToken>())
            .Returns(callInfo => asyncEnumerable.GetAsyncEnumerator(callInfo.Arg <CancellationToken>()));

            ((IEnumerable)mockedReadOnlyDbSet).GetEnumerator().Returns(callInfo => ((IEnumerable)asyncEnumerable).GetEnumerator());
            ((IEnumerable <TEntity>)mockedReadOnlyDbSet).GetEnumerator().Returns(callInfo => ((IEnumerable <TEntity>)asyncEnumerable).GetEnumerator());

            ((IListSource)mockedReadOnlyDbSet).GetList().Returns(callInfo => asyncEnumerable.ToList());

            mockedReadOnlyDbSet.AsAsyncEnumerable().Returns(callInfo => asyncEnumerable);
            mockedReadOnlyDbSet.AsQueryable().Returns(callInfo => asyncEnumerable);

            ((AsyncQueryProvider <TEntity>)mockedQueryProvider).SetSource(asyncEnumerable);
        }
        public DiagnoseCommand(ICommandContext context)
            : base("diagnose", "Run diagnostics and gather logs to diagnose problems with Git Credential Manager")
        {
            EnsureArgument.NotNull(context, nameof(context));

            _context     = context;
            _diagnostics = new List <IDiagnostic>
            {
                // Add standard diagnostics
                new EnvironmentDiagnostic(context.Environment),
                new FileSystemDiagnostic(context.FileSystem),
                new NetworkingDiagnostic(context.HttpClientFactory),
                new GitDiagnostic(context.Git),
                new CredentialStoreDiagnostic(context.CredentialStore),
                new MicrosoftAuthenticationDiagnostic(context)
            };

            AddOption(
                new Option <string>(new [] { "--output", "-o" }, "Output directory for diagnostic logs.")
                );

            Handler = CommandHandler.Create <string>(ExecuteAsync);
        }
Example #22
0
        internal static IAppCache SetUpCacheEntryAdd <T>(this IAppCache mockedCachingService, string cacheEntryKey)
        {
            EnsureArgument.IsNotNull(mockedCachingService, nameof(mockedCachingService));
            EnsureArgument.IsNotNullOrEmpty(cacheEntryKey, nameof(cacheEntryKey));

            Logger.LogDebug("Setting up cache entry Add for '{cacheEntryKey}'", cacheEntryKey);

            mockedCachingService.When(x => x.Add(Arg.Is <string>(s => s.Equals(cacheEntryKey)), Arg.Any <T>(), Arg.Any <MemoryCacheEntryOptions>()))
            .Do(x =>
            {
                Logger.LogDebug("Cache Add invoked");

                //x provides the args as objects; this means we have to use reflection to set the item type for the SetUpCacheEntryGet method
                var args = x.Args();

                var key   = args[0].ToString();
                var value = args[1];

                ProjectReflectionShortcuts.SetUpCacheEntryGetMethod(value.GetType()).Invoke(null, new[] { mockedCachingService, key, value });
            });

            return(mockedCachingService);
        }
        /// <summary>
        /// Marks a user as 'signed in' to an Azure DevOps organization.
        /// </summary>
        /// <param name="bindingManager">Binding manager.</param>
        /// <param name="orgName">Organization name.</param>
        /// <param name="userName">User identifier to bind to this organization.</param>
        public static void SignIn(this IAzureReposBindingManager bindingManager, string orgName, string userName)
        {
            EnsureArgument.NotNullOrWhiteSpace(orgName, nameof(orgName));
            EnsureArgument.NotNullOrWhiteSpace(userName, nameof(userName));

            //
            // Try to bind the user to the organization.
            //
            //   A = User to sign-in
            //   B = Another user
            //   - = No user
            //
            //  Global | Local | -> | Global | Local
            // --------|-------|----|--------|-------
            //    -    |   -   | -> |   A    |   -
            //    -    |   A   | -> |   A    |   -
            //    -    |   B   | -> |   A    |   -
            //    A    |   -   | -> |   A    |   -
            //    A    |   A   | -> |   A    |   -
            //    A    |   B   | -> |   A    |   -
            //    B    |   -   | -> |   B    |   A
            //    B    |   A   | -> |   B    |   A
            //    B    |   B   | -> |   B    |   A
            //
            AzureReposBinding existingBinding = bindingManager.GetBinding(orgName);

            if (existingBinding?.GlobalUserName != null &&
                !StringComparer.OrdinalIgnoreCase.Equals(existingBinding.GlobalUserName, userName))
            {
                bindingManager.Bind(orgName, userName, local: true);
            }
            else
            {
                bindingManager.Bind(orgName, userName, local: false);
                bindingManager.Unbind(orgName, local: true);
            }
        }
        public GitCredential GetCredentials(string resource, string userName)
        {
            EnsureArgument.NotNullOrWhiteSpace(resource, nameof(resource));

            EnsureTerminalPromptsEnabled();

            Context.Terminal.WriteLine("Enter basic credentials for '{0}':", resource);

            if (!string.IsNullOrWhiteSpace(userName))
            {
                // Don't need to prompt for the username if it has been specified already
                Context.Terminal.WriteLine("Username: {0}", userName);
            }
            else
            {
                // Prompt for username
                userName = Context.Terminal.Prompt("Username");
            }

            // Prompt for password
            string password = Context.Terminal.PromptSecret("Password");

            return(new GitCredential(userName, password));
        }
Example #25
0
            public MsalHttpClientFactoryAdaptor(IHttpClientFactory factory)
            {
                EnsureArgument.NotNull(factory, nameof(factory));

                _factory = factory;
            }
 public void EnsureArgument_InRange_ThrowsException(int x, int lower, int upper, bool lowerInc, bool upperInc)
 {
     Assert.Throws <ArgumentOutOfRangeException>(
         () => EnsureArgument.InRange(x, nameof(x), lower, upper, lowerInc, upperInc)
         );
 }
 public void EnsureArgument_InRange_DoesNotThrow(int x, int lower, int upper, bool lowerInc, bool upperInc)
 {
     EnsureArgument.InRange(x, nameof(x), lower, upper, lowerInc, upperInc);
 }
 internal WindowsEnvironment(IFileSystem fileSystem, IReadOnlyDictionary <string, string> variables)
     : base(fileSystem)
 {
     EnsureArgument.NotNull(variables, nameof(variables));
     Variables = variables;
 }
 /// <summary>
 ///     Removes all items from the mocked readonly db set source.
 /// </summary>
 /// <typeparam name="TEntity">The entity type.</typeparam>
 /// <param name="mockedReadOnlyDbSet">The mocked readonly db set.</param>
 public static void ClearReadOnlySource <TEntity>(this DbSet <TEntity> mockedReadOnlyDbSet) where TEntity : class
 {
     EnsureArgument.IsNotNull(mockedReadOnlyDbSet, nameof(mockedReadOnlyDbSet));
     mockedReadOnlyDbSet.SetSource(new List <TEntity>());
 }
Example #30
0
        public void AddOrUpdate(string service, string account, string secret)
        {
            EnsureArgument.NotNullOrWhiteSpace(service, nameof(service));

            IntPtr existingCredPtr = IntPtr.Zero;
            IntPtr credBlob        = IntPtr.Zero;

            try
            {
                // Determine if we need to update an existing credential, which might have
                // a target name that does not include the account name.
                //
                // We first check for the presence of a credential with an account-less
                // target name.
                //
                //  - If such credential exists and *has the same account* then we will
                //    update that entry.
                //  - If such credential exists and does *not* have the same account then
                //    we must create a new entry with the account in the target name.
                //  - If no such credential exists then we create a new entry with the
                //    account-less target name.
                //
                string targetName = CreateTargetName(service, account: null);
                if (Advapi32.CredRead(targetName, CredentialType.Generic, 0, out existingCredPtr))
                {
                    var existingCred = Marshal.PtrToStructure <Win32Credential>(existingCredPtr);
                    if (!StringComparer.Ordinal.Equals(existingCred.UserName, account))
                    {
                        // Create new entry with the account in the target name
                        targetName = CreateTargetName(service, account);
                    }
                }

                byte[] secretBytes = Encoding.Unicode.GetBytes(secret);
                credBlob = Marshal.AllocHGlobal(secretBytes.Length);
                Marshal.Copy(secretBytes, 0, credBlob, secretBytes.Length);

                var newCred = new Win32Credential
                {
                    Type               = CredentialType.Generic,
                    TargetName         = targetName,
                    CredentialBlobSize = secretBytes.Length,
                    CredentialBlob     = credBlob,
                    Persist            = CredentialPersist.LocalMachine,
                    UserName           = account,
                };

                int result = Win32Error.GetLastError(
                    Advapi32.CredWrite(ref newCred, 0)
                    );

                Win32Error.ThrowIfError(result, "Failed to write item to store.");
            }
            finally
            {
                if (credBlob != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(credBlob);
                }

                if (existingCredPtr != IntPtr.Zero)
                {
                    Advapi32.CredFree(existingCredPtr);
                }
            }
        }