private void ITokenStoreTest(ITokenStore tokenStore, string url, string token, DateTimeOffset expires)
        {
            try
            {
                TargetUri uri = new TargetUri(url);

                Token writeToken = new Token(token, TokenType.Test);
                Token readToken = null;

                tokenStore.WriteToken(uri, writeToken);

                if ((readToken = tokenStore.ReadToken(uri)) != null)
                {
                    Assert.AreEqual(writeToken.Value, readToken.Value, "Token values did not match between written and read");
                    Assert.AreEqual(writeToken.Type, readToken.Type, "Token types did not mathc between written and read");
                }
                else
                {
                    Assert.Fail("Failed to read token");
                }

                tokenStore.DeleteToken(uri);

                Assert.IsNull(readToken = tokenStore.ReadToken(uri), "Deleted token was read back");
            }
            catch (Exception exception)
            {
                Assert.Fail(exception.Message);
            }
        }
 public async Task<bool> ValidateCredentials(TargetUri targetUri, Credential credentials)
 {
     return await Task.Run(() =>
     {
         try
         {
             BaseSecureStore.ValidateCredential(credentials);
             return true;
         }
         catch { }
         return false;
     });
 }
 public async Task<bool> ValidateToken(TargetUri targetUri, Token token)
 {
     return await Task.Run(() =>
     {
         try
         {
             Token.Validate(token);
             return true;
         }
         catch { }
         return false;
     });
 }
        public void BasicAuthDeleteCredentialsTest()
        {
            TargetUri targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-delete");

            basicAuth.CredentialStore.WriteCredentials(targetUri, new Credential("username", "password"));

            Credential credentials;

            basicAuth.DeleteCredentials(targetUri);

            Assert.IsNull(credentials = basicAuth.CredentialStore.ReadCredentials(targetUri), "User credentials were not deleted as expected");
        }
        public void BasicAuthGetCredentialsTest()
        {
            TargetUri targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-get");

            Credential credentials = null;

            Assert.IsNull(credentials = basicAuth.GetCredentials(targetUri), "User credentials were unexpectedly retrieved.");

            credentials = new Credential("username", "password");

            basicAuth.CredentialStore.WriteCredentials(targetUri, credentials);

            Assert.IsNotNull(credentials = basicAuth.GetCredentials(targetUri), "User credentials were unexpectedly not retrieved.");
        }
        public void BasicAuthSetCredentialsTest()
        {
            TargetUri targetUri = new TargetUri("http://localhost");
            BasicAuthentication basicAuth = GetBasicAuthentication("basic-set");

            Credential credentials = null;

            Assert.IsFalse(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly retrieved.");
            try
            {
                basicAuth.SetCredentials(targetUri, credentials);
                Assert.Fail("User credentials were unexpectedly set.");
            }
            catch { }

            credentials = new Credential("username", "password");

            Assert.IsTrue(basicAuth.SetCredentials(targetUri, credentials), "User credentials were unexpectedly not set.");
            Assert.IsTrue(basicAuth.GetCredentials(targetUri, out credentials), "User credentials were unexpectedly not retrieved.");
        }
 /// <summary>
 /// Deletes a <see cref="Credential"/> from the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">
 /// The uniform resource indicator used to uniquely identify the credentials.
 /// </param>
 public abstract void DeleteCredentials(TargetUri targetUri);
 public async Task<TokenPair> AcquireTokenByRefreshTokenAsync(TargetUri targetUri, string clientId, string resource, Token refreshToken)
 {
     return await Task.Run(() => { return new TokenPair("token-access", "token-refresh"); });
 }
 /// <summary>
 /// Gets a <see cref="Credential"/> from the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">
 /// The uniform resource indicator used to uniquely identify the credentials.
 /// </param>
 /// <returns>If successful a <see cref="Credential"/> object from the authentication object,
 /// authority or storage; otherwise <see langword="null"/>.</returns>
 public abstract Credential GetCredentials(TargetUri targetUri);
Exemplo n.º 10
0
 public override int GetHashCode()
 => unchecked ((397 * Id.GetHashCode()) ^ (397 * TargetUri.GetHashCode()) ^ Drawing.GetHashCode());
        /// <summary>
        /// Generate a new <see cref="TargetUri"/> to be used as the key when storing the
        /// refresh_tokne alongside the access_token.
        /// </summary>
        /// <param name="targetUri">contains Authority URL etc used for storing the sibling access_token</param>
        /// <returns></returns>
        private static TargetUri GetRefreshTokenTargetUri(TargetUri targetUri)
        {
            var uri = new Uri(targetUri.ActualUri, refreshTokenSuffix);

            return(new TargetUri(uri));
        }
 internal Credential ModalPromptForCredentials(TargetUri targetUri, string message)
 => _modalPromptForCredentials(this, targetUri, message);
 public async Task<Token> GeneratePersonalAccessToken(TargetUri targetUri, Token accessToken, VstsTokenScope tokenScope, bool requireCompactToken)
 {
     return await Task.Run(() => { return new Token("personal-access-token", TokenType.Personal); });
 }
 public void DeleteCredentials(TargetUri targetUri)
 {
     this.data.Remove(targetUri);
 }
Exemplo n.º 15
0
 /// <summary>
 /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param>
 /// <param name="credentials">The value to be stored.</param>
 public abstract void SetCredentials(TargetUri targetUri, Credential credentials);
Exemplo n.º 16
0
 /// <summary>
 /// Gets a <see cref="Credential"/> from the storage used by the authentication object.
 /// <para/>
 /// Returns a `<see cref="Credential"/>` if successful; otherwise `<see langword="null"/>`.
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param>
 public abstract Credential GetCredentials(TargetUri targetUri);
Exemplo n.º 17
0
 /// <summary>
 /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param>
 /// <param name="username">The username of the credentials to be deleted.</param>
 public virtual void DeleteCredentials(TargetUri targetUri, string username)
 => DeleteCredentials(targetUri, null);
Exemplo n.º 18
0
 /// <summary>
 /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param>
 public abstract void DeleteCredentials(TargetUri targetUri);
Exemplo n.º 19
0
        internal void CreateTargetUri()
        {
            string actualUrl = null;
            string queryUrl  = null;
            string proxyUrl  = _proxyUri?.ToString();

            // when the target requests a path...
            if (UseHttpPath)
            {
                // and lacks a protocol...
                if (String.IsNullOrWhiteSpace(_queryProtocol))
                {
                    // and the target lacks a path: use just the host
                    if ((String.IsNullOrWhiteSpace(_queryPath)))
                    {
                        queryUrl = _queryHost;
                    }
                    // combine the host + path
                    else
                    {
                        queryUrl = $"{_queryHost}/{_queryPath}";
                    }
                }
                // and has a protocol...
                else
                {
                    // and the target lacks a path, combine protocol + host
                    if (String.IsNullOrWhiteSpace(_queryPath))
                    {
                        queryUrl = $"{_queryProtocol}://{_queryHost}";
                    }
                    // combine protocol + host + path
                    else
                    {
                        queryUrl = $"{_queryProtocol}://{_queryHost}/{_queryPath}";
                    }
                }

                actualUrl = queryUrl;
            }
            // when the target ignores paths...
            else
            {
                // and lacks a protocol...
                if (String.IsNullOrWhiteSpace(_queryProtocol))
                {
                    // and the host starts with "\\", strip the path...
                    if (_queryHost.StartsWith(@"\\", StringComparison.Ordinal))
                    {
                        int idx = _queryHost.IndexOfAny(SeperatorCharacters, 2);
                        queryUrl = (idx > 0)
                            ? _queryHost.Substring(0, idx)
                            : _queryHost;
                    }
                    // use just the host
                    else
                    {
                        queryUrl = _queryHost;
                    }

                    if (String.IsNullOrWhiteSpace(_queryPath))
                    {
                        actualUrl = queryUrl;
                    }
                    else
                    {
                        actualUrl = $"{queryUrl}/{_queryPath}";
                    }
                }
                // and the protocol is "file://" strip any path
                else if (_queryProtocol.StartsWith(Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
                {
                    int idx = _queryHost.IndexOfAny(SeperatorCharacters);

                    // strip the host as neccisary
                    queryUrl = (idx > 0)
                        ? _queryHost.Substring(0, idx)
                        : _queryHost;

                    // combine with protocol
                    queryUrl = $"{_queryProtocol}://{queryUrl}";

                    actualUrl = queryUrl;
                }
                // combine the protocol + host
                else
                {
                    queryUrl = $"{_queryProtocol}://{_queryHost}";

                    if (String.IsNullOrWhiteSpace(_queryPath))
                    {
                        actualUrl = queryUrl;
                    }
                    else
                    {
                        actualUrl = $"{queryUrl}/{_queryPath}";
                    }
                }
            }

            _targetUri = new TargetUri(actualUrl, queryUrl, proxyUrl);
        }
 /// <summary>
 /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">
 /// The uniform resource indicator used to uniquely identify the credentials.
 /// </param>
 /// <param name="credentials">The value to be stored.</param>
 /// <returns><see langword="true"/> if successful; otherwise <see langword="false"/>.</returns>
 public abstract bool SetCredentials(TargetUri targetUri, Credential credentials);
        internal virtual void CreateTargetUri()
        {
            string queryUrl  = null;
            string proxyUrl  = _proxyUri?.OriginalString;
            string actualUrl = null;

            StringBuilder buffer = new StringBuilder();

            // URI format is {protocol}://{username}@{host}/{path] with
            // everything optional except for {host}.

            // Protocol.
            if (!string.IsNullOrWhiteSpace(_queryProtocol))
            {
                buffer.Append(_queryProtocol)
                .Append("://");
            }

            // Username.
            if (!string.IsNullOrWhiteSpace(_username))
            {
                var username = NeedsToBeEscaped(_username)
                    ? Uri.EscapeDataString(_username)
                    : _username;

                buffer.Append(username)
                .Append('@');
            }

            // Host.
            buffer.Append(_queryHost)
            .Append('/');

            // Path
            if (!string.IsNullOrWhiteSpace(_queryPath))
            {
                buffer.Append(_queryPath);
            }

            queryUrl = buffer.ToString();

            // If the git-remote-http(s) command line has been captured,
            // try and parse it and provide the command-url .
            if (!string.IsNullOrEmpty(_gitRemoteHttpCommandLine))
            {
                string[] parts = _gitRemoteHttpCommandLine.Split(' ');

                switch (parts.Length)
                {
                case 1:
                {
                    if (Uri.TryCreate(parts[0], UriKind.Absolute, out Uri uri))
                    {
                        actualUrl = uri.ToString();
                    }
                }
                break;

                case 3:
                {
                    if (Uri.TryCreate(parts[2], UriKind.Absolute, out Uri uri))
                    {
                        actualUrl = uri.ToString();
                    }
                }
                break;
                }
            }

            // Create the target URI object.
            _targetUri = new TargetUri(queryUrl, proxyUrl, actualUrl);
        }
        public Credential ReadCredentials(TargetUri targetUri)
        {
            Credential credentials;

            return(this.data.TryGetValue(targetUri, out credentials) ? credentials : null);
        }
Exemplo n.º 23
0
 public async Task <Token> NoninteractiveAcquireToken(TargetUri targetUri, string clientId, string resource, Uri redirectUri)
 {
     return(await Task.Run(() => { return new Token("token-access", TokenType.Access); }));
 }
 public void WriteCredentials(TargetUri targetUri, Credential credentials)
 {
     this.data[targetUri] = credentials;
 }
 private Credential ModalPromptForPassword(TargetUri targetUri, string message, string username)
 => _modalPromptForPassword(this, targetUri, message, username);
Exemplo n.º 26
0
        public static async Task <Guid?> DetectAuthority(RuntimeContext context, TargetUri targetUri)
        {
            const int    GuidStringLength         = 36;
            const string VstsResourceTenantHeader = "X-VSS-ResourceTenant";

            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }

            // Assume VSTS using Azure "common tenant" (empty GUID).
            var tenantId = Guid.Empty;

            // Compose the request Uri, by default it is the target Uri.
            var requestUri = targetUri;

            // Override the request Uri, when actual Uri exists, with actual Uri.
            if (targetUri.ActualUri != null)
            {
                requestUri = targetUri.CreateWith(queryUri: targetUri.ActualUri);
            }

            // If the protocol (aka scheme) being used isn't HTTP based, there's no point in
            // querying the server, so skip that work.
            if (OrdinalIgnoreCase.Equals(requestUri.Scheme, Uri.UriSchemeHttp) ||
                OrdinalIgnoreCase.Equals(requestUri.Scheme, Uri.UriSchemeHttps))
            {
                var requestUrl = GetTargetUrl(requestUri, false);

                // Read the cache from disk.
                var cache = await DeserializeTenantCache(context);

                // Check the cache for an existing value.
                if (cache.TryGetValue(requestUrl, out tenantId))
                {
                    context.Trace.WriteLine($"'{requestUrl}' is VSTS, tenant resource is {{{tenantId.ToString("N")}}}.");

                    return(tenantId);
                }

                var options = new NetworkRequestOptions(false)
                {
                    Flags   = NetworkRequestOptionFlags.UseProxy,
                    Timeout = TimeSpan.FromMilliseconds(Global.RequestTimeout),
                };

                try
                {
                    // Query the host use the response headers to determine if the host is VSTS or not.
                    using (var response = await context.Network.HttpHeadAsync(requestUri, options))
                    {
                        if (response.Headers != null)
                        {
                            // If the "X-VSS-ResourceTenant" was returned, then it is VSTS and we'll need it's value.
                            if (response.Headers.TryGetValues(VstsResourceTenantHeader, out IEnumerable <string> values))
                            {
                                context.Trace.WriteLine($"detected '{requestUrl}' as VSTS from GET response.");

                                // The "Www-Authenticate" is a more reliable header, because it indicates the
                                // authentication scheme that should be used to access the requested entity.
                                if (response.Headers.WwwAuthenticate != null)
                                {
                                    foreach (var header in response.Headers.WwwAuthenticate)
                                    {
                                        const string AuthorizationUriPrefix = "authorization_uri=";

                                        var value = header.Parameter;

                                        if (value.Length >= AuthorizationUriPrefix.Length + AuthorityHostUrlBase.Length + GuidStringLength)
                                        {
                                            // The header parameter will look something like "authorization_uri=https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47"
                                            // and all we want is the portion after the '=' and before the last '/'.
                                            int index1 = value.IndexOf('=', AuthorizationUriPrefix.Length - 1);
                                            int index2 = value.LastIndexOf('/');

                                            // Parse the header value if the necessary characters exist...
                                            if (index1 > 0 && index2 > index1)
                                            {
                                                var authorityUrl = value.Substring(index1 + 1, index2 - index1 - 1);
                                                var guidString   = value.Substring(index2 + 1, GuidStringLength);

                                                // If the authority URL is as expected, attempt to parse the tenant resource identity.
                                                if (OrdinalIgnoreCase.Equals(authorityUrl, AuthorityHostUrlBase) &&
                                                    Guid.TryParse(guidString, out tenantId))
                                                {
                                                    // Update the cache.
                                                    cache[requestUrl] = tenantId;

                                                    // Write the cache to disk.
                                                    await SerializeTenantCache(context, cache);

                                                    // Since we found a value, break the loop (likely a loop of one item anyways).
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    // Since there wasn't a "Www-Authenticate" header returned
                                    // iterate through the values, taking the first non-zero value.
                                    foreach (string value in values)
                                    {
                                        // Try to find a value for the resource-tenant identity.
                                        // Given that some projects will return multiple tenant identities,
                                        if (!string.IsNullOrWhiteSpace(value) &&
                                            Guid.TryParse(value, out tenantId))
                                        {
                                            // Update the cache.
                                            cache[requestUrl] = tenantId;

                                            // Write the cache to disk.
                                            await SerializeTenantCache(context, cache);

                                            // Break the loop if a non-zero value has been detected.
                                            if (tenantId != Guid.Empty)
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }

                                context.Trace.WriteLine($"tenant resource for '{requestUrl}' is {{{tenantId.ToString("N")}}}.");

                                // Return the tenant identity to the caller because this is VSTS.
                                return(tenantId);
                            }
                        }
                        else
                        {
                            context.Trace.WriteLine($"unable to get response from '{requestUri}' [{(int)response.StatusCode} {response.StatusCode}].");
                        }
                    }
                }
                catch (HttpRequestException exception)
                {
                    context.Trace.WriteLine($"unable to get response from '{requestUri}', an error occurred before the server could respond.");
                    context.Trace.WriteException(exception);
                }
            }
            else
            {
                context.Trace.WriteLine($"detected non-http(s) based protocol: '{requestUri.Scheme}'.");
            }

            if (OrdinalIgnoreCase.Equals(VstsBaseUrlHost, requestUri.Host))
            {
                return(Guid.Empty);
            }

            // Fallback to basic authentication.
            return(null);
        }
 /// <summary>
 /// Deletes a `<see cref="Credential"/>` from the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">The uniform resource indicator used to uniquely identify the credentials.</param>
 public override void DeleteCredentials(TargetUri targetUri)
 {
     DeleteCredentials(targetUri, null);
 }
Exemplo n.º 28
0
 /// <summary>
 /// Validates that a set of credentials grants access to the target resource.
 /// <para/>
 /// Returns `<see langword="true"/>` if successful; otherwise `<see langword="false"/>`.
 /// </summary>
 /// <param name="targetUri">The target resource to validate against.</param>
 /// <param name="credentials">The credentials to validate.</param>
 public async Task <bool> ValidateCredentials(TargetUri targetUri, Credential credentials)
 {
     return(await Authority.ValidateCredentials(targetUri, credentials));
 }
        public static Credential PasswordPrompt(Program program, TargetUri targetUri, string message, string username)
        {
            Debug.Assert(targetUri != null);
            Debug.Assert(message != null);
            Debug.Assert(username != null);

            NativeMethods.CredentialUiInfo credUiInfo = new NativeMethods.CredentialUiInfo
            {
                BannerArt   = IntPtr.Zero,
                CaptionText = program.Title,
                MessageText = message,
                Parent      = IntPtr.Zero,
                Size        = Marshal.SizeOf(typeof(NativeMethods.CredentialUiInfo))
            };
            NativeMethods.CredentialUiWindowsFlags flags       = NativeMethods.CredentialUiWindowsFlags.Generic;
            NativeMethods.CredentialPackFlags      authPackage = NativeMethods.CredentialPackFlags.None;
            IntPtr packedAuthBufferPtr  = IntPtr.Zero;
            IntPtr inBufferPtr          = IntPtr.Zero;
            uint   packedAuthBufferSize = 0;
            bool   saveCredentials      = false;
            int    inBufferSize         = 0;
            string password;

            try
            {
                int error;

                // execute with `null` to determine buffer size always returns false when determining
                // size, only fail if `inBufferSize` looks bad
                NativeMethods.CredPackAuthenticationBuffer(flags: authPackage,
                                                           username: username,
                                                           password: string.Empty,
                                                           packedCredentials: IntPtr.Zero,
                                                           packedCredentialsSize: ref inBufferSize);
                if (inBufferSize <= 0)
                {
                    error = Marshal.GetLastWin32Error();
                    Git.Trace.WriteLine($"unable to determine credential buffer size ('{NativeMethods.Win32Error.GetText(error)}').");

                    return(null);
                }

                inBufferPtr = Marshal.AllocHGlobal(inBufferSize);

                if (!NativeMethods.CredPackAuthenticationBuffer(flags: authPackage,
                                                                username: username,
                                                                password: string.Empty,
                                                                packedCredentials: inBufferPtr,
                                                                packedCredentialsSize: ref inBufferSize))
                {
                    error = Marshal.GetLastWin32Error();
                    Git.Trace.WriteLine($"unable to write to credential buffer ('{NativeMethods.Win32Error.GetText(error)}').");

                    return(null);
                }

                if (program.ModalPromptDisplayDialog(ref credUiInfo,
                                                     ref authPackage,
                                                     packedAuthBufferPtr,
                                                     packedAuthBufferSize,
                                                     inBufferPtr,
                                                     inBufferSize,
                                                     saveCredentials,
                                                     flags,
                                                     out username,
                                                     out password))
                {
                    return(new Credential(username, password));
                }
            }
            finally
            {
                if (inBufferPtr != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(inBufferPtr);
                }
            }

            return(null);
        }
Exemplo n.º 30
0
 public void TestInitialize()
 {
     mockCredentialStore = new Mock <ICredentialStore>();
     testSubject         = new CredentialStore(mockCredentialStore.Object);
     wellKnownTargetUri  = new TargetUri("http://sonarcredtest/");
 }
 /// <summary>
 /// Sets a <see cref="Credential"/> in the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">
 /// The uniform resource indicator used to uniquely identify the credentials.
 /// </param>
 /// <param name="credentials">The value to be stored.</param>
 public abstract void SetCredentials(TargetUri targetUri, Credential credentials);
        internal Credential BasicCredentialPrompt(TargetUri targetUri)
        {
            string message = "Please enter your credentials for ";

            return(BasicCredentialPrompt(targetUri, message));
        }
 public TokenPair AcquireToken(TargetUri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null)
 {
     return new TokenPair("token-access", "token-refresh");
 }
 internal Credential BasicCredentialPrompt(TargetUri targetUri, string titleMessage)
 => _basicCredentialPrompt(this, targetUri, titleMessage);
 /// <summary>
 /// Gets a <see cref="Credential"/> from the storage used by the authentication object.
 /// </summary>
 /// <param name="targetUri">
 /// The uniform resource indicator used to uniquely identify the credentials.
 /// </param>
 /// <param name="credentials">
 /// If successful a <see cref="Credential"/> object from the authentication object,
 /// authority or storage; otherwise <see langword="null"/>.
 /// </param>
 /// <returns><see langword="true"/> if successful; otherwise <see langword="false"/>.</returns>
 public abstract bool GetCredentials(TargetUri targetUri, out Credential credentials);
 internal bool BitbucketCredentialPrompt(string titleMessage, TargetUri targetUri, out string username, out string password)
 => _bitbucketCredentialPrompt(this, titleMessage, targetUri, out username, out password);
 public async Task<Token> NoninteractiveAcquireToken(TargetUri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null)
 {
     return await Task.Run(() => { return new Token("token-access", TokenType.Access); });
 }
Exemplo n.º 38
0
 public async Task <Token> GeneratePersonalAccessToken(TargetUri targetUri, Token accessToken, VstsTokenScope tokenScope, bool requireCompactToken)
 {
     return(await Task.Run(() => { return new Token("personal-access-token", TokenType.Personal); }));
 }
Exemplo n.º 39
0
        internal virtual void CreateTargetUri()
        {
            string queryUrl  = null;
            string proxyUrl  = _proxyUri?.OriginalString;
            string actualUrl = null;

            var buffer = new StringBuilder();

            // URI format is {protocol}://{username}@{host}/{path] with
            // everything optional except for {host}.

            // Protocol.
            if (!string.IsNullOrWhiteSpace(_queryProtocol))
            {
                buffer.Append(_queryProtocol)
                .Append("://");
            }

            // Username.
            if (!string.IsNullOrWhiteSpace(_username))
            {
                var username = NeedsToBeEscaped(_username)
                    ? Uri.EscapeDataString(_username)
                    : _username;

                buffer.Append(username)
                .Append('@');
            }

            // Host.
            buffer.Append(_queryHost)
            .Append('/');

            // Path
            if (!string.IsNullOrWhiteSpace(_queryPath))
            {
                buffer.Append(_queryPath);
            }

            queryUrl = buffer.ToString();

            // if path is specified we should give the host/path priority
            if (!string.IsNullOrWhiteSpace(_queryPath))
            {
                actualUrl = queryUrl;
            }
            // If the actual-url override has been set, honor it.
            else if (!string.IsNullOrEmpty(_urlOverride))
            {
                if (Uri.TryCreate(_urlOverride, UriKind.Absolute, out Uri uri))
                {
                    actualUrl = uri.ToString();
                }
                else
                {
                    Trace.WriteLine($"failed to parse \"{_urlOverride}\", unable to set URL override.");
                }
            }
            // If the git-remote-http(s) command line has been captured,
            // try and parse it and provide the command-url .
            else if (!string.IsNullOrEmpty(_gitRemoteHttpCommandLine))
            {
                string[] parts = _gitRemoteHttpCommandLine.Split(' ');

                switch (parts.Length)
                {
                case 1:
                {
                    if (Uri.TryCreate(parts[0], UriKind.Absolute, out Uri uri))
                    {
                        actualUrl = uri.ToString();
                    }
                    else
                    {
                        Trace.WriteLine($"failed to parse \"{parts[0]}\", unable to set URL override.");
                    }
                }
                break;

                case 3:
                {
                    if (Uri.TryCreate(parts[2], UriKind.Absolute, out Uri uri))
                    {
                        actualUrl = uri.ToString();
                    }
                    else
                    {
                        Trace.WriteLine($"failed to parse \"{parts[2]}\", unable to set URL override.");
                    }
                }
                break;
                }
            }

            // Create the target URI object.
            _targetUri = new TargetUri(queryUrl, proxyUrl, actualUrl);
        }
        public static bool AuthCodePrompt(Program program, TargetUri targetUri, Github.GitHubAuthenticationResultType resultType, string username, out string authenticationCode)
        {
            // ReadConsole 32768 fail, 32767 ok @linquize [https://github.com/Microsoft/Git-Credential-Manager-for-Windows/commit/a62b9a19f430d038dcd85a610d97e5f763980f85]
            const int BufferReadSize = 16 * 1024;

            if (program is null)
            {
                throw new ArgumentNullException(nameof(program));
            }
            if (targetUri is null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }

            var trace = program.Trace;

            StringBuilder buffer  = new StringBuilder(BufferReadSize);
            uint          read    = 0;
            uint          written = 0;

            authenticationCode = null;

            NativeMethods.FileAccess              fileAccessFlags         = NativeMethods.FileAccess.GenericRead | NativeMethods.FileAccess.GenericWrite;
            NativeMethods.FileAttributes          fileAttributes          = NativeMethods.FileAttributes.Normal;
            NativeMethods.FileCreationDisposition fileCreationDisposition = NativeMethods.FileCreationDisposition.OpenExisting;
            NativeMethods.FileShare fileShareFlags = NativeMethods.FileShare.Read | NativeMethods.FileShare.Write;

            using (SafeFileHandle stdout = NativeMethods.CreateFile(NativeMethods.ConsoleOutName, fileAccessFlags, fileShareFlags, IntPtr.Zero, fileCreationDisposition, fileAttributes, IntPtr.Zero))
                using (SafeFileHandle stdin = NativeMethods.CreateFile(NativeMethods.ConsoleInName, fileAccessFlags, fileShareFlags, IntPtr.Zero, fileCreationDisposition, fileAttributes, IntPtr.Zero))
                {
                    string type = resultType == Github.GitHubAuthenticationResultType.TwoFactorApp
                    ? "app"
                    : "sms";

                    trace.WriteLine($"2fa type = '{type}'.");

                    buffer.AppendLine()
                    .Append("authcode (")
                    .Append(type)
                    .Append("): ");

                    if (!NativeMethods.WriteConsole(stdout, buffer, (uint)buffer.Length, out written, IntPtr.Zero))
                    {
                        int error = Marshal.GetLastWin32Error();
                        throw new Win32Exception(error, "Unable to write to standard output (" + NativeMethods.Win32Error.GetText(error) + ").");
                    }
                    buffer.Clear();

                    // read input from the user
                    if (!NativeMethods.ReadConsole(stdin, buffer, BufferReadSize, out read, IntPtr.Zero))
                    {
                        int error = Marshal.GetLastWin32Error();
                        throw new Win32Exception(error, "Unable to read from standard input (" + NativeMethods.Win32Error.GetText(error) + ").");
                    }

                    authenticationCode = buffer.ToString(0, (int)read);
                    authenticationCode = authenticationCode.Trim(program.NewLineChars);
                }

            return(authenticationCode != null);
        }
 internal bool BitbucketOAuthPrompt(string title, TargetUri targetUri, Bitbucket.AuthenticationResultType resultType, string username)
 => _bitbucketOauthPrompt(this, title, targetUri, resultType, username);
Exemplo n.º 42
0
        public async Task <Token> InteractiveAcquireToken(TargetUri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null)
        {
            Assert.Equal(this.ExpectedQueryParameters, queryParameters);

            return(await Task.Run(() => { return new Token("token-access", TokenType.Access); }));
        }
        private void ICredentialStoreTest(ICredentialStore credentialStore, string url, string username, string password)
        {
            try
            {
                TargetUri uri = new TargetUri(url);
                Credential writeCreds = new Credential(username, password);
                Credential readCreds = null;

                credentialStore.WriteCredentials(uri, writeCreds);

                if ((readCreds = credentialStore.ReadCredentials(uri)) != null)
                {
                    Assert.AreEqual(writeCreds.Password, readCreds.Password, "Passwords did not match between written and read credentials");
                    Assert.AreEqual(writeCreds.Username, readCreds.Username, "Usernames did not match between written and read credentials");
                }
                else
                {
                    Assert.Fail("Failed to read credentials");
                }

                credentialStore.DeleteCredentials(uri);

                Assert.IsNull(readCreds = credentialStore.ReadCredentials(uri), "Deleted credentials were read back");
            }
            catch (Exception exception)
            {
                Assert.Fail(exception.Message);
            }
        }
 internal bool GitHubAuthCodePrompt(TargetUri targetUri, Github.GitHubAuthenticationResultType resultType, string username, out string authenticationCode)
 => _gitHubAuthCodePrompt(this, targetUri, resultType, username, out authenticationCode);
 internal bool GitHubCredentialPrompt(TargetUri targetUri, out string username, out string password)
 => _gitHubCredentialPrompt(this, targetUri, out username, out password);
        public void TargetUri_Basics(string actualUrl, string queryUrl, string proxyUrl)
        {
            TargetUri targetUri;
            Uri       actualUri;
            Uri       queryUri;
            Uri       proxyUri;

            actualUri = new TargetUri(actualUrl);

            targetUri = new TargetUri(actualUrl);
            Assert.NotNull(targetUri);

            Assert.Equal(actualUri.AbsolutePath, targetUri.AbsolutePath);
            Assert.Equal(actualUri.DnsSafeHost, targetUri.DnsSafeHost);
            Assert.Equal(actualUri.Host, targetUri.Host);
            Assert.Equal(actualUri.IsAbsoluteUri, targetUri.IsAbsoluteUri);
            Assert.Equal(actualUri.IsDefaultPort, targetUri.IsDefaultPort);
            Assert.Equal(actualUri.Port, targetUri.Port);
            Assert.Equal(actualUri.Scheme, targetUri.Scheme);
            Assert.Equal(actualUri.UserInfo, targetUri.TargetUriUsername);

            actualUri = actualUrl is null ? null : new Uri(actualUrl);
            queryUri  = queryUrl is null ? null : new Uri(queryUrl);
            proxyUri  = proxyUrl is null ? null : new Uri(proxyUrl);

            targetUri = new TargetUri(actualUrl, queryUrl, proxyUrl);
            Assert.NotNull(targetUri);

            // Since the actual Uri will substitute for a null query Uri, test the correct value.
            var uri = queryUri ?? actualUri;

            Assert.Equal(uri.AbsolutePath, targetUri.AbsolutePath);
            Assert.Equal(uri.DnsSafeHost, targetUri.DnsSafeHost);
            Assert.Equal(uri.Host, targetUri.Host);
            Assert.Equal(uri.IsAbsoluteUri, targetUri.IsAbsoluteUri);
            Assert.Equal(uri.IsDefaultPort, targetUri.IsDefaultPort);
            Assert.Equal(uri.Port, targetUri.Port);
            Assert.Equal(uri.Scheme, targetUri.Scheme);

            Assert.Equal(uri.UserInfo, targetUri.TargetUriUsername);

            Assert.Equal(actualUri, targetUri.ActualUri);
            Assert.Equal(uri, targetUri.QueryUri);
            Assert.Equal(proxyUri, targetUri.ProxyUri);

            targetUri = new TargetUri(actualUri, queryUri, proxyUri);
            Assert.NotNull(targetUri);
            Assert.Equal(uri.AbsolutePath, targetUri.AbsolutePath);
            Assert.Equal(uri.DnsSafeHost, targetUri.DnsSafeHost);
            Assert.Equal(uri.Host, targetUri.Host);
            Assert.Equal(uri.IsAbsoluteUri, targetUri.IsAbsoluteUri);
            Assert.Equal(uri.IsDefaultPort, targetUri.IsDefaultPort);
            Assert.Equal(uri.Port, targetUri.Port);
            Assert.Equal(uri.Scheme, targetUri.Scheme);

            Assert.Equal(uri.UserInfo, targetUri.TargetUriUsername);

            Assert.Equal(actualUri, targetUri.ActualUri);
            Assert.Equal(uri, targetUri.QueryUri);
            Assert.Equal(proxyUri, targetUri.ProxyUri);
        }