|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Threading.Tasks; |
| 5 | +using GitCredentialManager; |
| 6 | +using GitCredentialManager.Authentication.OAuth; |
| 7 | +using System.Net.Http.Headers; |
| 8 | + |
| 9 | +namespace Gitea |
| 10 | +{ |
| 11 | + public class GiteaHostProvider : HostProvider |
| 12 | + { |
| 13 | + private static readonly string[] GiteaOAuthScopes = |
| 14 | + { |
| 15 | + }; |
| 16 | + |
| 17 | + private readonly IGiteaAuthentication _giteaAuth; |
| 18 | + |
| 19 | + public GiteaHostProvider(ICommandContext context) |
| 20 | + : this(context, new GiteaAuthentication(context)) { } |
| 21 | + |
| 22 | + public GiteaHostProvider(ICommandContext context, IGiteaAuthentication giteaAuth) |
| 23 | + : base(context) |
| 24 | + { |
| 25 | + EnsureArgument.NotNull(giteaAuth, nameof(giteaAuth)); |
| 26 | + |
| 27 | + _giteaAuth = giteaAuth; |
| 28 | + } |
| 29 | + |
| 30 | + public override string Id => "gitea"; |
| 31 | + |
| 32 | + public override string Name => "Gitea"; |
| 33 | + |
| 34 | + public override bool IsSupported(InputArguments input) |
| 35 | + { |
| 36 | + if (input is null) |
| 37 | + { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + // We do not support unencrypted HTTP communications to Gitea, |
| 42 | + // but we report `true` here for HTTP so that we can show a helpful |
| 43 | + // error message for the user in `CreateCredentialAsync`. |
| 44 | + if (!StringComparer.OrdinalIgnoreCase.Equals(input.Protocol, "http") && |
| 45 | + !StringComparer.OrdinalIgnoreCase.Equals(input.Protocol, "https")) |
| 46 | + { |
| 47 | + return false; |
| 48 | + } |
| 49 | + |
| 50 | + // Split port number and hostname from host input argument |
| 51 | + if (!input.TryGetHostAndPort(out string hostName, out _)) |
| 52 | + { |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + string[] domains = hostName.Split(new char[] { '.' }); |
| 57 | + |
| 58 | + // Gitea[.subdomain].domain.tld |
| 59 | + if (domains.Length >= 3 && |
| 60 | + StringComparer.OrdinalIgnoreCase.Equals(domains[0], "gitea")) |
| 61 | + { |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + return false; |
| 66 | + } |
| 67 | + |
| 68 | + public override bool IsSupported(HttpResponseMessage response) => |
| 69 | + response?.Headers.Any(pair => pair.Key == "Set-Cookie" && pair.Value.Any(x => x.Contains("i_like_gitea="))) ?? false; |
| 70 | + |
| 71 | + public override async Task<ICredential> GenerateCredentialAsync(InputArguments input) |
| 72 | + { |
| 73 | + ThrowIfDisposed(); |
| 74 | + |
| 75 | + Uri remoteUri = input.GetRemoteUri(); |
| 76 | + |
| 77 | + AuthenticationModes authModes = GetSupportedAuthenticationModes(remoteUri); |
| 78 | + |
| 79 | + AuthenticationPromptResult promptResult = _giteaAuth.GetAuthentication(remoteUri, input.UserName, authModes); |
| 80 | + |
| 81 | + switch (promptResult.AuthenticationMode) |
| 82 | + { |
| 83 | + case AuthenticationModes.Basic: |
| 84 | + case AuthenticationModes.Pat: |
| 85 | + return promptResult.Credential; |
| 86 | + |
| 87 | + case AuthenticationModes.Browser: |
| 88 | + return await GenerateOAuthCredentialAsync(input); |
| 89 | + |
| 90 | + default: |
| 91 | + throw new ArgumentOutOfRangeException(nameof(promptResult)); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + internal AuthenticationModes GetSupportedAuthenticationModes(Uri targetUri) |
| 96 | + { |
| 97 | + // Check for an explicit override for supported authentication modes |
| 98 | + if (Context.Settings.TryGetSetting( |
| 99 | + GiteaConstants.EnvironmentVariables.AuthenticationModes, |
| 100 | + Constants.GitConfiguration.Credential.SectionName, GiteaConstants.GitConfiguration.Credential.AuthenticationModes, |
| 101 | + out string authModesStr)) |
| 102 | + { |
| 103 | + if (Enum.TryParse(authModesStr, true, out AuthenticationModes authModes) && authModes != AuthenticationModes.None) |
| 104 | + { |
| 105 | + Context.Trace.WriteLine($"Supported authentication modes override present: {authModes}"); |
| 106 | + return authModes; |
| 107 | + } |
| 108 | + else |
| 109 | + { |
| 110 | + Context.Trace.WriteLine($"Invalid value for supported authentication modes override setting: '{authModesStr}'"); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + // Try to detect what auth modes are available for this non-Gitea.com host. |
| 115 | + // Assume that PATs are always available to give at least one option to users! |
| 116 | + var modes = AuthenticationModes.Pat; |
| 117 | + |
| 118 | + // If there is a configured OAuth client ID |
| 119 | + // then assume OAuth is possible. |
| 120 | + string oauthClientId = GiteaOAuth2Client.GetClientId(Context.Settings); |
| 121 | + if (oauthClientId != null) { |
| 122 | + modes |= AuthenticationModes.Browser; |
| 123 | + } else { |
| 124 | + // Tell the user that they may wish to configure OAuth for this Gitea instance |
| 125 | + Context.Streams.Error.WriteLine( |
| 126 | + $"warning: missing OAuth configuration for {targetUri.Host} - see {GiteaConstants.HelpUrls.Gitea} for more information"); |
| 127 | + } |
| 128 | + |
| 129 | + // assume password auth is always available. |
| 130 | + bool supportsBasic = true; |
| 131 | + if (supportsBasic) |
| 132 | + { |
| 133 | + modes |= AuthenticationModes.Basic; |
| 134 | + } |
| 135 | + |
| 136 | + return modes; |
| 137 | + } |
| 138 | + |
| 139 | + // <remarks>Stores OAuth tokens as a side effect</remarks> |
| 140 | + public override async Task<ICredential> GetCredentialAsync(InputArguments input) |
| 141 | + { |
| 142 | + string service = GetServiceName(input); |
| 143 | + ICredential credential = Context.CredentialStore.Get(service, input.UserName); |
| 144 | + if (credential?.Account == "oauth2" && IsOAuthTokenExpired(input.GetRemoteUri(), credential.Password)) |
| 145 | + { |
| 146 | + Context.Trace.WriteLine("Removing (possibly) expired OAuth access token..."); |
| 147 | + Context.CredentialStore.Remove(service, credential.Account); |
| 148 | + credential = null; |
| 149 | + } |
| 150 | + |
| 151 | + if (credential != null) |
| 152 | + { |
| 153 | + return credential; |
| 154 | + } |
| 155 | + |
| 156 | + string refreshService = GetRefreshTokenServiceName(input); |
| 157 | + string refreshToken = Context.CredentialStore.Get(refreshService, input.UserName)?.Password; |
| 158 | + if (refreshToken != null) |
| 159 | + { |
| 160 | + Context.Trace.WriteLine("Refreshing OAuth token..."); |
| 161 | + try |
| 162 | + { |
| 163 | + credential = await RefreshOAuthCredentialAsync(input, refreshToken); |
| 164 | + } |
| 165 | + catch (Exception e) |
| 166 | + { |
| 167 | + Context.Terminal.WriteLine($"OAuth token refresh failed: {e.Message}"); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + credential ??= await GenerateCredentialAsync(input); |
| 172 | + |
| 173 | + if (credential is OAuthCredential oAuthCredential) |
| 174 | + { |
| 175 | + Context.Trace.WriteLine("Pre-emptively storing OAuth access and refresh tokens..."); |
| 176 | + // freshly-generated OAuth credential |
| 177 | + // store credential, since we know it to be valid (whereas Git will only store credential if git push succeeds) |
| 178 | + Context.CredentialStore.AddOrUpdate(service, oAuthCredential.Account, oAuthCredential.AccessToken); |
| 179 | + // store refresh token under a separate service |
| 180 | + Context.CredentialStore.AddOrUpdate(refreshService, oAuthCredential.Account, oAuthCredential.RefreshToken); |
| 181 | + } |
| 182 | + return credential; |
| 183 | + } |
| 184 | + |
| 185 | + private bool IsOAuthTokenExpired(Uri baseUri, string accessToken) |
| 186 | + { |
| 187 | + return true; |
| 188 | + } |
| 189 | + |
| 190 | + internal class OAuthCredential : ICredential |
| 191 | + { |
| 192 | + public OAuthCredential(OAuth2TokenResult oAuth2TokenResult) |
| 193 | + { |
| 194 | + AccessToken = oAuth2TokenResult.AccessToken; |
| 195 | + RefreshToken = oAuth2TokenResult.RefreshToken; |
| 196 | + } |
| 197 | + |
| 198 | + public string Account => "oauth2"; |
| 199 | + public string AccessToken { get; } |
| 200 | + public string RefreshToken { get; } |
| 201 | + string ICredential.Password => AccessToken; |
| 202 | + } |
| 203 | + |
| 204 | + private async Task<OAuthCredential> GenerateOAuthCredentialAsync(InputArguments input) |
| 205 | + { |
| 206 | + OAuth2TokenResult result = await _giteaAuth.GetOAuthTokenViaBrowserAsync(input.GetRemoteUri(), GiteaOAuthScopes); |
| 207 | + return new OAuthCredential(result); |
| 208 | + } |
| 209 | + |
| 210 | + private async Task<OAuthCredential> RefreshOAuthCredentialAsync(InputArguments input, string refreshToken) |
| 211 | + { |
| 212 | + OAuth2TokenResult result = await _giteaAuth.GetOAuthTokenViaRefresh(input.GetRemoteUri(), refreshToken); |
| 213 | + return new OAuthCredential(result); |
| 214 | + } |
| 215 | + |
| 216 | + protected override void ReleaseManagedResources() |
| 217 | + { |
| 218 | + _giteaAuth.Dispose(); |
| 219 | + base.ReleaseManagedResources(); |
| 220 | + } |
| 221 | + |
| 222 | + private string GetRefreshTokenServiceName(InputArguments input) |
| 223 | + { |
| 224 | + var builder = new UriBuilder(GetServiceName(input)); |
| 225 | + builder.Host = "oauth-refresh-token." + builder.Host; |
| 226 | + return builder.Uri.ToString(); |
| 227 | + } |
| 228 | + |
| 229 | + public override Task EraseCredentialAsync(InputArguments input) |
| 230 | + { |
| 231 | + // delete any refresh token too |
| 232 | + Context.CredentialStore.Remove(GetRefreshTokenServiceName(input), "oauth2"); |
| 233 | + return base.EraseCredentialAsync(input); |
| 234 | + } |
| 235 | + } |
| 236 | +} |
0 commit comments