|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Specialized; |
| 6 | +using System.Net; |
| 7 | +using System.Net.Http.Headers; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using System.Web.Mvc; |
| 10 | +using NuGetGallery.Authentication; |
| 11 | +using NuGetGallery.Services.Authentication; |
| 12 | + |
| 13 | +#nullable enable |
| 14 | + |
| 15 | +namespace NuGetGallery |
| 16 | +{ |
| 17 | + public class CreateTokenRequest |
| 18 | + { |
| 19 | + public string? Username { get; set; } |
| 20 | + |
| 21 | + public string? TokenType { get; set; } |
| 22 | + } |
| 23 | + |
| 24 | + public class TokenApiController : AppController |
| 25 | + { |
| 26 | + public static readonly string ControllerName = nameof(TokenApiController).Replace("Controller", string.Empty); |
| 27 | + private const string JsonContentType = "application/json"; |
| 28 | + private const string ApiKeyTokenType = "ApiKey"; |
| 29 | + private const string BearerScheme = "Bearer"; |
| 30 | + private const string BearerPrefix = $"{BearerScheme} "; |
| 31 | + private const string AuthorizationHeaderName = "Authorization"; |
| 32 | + |
| 33 | + private readonly IFederatedCredentialService _federatedCredentialService; |
| 34 | + private readonly IFederatedCredentialConfiguration _configuration; |
| 35 | + |
| 36 | + public TokenApiController( |
| 37 | + IFederatedCredentialService federatedCredentialService, |
| 38 | + IFederatedCredentialConfiguration configuration) |
| 39 | + { |
| 40 | + _federatedCredentialService = federatedCredentialService ?? throw new ArgumentNullException(nameof(federatedCredentialService)); |
| 41 | + _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); |
| 42 | + } |
| 43 | + |
| 44 | +#pragma warning disable CA3147 // No need to validate Antiforgery Token with API request |
| 45 | + [HttpPost] |
| 46 | + [ActionName(RouteName.CreateToken)] |
| 47 | + [AllowAnonymous] // authentication is handled inside the action |
| 48 | + public async Task<ActionResult> CreateToken(CreateTokenRequest request) |
| 49 | +#pragma warning restore CA3147 // No need to validate Antiforgery Token with API request |
| 50 | + { |
| 51 | + if (!_configuration.EnableTokenApi) |
| 52 | + { |
| 53 | + return HttpNotFound(); |
| 54 | + } |
| 55 | + |
| 56 | + if (!TryGetBearerToken(Request.Headers, out var bearerToken, out var errorMessage)) |
| 57 | + { |
| 58 | + return UnauthorizedJson(errorMessage!); |
| 59 | + } |
| 60 | + |
| 61 | + if (User.Identity.IsAuthenticated) |
| 62 | + { |
| 63 | + return UnauthorizedJson("Only Bearer token authentication is accepted."); |
| 64 | + } |
| 65 | + |
| 66 | + if (!MediaTypeWithQualityHeaderValue.TryParse(Request.ContentType, out var parsed) |
| 67 | + || !string.Equals(parsed.MediaType, JsonContentType, StringComparison.OrdinalIgnoreCase)) |
| 68 | + { |
| 69 | + return ErrorJson(HttpStatusCode.UnsupportedMediaType, $"The request must have a Content-Type of '{JsonContentType}'."); |
| 70 | + } |
| 71 | + |
| 72 | + if (string.IsNullOrWhiteSpace(Request.UserAgent)) |
| 73 | + { |
| 74 | + return ErrorJson(HttpStatusCode.BadRequest, "A User-Agent header is required."); |
| 75 | + } |
| 76 | + |
| 77 | + if (string.IsNullOrWhiteSpace(request?.Username)) |
| 78 | + { |
| 79 | + return ErrorJson(HttpStatusCode.BadRequest, "The username property in the request body is required."); |
| 80 | + } |
| 81 | + |
| 82 | + if (request?.TokenType != ApiKeyTokenType) |
| 83 | + { |
| 84 | + return ErrorJson(HttpStatusCode.BadRequest, $"The tokenType property in the request body is required and must set to '{ApiKeyTokenType}'."); |
| 85 | + } |
| 86 | + |
| 87 | + var result = await _federatedCredentialService.GenerateApiKeyAsync(request!.Username!, bearerToken!, Request.Headers); |
| 88 | + |
| 89 | + return result.Type switch |
| 90 | + { |
| 91 | + GenerateApiKeyResultType.BadRequest => ErrorJson(HttpStatusCode.BadRequest, result.UserMessage), |
| 92 | + GenerateApiKeyResultType.Unauthorized => UnauthorizedJson(result.UserMessage), |
| 93 | + GenerateApiKeyResultType.Created => ApiKeyJson(result), |
| 94 | + _ => throw new NotImplementedException($"Unexpected result type: {result.Type}"), |
| 95 | + }; |
| 96 | + } |
| 97 | + |
| 98 | + private JsonResult ApiKeyJson(GenerateApiKeyResult result) |
| 99 | + { |
| 100 | + return Json(HttpStatusCode.OK, new |
| 101 | + { |
| 102 | + tokenType = ApiKeyTokenType, |
| 103 | + expires = result.Expires.ToString("O"), |
| 104 | + apiKey = result.PlaintextApiKey, |
| 105 | + }); |
| 106 | + } |
| 107 | + |
| 108 | + private JsonResult UnauthorizedJson(string errorMessage) |
| 109 | + { |
| 110 | + // Add the "Federated" challenge so the other authentication providers (such as the default sign-in) are not triggered. |
| 111 | + OwinContext.Authentication.Challenge(AuthenticationTypes.Federated); |
| 112 | + |
| 113 | + Response.Headers["WWW-Authenticate"] = BearerScheme; |
| 114 | + |
| 115 | + return ErrorJson(HttpStatusCode.Unauthorized, errorMessage); |
| 116 | + } |
| 117 | + |
| 118 | + private JsonResult ErrorJson(HttpStatusCode status, string errorMessage) |
| 119 | + { |
| 120 | + // Show the error message in the HTTP reason phrase (status description) for compatibility with NuGet client error "protocol". |
| 121 | + // This, and the response body below, could be formalized with https://github.com/NuGet/NuGetGallery/issues/5818 |
| 122 | + Response.StatusDescription = errorMessage; |
| 123 | + |
| 124 | + return Json(status, new { error = errorMessage }); |
| 125 | + } |
| 126 | + |
| 127 | + private static bool TryGetBearerToken(NameValueCollection requestHeaders, out string? bearerToken, out string? errorMessage) |
| 128 | + { |
| 129 | + var authorizationHeaders = requestHeaders.GetValues(AuthorizationHeaderName); |
| 130 | + if (authorizationHeaders is null || authorizationHeaders.Length == 0) |
| 131 | + { |
| 132 | + bearerToken = null; |
| 133 | + errorMessage = $"The {AuthorizationHeaderName} header is missing."; |
| 134 | + return false; |
| 135 | + } |
| 136 | + |
| 137 | + if (authorizationHeaders.Length > 1) |
| 138 | + { |
| 139 | + bearerToken = null; |
| 140 | + errorMessage = $"Only one {AuthorizationHeaderName} header is allowed."; |
| 141 | + return false; |
| 142 | + } |
| 143 | + |
| 144 | + var authorizationHeader = authorizationHeaders[0]; |
| 145 | + if (!authorizationHeader.StartsWith(BearerPrefix, StringComparison.OrdinalIgnoreCase)) |
| 146 | + { |
| 147 | + bearerToken = null; |
| 148 | + errorMessage = $"The {AuthorizationHeaderName} header value must start with '{BearerPrefix}'."; |
| 149 | + return false; |
| 150 | + } |
| 151 | + |
| 152 | + const string missingToken = $"The bearer token is missing from the {AuthorizationHeaderName} header."; |
| 153 | + |
| 154 | + if (authorizationHeader.Length <= BearerPrefix.Length) |
| 155 | + { |
| 156 | + bearerToken = null; |
| 157 | + errorMessage = missingToken; |
| 158 | + return false; |
| 159 | + } |
| 160 | + |
| 161 | + bearerToken = authorizationHeader.Substring(BearerPrefix.Length); |
| 162 | + if (string.IsNullOrWhiteSpace(bearerToken)) |
| 163 | + { |
| 164 | + bearerToken = null; |
| 165 | + errorMessage = missingToken; |
| 166 | + return false; |
| 167 | + } |
| 168 | + |
| 169 | + bearerToken = bearerToken.Trim(); |
| 170 | + errorMessage = null; |
| 171 | + return true; |
| 172 | + } |
| 173 | + } |
| 174 | +} |
0 commit comments