Skip to content
Snippets Groups Projects
Commit 9c1685f7 authored by Andreia Gaita's avatar Andreia Gaita
Browse files

Add GitHub.Api, Octokit and helper libraries for authentication

Add the simple api client from GHfVS, add credential management stubs per platform, add octokit and TPL 3.5 ports.
Remove CredentialManagement for now, it blows up on Mono (likely due to marshaling), so needs testing first.
parent ef6595cb
No related branches found
No related tags found
No related merge requests found
Showing
with 1146 additions and 0 deletions
[submodule "submodules/octokit.net"]
path = submodules/octokit.net
url = https://github.com/editor-tools/octokit.net.git
[submodule "submodules/dotnet-httpclient35"]
path = submodules/dotnet-httpclient35
url = https://github.com/shana/dotnet-httpClient35
......@@ -7,6 +7,18 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitHub.Unity", "src\UnityEx
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitHub.Unity.Tests", "src\GitHub.Unity.Tests\GitHub.Unity.Tests.csproj", "{69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Net.Http-net_3_5", "submodules\dotnet-httpclient35\System.Net.Http\System.Net.Http-net_3_5.csproj", "{9862694D-E4FA-418B-8692-A0280FEDDF36}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dotnet-http35", "dotnet-http35", "{0D94B00D-1578-450B-B6A5-2A1E508421C3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "octokit", "octokit", "{7DB5B8B0-5126-4025-913C-74B090ED625B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Octokit-Extensions35", "submodules\octokit.net\Octokit-Extensions35\Octokit-Extensions35.csproj", "{EB4B074E-62A7-4F1D-8F95-E64B7AEA0236}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Octokit-35", "submodules\octokit.net\Octokit\Octokit-35.csproj", "{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GitHub.Api", "src\GitHub.Api\GitHub.Api.csproj", "{B389ADAF-62CC-486E-85B4-2D8B078DF763}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -21,8 +33,29 @@ Global
{69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{69F13D9D-AD56-4EEC-AE10-D528EE23E1A9}.Release|Any CPU.Build.0 = Release|Any CPU
{9862694D-E4FA-418B-8692-A0280FEDDF36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9862694D-E4FA-418B-8692-A0280FEDDF36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9862694D-E4FA-418B-8692-A0280FEDDF36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9862694D-E4FA-418B-8692-A0280FEDDF36}.Release|Any CPU.Build.0 = Release|Any CPU
{EB4B074E-62A7-4F1D-8F95-E64B7AEA0236}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EB4B074E-62A7-4F1D-8F95-E64B7AEA0236}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EB4B074E-62A7-4F1D-8F95-E64B7AEA0236}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EB4B074E-62A7-4F1D-8F95-E64B7AEA0236}.Release|Any CPU.Build.0 = Release|Any CPU
{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4}.Release|Any CPU.Build.0 = Release|Any CPU
{B389ADAF-62CC-486E-85B4-2D8B078DF763}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B389ADAF-62CC-486E-85B4-2D8B078DF763}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B389ADAF-62CC-486E-85B4-2D8B078DF763}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B389ADAF-62CC-486E-85B4-2D8B078DF763}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{9862694D-E4FA-418B-8692-A0280FEDDF36} = {0D94B00D-1578-450B-B6A5-2A1E508421C3}
{EB4B074E-62A7-4F1D-8F95-E64B7AEA0236} = {7DB5B8B0-5126-4025-913C-74B090ED625B}
{49EF16A2-5ED1-480F-80A1-D1D05D6C1BE4} = {7DB5B8B0-5126-4025-913C-74B090ED625B}
EndGlobalSection
EndGlobal
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "0.1.0.0";
}
}
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
namespace GitHub.Authentication.CredentialManagement
{
public class Credential : IDisposable
{
const int maxPasswordLengthInBytes = NativeMethods.CREDUI_MAX_PASSWORD_LENGTH * 2;
static readonly object _lockObject = new object();
static readonly SecurityPermission _unmanagedCodePermission;
CredentialType _type;
string _target;
SecureString _password;
string _username;
string _description;
DateTime _lastWriteTime;
PersistenceType _persistanceType;
static Credential()
{
lock (_lockObject)
{
_unmanagedCodePermission = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
}
}
public Credential() : this(null, (string)null)
{}
public Credential(
string username,
SecureString password,
string target = null)
{
Username = username;
SecurePassword = password;
Target = target;
Type = CredentialType.Generic;
PersistenceType = PersistenceType.LocalComputer;
_lastWriteTime = DateTime.MinValue;
}
public Credential(
string username,
string password,
string target = null)
{
Username = username;
Password = password;
Target = target;
Type = CredentialType.Generic;
PersistenceType = PersistenceType.LocalComputer;
_lastWriteTime = DateTime.MinValue;
}
bool disposed;
void Dispose(bool disposing)
{
if (disposing)
{
if (disposed) return;
SecurePassword.Clear();
SecurePassword.Dispose();
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void CheckNotDisposed()
{
if (disposed)
{
throw new ObjectDisposedException("Credential object is already disposed.");
}
}
public string Username
{
get
{
CheckNotDisposed();
return _username;
}
set
{
CheckNotDisposed();
_username = value;
}
}
public string Password
{
get
{
return SecureStringHelper.CreateString(SecurePassword);
}
set
{
CheckNotDisposed();
SecurePassword = SecureStringHelper.CreateSecureString(string.IsNullOrEmpty(value) ? string.Empty : value);
}
}
public SecureString SecurePassword
{
get
{
CheckNotDisposed();
_unmanagedCodePermission.Demand();
return _password == null ? new SecureString() : _password.Copy();
}
set
{
CheckNotDisposed();
if (_password != null)
{
_password.Clear();
_password.Dispose();
}
_password = null == value ? new SecureString() : value.Copy();
}
}
public string Target
{
get
{
CheckNotDisposed();
return _target;
}
set
{
CheckNotDisposed();
_target = value;
}
}
public string Description
{
get
{
CheckNotDisposed();
return _description;
}
set
{
CheckNotDisposed();
_description = value;
}
}
public DateTime LastWriteTime
{
get
{
return LastWriteTimeUtc.ToLocalTime();
}
}
public DateTime LastWriteTimeUtc
{
get
{
CheckNotDisposed();
return _lastWriteTime;
}
private set { _lastWriteTime = value; }
}
public CredentialType Type
{
get
{
CheckNotDisposed();
return _type;
}
set
{
CheckNotDisposed();
_type = value;
}
}
public PersistenceType PersistenceType
{
get
{
CheckNotDisposed();
return _persistanceType;
}
set
{
CheckNotDisposed();
_persistanceType = value;
}
}
public bool Save()
{
CheckNotDisposed();
_unmanagedCodePermission.Demand();
byte[] passwordBytes = Encoding.Unicode.GetBytes(Password);
ValidatePasswordLength(passwordBytes);
var credential = new NativeMethods.CREDENTIAL
{
TargetName = Target,
UserName = Username,
CredentialBlob = Marshal.StringToCoTaskMemUni(Password),
CredentialBlobSize = passwordBytes.Length,
Comment = Description,
Type = (int)Type,
Persist = (int)PersistenceType
};
bool result = NativeMethods.CredWrite(ref credential, 0);
if (!result)
{
return false;
}
LastWriteTimeUtc = DateTime.UtcNow;
return true;
}
public bool Save(byte[] passwordBytes)
{
CheckNotDisposed();
_unmanagedCodePermission.Demand();
ValidatePasswordLength(passwordBytes);
var blob = Marshal.AllocCoTaskMem(passwordBytes.Length);
Marshal.Copy(passwordBytes, 0, blob, passwordBytes.Length);
var credential = new NativeMethods.CREDENTIAL
{
TargetName = Target,
UserName = Username,
CredentialBlob = blob,
CredentialBlobSize = passwordBytes.Length,
Comment = Description,
Type = (int)Type,
Persist = (int)PersistenceType
};
bool result = NativeMethods.CredWrite(ref credential, 0);
Marshal.FreeCoTaskMem(blob);
if (!result)
{
return false;
}
LastWriteTimeUtc = DateTime.UtcNow;
return true;
}
public bool Delete()
{
CheckNotDisposed();
_unmanagedCodePermission.Demand();
if (string.IsNullOrEmpty(Target))
{
throw new InvalidOperationException("Target must be specified to delete a credential.");
}
StringBuilder target = string.IsNullOrEmpty(Target) ? new StringBuilder() : new StringBuilder(Target);
bool result = NativeMethods.CredDelete(target, Type, 0);
return result;
}
public bool Load()
{
CheckNotDisposed();
_unmanagedCodePermission.Demand();
IntPtr credPointer;
bool result = NativeMethods.CredRead(Target, Type, 0, out credPointer);
if (!result)
{
return false;
}
using (NativeMethods.CriticalCredentialHandle credentialHandle = new NativeMethods.CriticalCredentialHandle(credPointer))
{
LoadInternal(credentialHandle.GetCredential());
}
return true;
}
public bool Exists()
{
CheckNotDisposed();
_unmanagedCodePermission.Demand();
if (string.IsNullOrEmpty(Target))
{
throw new InvalidOperationException("Target must be specified to check existance of a credential.");
}
using (Credential existing = new Credential { Target = Target, Type = Type })
{
return existing.Load();
}
}
internal void LoadInternal(NativeMethods.CREDENTIAL credential)
{
Username = credential.UserName;
if (credential.CredentialBlobSize > 0)
{
Password = Marshal.PtrToStringUni(credential.CredentialBlob, credential.CredentialBlobSize / 2);
}
Target = credential.TargetName;
Type = (CredentialType)credential.Type;
PersistenceType = (PersistenceType)credential.Persist;
Description = credential.Comment;
LastWriteTimeUtc = DateTime.FromFileTimeUtc(credential.LastWritten);
}
static void ValidatePasswordLength(byte[] passwordBytes)
{
if (passwordBytes.Length > maxPasswordLengthInBytes)
{
var message = string.Format(CultureInfo.InvariantCulture,
"The password length ({0} bytes) exceeds the maximum password length ({1} bytes).",
passwordBytes.Length,
maxPasswordLengthInBytes);
throw new ArgumentOutOfRangeException(message);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{41A47C5B-C606-45B4-B83C-22B9239E4DA0}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CredentialManagement</RootNamespace>
<AssemblyName>GitHub.CredentialManagement</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
<BuildType Condition="Exists('..\..\script\src\ApiClientConfiguration.cs')">Internal</BuildType>
<OutputPath>bin\$(Configuration)\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="$(Buildtype) == 'Internal'">
<AssemblyOriginatorKeyFile>..\..\script\Key.snk</AssemblyOriginatorKeyFile>
<SignAssembly>true</SignAssembly>
<DelaySign>false</DelaySign>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(SolutionDir)common\SolutionInfo.cs">
<Link>Properties\SolutionInfo.cs</Link>
</Compile>
<Compile Include="Credential.cs" />
<Compile Include="CredentialSet.cs" />
<Compile Include="CredentialType.cs" />
<Compile Include="Guard.cs" />
<Compile Include="NativeMethods.cs" />
<Compile Include="PersistenceType.cs" />
<Compile Include="SecureStringHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
using GitHub.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
namespace GitHub.Authentication.CredentialManagement
{
public class CredentialSet : List<Credential>, IDisposable
{
public CredentialSet()
{
}
public CredentialSet(string target)
: this()
{
Guard.ArgumentNotEmptyString(target, nameof(target));
Target = target;
}
public string Target { get; set; }
bool disposed;
private void Dispose(bool disposing)
{
if (disposing)
{
if (disposed) return;
if (Count > 0)
{
ForEach(cred => cred.Dispose());
}
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public CredentialSet Load()
{
LoadInternal();
return this;
}
private void LoadInternal()
{
uint count;
IntPtr pCredentials;
bool result = NativeMethods.CredEnumerateW(Target, 0, out count, out pCredentials);
if (!result)
{
var lastError = Marshal.GetLastWin32Error();
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Win32Exception: {0}", new Win32Exception(lastError)));
return;
}
// Read in all of the pointers first
var ptrCredList = new IntPtr[count];
for (int i = 0; i < count; i++)
{
ptrCredList[i] = Marshal.ReadIntPtr(pCredentials, IntPtr.Size * i);
}
// Now let's go through all of the pointers in the list
// and create our Credential object(s)
var credentialHandles =
ptrCredList.Select(ptrCred => new NativeMethods.CriticalCredentialHandle(ptrCred)).ToList();
var existingCredentials = credentialHandles
.Select(handle => handle.GetCredential())
.Select(nativeCredential =>
{
Credential credential = new Credential();
credential.LoadInternal(nativeCredential);
return credential;
});
AddRange(existingCredentials);
// The individual credentials should not be free'd
credentialHandles.ForEach(handle => handle.SetHandleAsInvalid());
// Clean up memory to the Enumeration pointer
NativeMethods.CredFree(pCredentials);
}
}
}
\ No newline at end of file
using System.Diagnostics.CodeAnalysis;
namespace GitHub.Authentication.CredentialManagement
{
[SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32",
Justification = "This is a uint as required by the unmanaged API")]
public enum CredentialType : uint
{
None = 0,
Generic = 1,
DomainPassword = 2,
DomainCertificate = 3,
DomainVisiblePassword = 4
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace GitHub.Extensions
{
static class Guard
{
public static void ArgumentNotNull(object value, string name)
{
if (value != null) return;
string message = String.Format(CultureInfo.InvariantCulture, "Failed Null Check on '{0}'", name);
throw new ArgumentNullException(name, message);
}
public static void ArgumentNonNegative(int value, string name)
{
if (value > -1) return;
var message = String.Format(CultureInfo.InvariantCulture, "The value for '{0}' must be non-negative", name);
throw new ArgumentException(message, name);
}
/// <summary>
/// Checks a string argument to ensure it isn't null or empty.
/// </summary>
/// <param name = "value">The argument value to check.</param>
/// <param name = "name">The name of the argument.</param>
public static void ArgumentNotEmptyString(string value, string name)
{
if (value.Length > 0) return;
string message = String.Format(CultureInfo.InvariantCulture, "The value for '{0}' must not be empty", name);
throw new ArgumentException(message, name);
}
public static void ArgumentInRange(int value, int minValue, string name)
{
if (value >= minValue) return;
string message = String.Format(CultureInfo.InvariantCulture,
"The value '{0}' for '{1}' must be greater than or equal to '{2}'",
value,
name,
minValue);
throw new ArgumentOutOfRangeException(name, message);
}
public static void ArgumentInRange(int value, int minValue, int maxValue, string name)
{
if (value >= minValue && value <= maxValue) return;
string message = String.Format(CultureInfo.InvariantCulture,
"The value '{0}' for '{1}' must be greater than or equal to '{2}' and less than or equal to '{3}'",
value,
name,
minValue,
maxValue);
throw new ArgumentOutOfRangeException(name, message);
}
// Borrowed from Splat.
static bool InUnitTestRunner()
{
return false;
}
}
}
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace GitHub.Authentication.CredentialManagement
{
public static class NativeMethods
{
public const int CREDUI_MAX_USERNAME_LENGTH = 513;
public const int CREDUI_MAX_PASSWORD_LENGTH = 256;
public const int CREDUI_MAX_MESSAGE_LENGTH = 32767;
public const int CREDUI_MAX_CAPTION_LENGTH = 128;
[SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable"
, Justification = "This type needs to be this way for interop")]
[StructLayout(LayoutKind.Sequential)]
internal struct CREDENTIAL
{
public int Flags;
public int Type;
[MarshalAs(UnmanagedType.LPWStr)]
public string TargetName;
[MarshalAs(UnmanagedType.LPWStr)]
public string Comment;
public long LastWritten;
public int CredentialBlobSize;
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources"
, Justification = "Need to validate that SafeHandle works properly with native interop")]
public IntPtr CredentialBlob;
public int Persist;
public int AttributeCount;
public IntPtr Attributes;
[MarshalAs(UnmanagedType.LPWStr)]
public string TargetAlias;
[MarshalAs(UnmanagedType.LPWStr)]
public string UserName;
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes",
Justification = "This type is soley for native interop")]
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CREDUI_INFO
{
public int cbSize;
[SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible"
, Justification = "This is needed for native interop")]
public IntPtr hwndParent;
public string pszMessageText;
public string pszCaptionText;
[SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible"
, Justification = "This is needed for native interop")]
public IntPtr hbmBanner;
}
[Flags]
internal enum WINXP_CREDUI_FLAGS
{
INCORRECT_PASSWORD = 0x00001,
DO_NOT_PERSIST = 0x00002,
REQUEST_ADMINISTRATOR = 0x00004,
EXCLUDE_CERTIFICATES = 0x00008,
REQUIRE_CERTIFICATE = 0x00010,
SHOW_SAVE_CHECK_BOX = 0x00040,
ALWAYS_SHOW_UI = 0x00080,
REQUIRE_SMARTCARD = 0x00100,
PASSWORD_ONLY_OK = 0x00200,
VALIDATE_USERNAME = 0x00400,
COMPLETE_USERNAME = 0x00800,
PERSIST = 0x01000,
SERVER_CREDENTIAL = 0x04000,
EXPECT_CONFIRMATION = 0x20000,
GENERIC_CREDENTIALS = 0x40000,
USERNAME_TARGET_CREDENTIALS = 0x80000,
KEEP_USERNAME = 0x100000,
}
[Flags]
internal enum WINVISTA_CREDUI_FLAGS
{
/// <summary>
/// The caller is requesting that the credential provider return the user name and password in plain text.
/// This value cannot be combined with SECURE_PROMPT.
/// </summary>
CREDUIWIN_GENERIC = 0x1,
/// <summary>
/// The Save check box is displayed in the dialog box.
/// </summary>
CREDUIWIN_CHECKBOX = 0x2,
/// <summary>
/// Only credential providers that support the authentication package specified by the authPackage parameter should be enumerated.
/// This value cannot be combined with CREDUIWIN_IN_CRED_ONLY.
/// </summary>
CREDUIWIN_AUTHPACKAGE_ONLY = 0x10,
/// <summary>
/// Only the credentials specified by the InAuthBuffer parameter for the authentication package specified by the authPackage parameter should be enumerated.
/// If this flag is set, and the InAuthBuffer parameter is NULL, the function fails.
/// This value cannot be combined with CREDUIWIN_AUTHPACKAGE_ONLY.
/// </summary>
CREDUIWIN_IN_CRED_ONLY = 0x20,
/// <summary>
/// Credential providers should enumerate only administrators. This value is intended for User Account Control (UAC) purposes only. We recommend that external callers not set this flag.
/// </summary>
CREDUIWIN_ENUMERATE_ADMINS = 0x100,
/// <summary>
/// Only the incoming credentials for the authentication package specified by the authPackage parameter should be enumerated.
/// </summary>
CREDUIWIN_ENUMERATE_CURRENT_USER = 0x200,
/// <summary>
/// The credential dialog box should be displayed on the secure desktop. This value cannot be combined with CREDUIWIN_GENERIC.
/// Windows Vista: This value is not supported until Windows Vista with SP1.
/// </summary>
CREDUIWIN_SECURE_PROMPT = 0x1000,
/// <summary>
/// The credential provider should align the credential BLOB pointed to by the refOutAuthBuffer parameter to a 32-bit boundary, even if the provider is running on a 64-bit system.
/// </summary>
CREDUIWIN_PACK_32_WOW = 0x10000000,
}
internal enum CredUIReturnCodes
{
NO_ERROR = 0,
ERROR_CANCELLED = 1223,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_NOT_FOUND = 1168,
ERROR_INVALID_ACCOUNT_NAME = 1315,
ERROR_INSUFFICIENT_BUFFER = 122,
ERROR_BAD_ARGUMENTS = 160,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
}
internal enum CREDErrorCodes
{
NO_ERROR = 0,
ERROR_NOT_FOUND = 1168,
ERROR_NO_SUCH_LOGON_SESSION = 1312,
ERROR_INVALID_PARAMETER = 87,
ERROR_INVALID_FLAGS = 1004,
ERROR_BAD_USERNAME = 2202,
SCARD_E_NO_READERS_AVAILABLE = (int)(0x8010002E - 0x100000000),
SCARD_E_NO_SMARTCARD = (int)(0x8010000C - 0x100000000),
SCARD_W_REMOVED_CARD = (int)(0x80100069 - 0x100000000),
SCARD_W_WRONG_CHV = (int)(0x8010006B - 0x100000000)
}
[DllImport("Advapi32.dll", EntryPoint = "CredReadW", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredRead(string target, CredentialType type, int reservedFlag, out IntPtr CredentialPtr);
[DllImport("Advapi32.dll", EntryPoint = "CredWriteW", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredWrite([In] ref CREDENTIAL userCredential, [In] UInt32 flags);
[DllImport("Advapi32.dll", EntryPoint = "CredFree", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredFree([In] IntPtr cred);
[DllImport("advapi32.dll", EntryPoint = "CredDeleteW", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredDelete(StringBuilder target, CredentialType type, int flags);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredEnumerateW(string filter, int flag, out uint count, out IntPtr pCredentials);
[DllImport("credui.dll", CharSet = CharSet.Unicode)]
internal static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR, string targetName, IntPtr reserved1, int iError, StringBuilder userName, int maxUserName, StringBuilder password, int maxPassword, [MarshalAs(UnmanagedType.Bool)] ref bool pfSave, int flags);
[DllImport("credui.dll", CharSet = CharSet.Unicode)]
internal static extern CredUIReturnCodes CredUIPromptForWindowsCredentials(ref CREDUI_INFO notUsedHere, int authError, ref uint authPackage, IntPtr InAuthBuffer, uint InAuthBufferSize, out IntPtr refOutAuthBuffer, out uint refOutAuthBufferSize, [MarshalAs(UnmanagedType.Bool)]ref bool fSave, int flags);
[DllImport("ole32.dll")]
internal static extern void CoTaskMemFree(IntPtr ptr);
[DllImport("credui.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredPackAuthenticationBuffer(int dwFlags, StringBuilder pszUserName, StringBuilder pszPassword, IntPtr pPackedCredentials, ref int pcbPackedCredentials);
[DllImport("credui.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CredUnPackAuthenticationBuffer(int dwFlags, IntPtr pAuthBuffer, uint cbAuthBuffer, StringBuilder pszUserName, ref int pcchMaxUserName, StringBuilder pszDomainName, ref int pcchMaxDomainame, StringBuilder pszPassword, ref int pcchMaxPassword);
internal sealed class CriticalCredentialHandle : CriticalHandleZeroOrMinusOneIsInvalid
{
// Set the handle.
internal CriticalCredentialHandle(IntPtr preexistingHandle)
{
SetHandle(preexistingHandle);
}
internal CREDENTIAL GetCredential()
{
if (!IsInvalid)
{
// Get the Credential from the mem location
return (CREDENTIAL)Marshal.PtrToStructure(handle, typeof(CREDENTIAL));
}
else
{
throw new InvalidOperationException("Invalid CriticalHandle!");
}
}
// Perform any specific actions to release the handle in the ReleaseHandle method.
// Often, you need to use Pinvoke to make a call into the Win32 API to release the
// handle. In this case, however, we can use the Marshal class to release the unmanaged memory.
override protected bool ReleaseHandle()
{
// If the handle was set, free it. Return success.
if (!IsInvalid)
{
// NOTE: We should also ZERO out the memory allocated to the handle, before free'ing it
// so there are no traces of the sensitive data left in memory.
CredFree(handle);
// Mark the handle as invalid for future users.
SetHandleAsInvalid();
return true;
}
// Return false.
return false;
}
}
}
}
using System.Diagnostics.CodeAnalysis;
namespace GitHub.Authentication.CredentialManagement
{
[SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32"
, Justification = "This is this way for interop")]
[SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue"
, Justification = "I assume this is defined this way for Native interop")]
public enum PersistenceType : uint
{
Session = 1,
LocalComputer = 2,
Enterprise = 3
}
}
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GitHub.CredentialManagement")]
[assembly: AssemblyDescription("GitHub CredentialManagement")]
[assembly: Guid("41a47c5b-c606-45b4-b83c-22b9239e4da0")]
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace GitHub.Authentication.CredentialManagement
{
[SuppressUnmanagedCodeSecurity]
internal static class SecureStringHelper
{
// Methods
internal static SecureString CreateSecureString(string plainString)
{
var str = new SecureString();
if (!string.IsNullOrEmpty(plainString))
{
foreach (char c in plainString)
{
str.AppendChar(c);
}
}
return str;
}
internal static string CreateString(SecureString secureString)
{
string str;
var zero = IntPtr.Zero;
if ((secureString == null) || (secureString.Length == 0))
{
return string.Empty;
}
try
{
zero = Marshal.SecureStringToBSTR(secureString);
str = Marshal.PtrToStringBSTR(zero);
}
finally
{
if (zero != IntPtr.Zero)
{
Marshal.ZeroFreeBSTR(zero);
}
}
return str;
}
}
}
using System.Threading.Tasks;
using GitHub.Primitives;
using Octokit;
using System;
namespace GitHub.Api
{
public interface ISimpleApiClient
{
HostAddress HostAddress { get; }
UriString OriginalUrl { get; }
Task GetRepository(Action<Repository> callback);
}
}
using GitHub.Primitives;
namespace GitHub.Api
{
public interface ISimpleApiClientFactory
{
ISimpleApiClient Create(UriString repositoryUrl);
void ClearFromCache(ISimpleApiClient client);
}
}
namespace GitHub.Authentication
{
enum AuthenticationResult
{
/// <summary>
/// Could not authenticate using the credentials provided.
/// </summary>
CredentialFailure,
/// <summary>
/// The two factor authentication challenge failed.
/// </summary>
VerificationFailure,
/// <summary>
/// The given remote Uri is not an enterprise Uri.
/// </summary>
EnterpriseServerNotFound,
/// <summary>
/// Aaaawwww yeeeaah
/// </summary>
Success
}
}
namespace GitHub.Authentication
{
static class AuthenticationResultExtensions
{
public static bool IsFailure(this AuthenticationResult result)
{
return result != AuthenticationResult.Success;
}
public static bool IsSuccess(this AuthenticationResult result)
{
return result == AuthenticationResult.Success;
}
}
}
namespace GitHub.Api
{
sealed class Credential : ICredential
{
public Credential(string host)
{
this.Host = host;
}
public ICredential Set(string key, string value)
{
Key = key;
Value = value;
return this;
}
public string Host { get; private set; }
public string Key { get; private set; }
public string Value { get; private set; }
private bool disposed = false;
void Dispose(bool disposing)
{
if (disposing)
{
if (!disposed)
{
disposed = true;
Value = null;
}
}
}
public void Dispose()
{
Dispose(true);
}
}
}
\ No newline at end of file
namespace GitHub.Api
{
public interface IBackendFactory
{
ICredentialManager CredentialManager { get; }
}
}
\ No newline at end of file
using System;
namespace GitHub.Api
{
public interface ICredential : IDisposable
{
string Host { get; }
string Key { get; }
string Value { get; }
}
public interface ICredentialManager
{
ICredential Load(string key);
void Save(ICredential credential);
void Delete(ICredential credential);
}
}
\ No newline at end of file
using System;
using Octokit;
using System.Threading;
namespace GitHub.Extensions
{
static class ApiExceptionExtensions
{
const string GithubHeader = "X-GitHub-Request-Id";
public static bool IsGitHubApiException(this Exception ex)
{
var apiex = ex as ApiException;
return apiex?.HttpResponse?.Headers.ContainsKey(GithubHeader) ?? false;
}
}
static class ExceptionExtensions
{
/// <summary>
/// Represents exceptions we should never attempt to catch and ignore.
/// </summary>
/// <param name="exception">The exception being thrown.</param>
/// <returns></returns>
public static bool IsCriticalException(this Exception exception)
{
if (exception == null)
{
throw new ArgumentNullException("exception");
}
return exception.IsFatalException()
|| exception is AppDomainUnloadedException
|| exception is BadImageFormatException
|| exception is CannotUnloadAppDomainException
|| exception is InvalidProgramException
|| exception is NullReferenceException
|| exception is ArgumentException;
}
/// <summary>
/// Represents exceptions we should never attempt to catch and ignore when executing third party plugin code.
/// This is not as extensive as a proposed IsCriticalException method that I want to write for our own code.
/// </summary>
/// <param name="exception">The exception being thrown.</param>
/// <returns></returns>
public static bool IsFatalException(this Exception exception)
{
if (exception == null)
{
throw new ArgumentNullException("exception");
}
return exception is StackOverflowException
|| exception is OutOfMemoryException
|| exception is ThreadAbortException
|| exception is AccessViolationException;
}
public static bool CanRetry(this Exception exception)
{
return !exception.IsCriticalException()
&& !(exception is ObjectDisposedException);
}
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment